code stringlengths 2 1.05M |
|---|
var healthStore = HKHealthStore.alloc().jsinit();
/*****************************************************************
* Name : onRowClick_FrmHomeMenu
* Author : Kony
* Purpose : Based on the row index , Navigate to respective form.
******************************************************************/
function onRowClick_FrmHomeMenu(rowIndex)
{
var selectedIndex = rowIndex;
if(selectedIndex == 0)
body.show();
else if(selectedIndex == 1)
fitness.show();
else if (selectedIndex == 2)
vitalsigns.show();
else if (selectedIndex == 3)
results.show();
else if(selectedIndex == 4)
nutrition.show();
else
characteristics.show();
}
/*****************************************************************
* Name : initAuthBody
* Author : Kony
* Purpose : This method requesta authorization from Native Health app to read/share body measurements.
******************************************************************/
function initAuthBody() {
var available = HKHealthStore.isHealthDataAvailable();
var heightType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight);
var weightType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass);
var bodyMassIndex = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex);
var bodyFatPercentage = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyFatPercentage);
var leanBodyMass = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierLeanBodyMass);
var dataTypesToRead = [heightType, weightType, bodyMassIndex, bodyFatPercentage, leanBodyMass];
var dataTypes = NSSet.setWithArray(dataTypesToRead);
if (available) {
healthStore.requestAuthorizationToShareTypesReadTypesCompletion(dataTypes, dataTypes, authCallback);
}
}
/*****************************************************************
* Name : initNutritionAuth
* Author : Kony
* Purpose : This method requesta authorization from Mative Health app to read/share nutrition details.
******************************************************************/
function initNutritionAuth() {
var available = HKHealthStore.isHealthDataAvailable();
var idDietaryBiotin = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryBiotin);
var idDietaryCaffeine = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCaffeine);
var idDietaryCalcium = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCalcium);
var idDietaryCarbohydrates = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates);
var idDietaryChloride = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryChloride);
var idDietaryCholesterol = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol);
var idDietaryChromium = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryChromium);
var idDietaryCopper = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCopper);
var idDietaryEnergyConsumed = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed);
var idDietaryFatMonounsaturated = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatMonounsaturated);
var idDietaryFatPolyunsaturated = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatPolyunsaturated);
var idDietaryFatSaturated = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatSaturated);
var idDietaryFatTotal = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal);
var idDietaryFiber = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFiber);
var idDietaryFolate = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFolate);
var idDietaryIodine = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryIodine);
var idDietaryIron = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryIron);
var idDietaryMagnesium = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryMagnesium);
var idDietaryManganese = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryManganese);
var idDietaryMolybdenum = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryMolybdenum);
var idDietaryNiacin = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryNiacin);
var idDietaryPantothenicAcid = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryPantothenicAcid);
var idDietaryPhosphorus = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryPhosphorus);
var idDietaryPotassium = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryPotassium);
var idDietaryProtein = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein);
var idDietaryRiboflavin = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryRiboflavin);
var idDietarySelenium = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySelenium);
var idDietarySodium = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySodium);
var idDietarySugar = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar);
var idDietaryThiamin = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryThiamin);
var idDietaryVitaminA = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminA);
var idDietaryVitaminB12 = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminB12);
var idDietaryVitaminB6 = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminB6);
var idDietaryVitaminC = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminC);
var idDietaryVitaminD = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminD);
var idDietaryVitaminE = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminE);
var idDietaryVitaminK = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminK);
var idDietaryZinc = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryZinc);
var dataTypesToRead = [idDietaryBiotin, idDietaryCaffeine, idDietaryCalcium, idDietaryCarbohydrates, idDietaryChloride, idDietaryCholesterol, idDietaryChromium, idDietaryCopper, idDietaryEnergyConsumed, idDietaryFatMonounsaturated, idDietaryFatPolyunsaturated, idDietaryFatSaturated, idDietaryFatTotal, idDietaryFiber, idDietaryFolate, idDietaryIodine, idDietaryIron, idDietaryMagnesium, idDietaryManganese, idDietaryMolybdenum, idDietaryNiacin, idDietaryPantothenicAcid, idDietaryPhosphorus, idDietaryPotassium, idDietaryProtein, idDietaryRiboflavin, idDietarySelenium, idDietarySodium, idDietarySugar, idDietaryThiamin, idDietaryVitaminA, idDietaryVitaminB12, idDietaryVitaminB6, idDietaryVitaminC, idDietaryVitaminD, idDietaryVitaminE, idDietaryVitaminK, idDietaryZinc];
var dataTypes = NSSet.setWithArray(dataTypesToRead);
if (available) {
healthStore.requestAuthorizationToShareTypesReadTypesCompletion(dataTypes, dataTypes, authCallback);
}
}
/*****************************************************************
* Name : initAuthFitness
* Author : Kony
* Purpose : This method requesta authorization from Mative Health app to read/share fitness details.
******************************************************************/
function initAuthFitness() {
print("Im Here");
var available = HKHealthStore.isHealthDataAvailable();
var stepCount = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount);
var walking = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning);
var cycling = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceCycling);
var basalEnergy = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBasalEnergyBurned);
var activeEnergy = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned);
var flightsClimbed = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierFlightsClimbed);
print("Im Here 1");
var nikeFuel = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierNikeFuel);
var dataTypesToRead = [stepCount, walking, cycling, basalEnergy, activeEnergy, flightsClimbed];
var dataTypesToWrite = [stepCount, walking, cycling, basalEnergy, activeEnergy, flightsClimbed, nikeFuel];
var dataTypesR = NSSet.setWithArray(dataTypesToRead);
var dataTypesW = NSSet.setWithArray(dataTypesToWrite);
print("Im Here 2");
if (available) {
healthStore.requestAuthorizationToShareTypesReadTypesCompletion(dataTypesR, dataTypesW, authCallback);
}
print("Im Here 3");
}
/*****************************************************************
* Name : initAuthVitalSigns
* Author : Kony
* Purpose : This method requesta authorization from Mative Health app to read/share vital sign details.
******************************************************************/
function initAuthVitalSigns() {
print("Im Init Auth VitalSigns");
var available = HKHealthStore.isHealthDataAvailable();
var idHeartRate = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate);
var idBodyTemperature = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyTemperature);
var idBloodPressureSystolic = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureSystolic);
var idBloodPressureDiastolic = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureDiastolic);
var idRespiratoryRate = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierRespiratoryRate);
var dataTypesToRead = [idHeartRate, idBodyTemperature, idBloodPressureSystolic, idBloodPressureDiastolic, idRespiratoryRate];
var dataTypes = NSSet.setWithArray(dataTypesToRead);
if (available) {
healthStore.requestAuthorizationToShareTypesReadTypesCompletion(dataTypes, dataTypes, authCallback);
}
}
/*****************************************************************
* Name : initAuthResults
* Author : Kony
* Purpose : This method requesta authorization from Mative Health app to read/share result details.
******************************************************************/
function initAuthResults() {
print("Im Init Auth Result");
var available = HKHealthStore.isHealthDataAvailable();
var idOxygenSaturation = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierOxygenSaturation);
var idPeripheralPerfusionIndex = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierPeripheralPerfusionIndex);
var idBloodGlucose = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose);
var idNumberOfTimesFallen = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierNumberOfTimesFallen);
var idElectrodermalActivity = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierElectrodermalActivity);
var idInhalerUsage = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierInhalerUsage);
var idBloodAlcoholContent = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodAlcoholContent);
var idForcedVitalCapacity = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierForcedVitalCapacity);
var idForcedExpiratoryVolume1 = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierForcedExpiratoryVolume1);
var idPeakExpiratoryFlowRate = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierPeakExpiratoryFlowRate);
var dataTypesToRead = [idOxygenSaturation, idPeripheralPerfusionIndex, idBloodGlucose, idNumberOfTimesFallen, idElectrodermalActivity, idInhalerUsage, idBloodAlcoholContent, idForcedVitalCapacity, idForcedExpiratoryVolume1, idPeakExpiratoryFlowRate];
var dataTypes = NSSet.setWithArray(dataTypesToRead);
if (available) {
healthStore.requestAuthorizationToShareTypesReadTypesCompletion(dataTypes, dataTypes, authCallback);
}
}
/*****************************************************************
* Name : initAuthCharacteristics
* Author : Kony
* Purpose : This method requesta authorization from Native Health app to read/share characteristics.
******************************************************************/
function initAuthCharacteristics() {
print("Im Init Auth Characteristics");
var available = HKHealthStore.isHealthDataAvailable();
var s1 = HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex);
var s2 = HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType);
var s3 = HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth);
var dataTypesToRead = [s1,s2,s3];
var dataTypes = NSSet.setWithArray(dataTypesToRead);
if (available) {
healthStore.requestAuthorizationToShareTypesReadTypesCompletion(null, dataTypes, authCallback);
}
}
/*****************************************************************
* Name : authCallback
* Author : Kony
* Purpose : This callback will get invoked on all authorization requests like body measurements etc.
******************************************************************/
function authCallback(success, errorObj) {
if (success) {
kony.print("Healthkit permissions granted");
} else {
kony.print("Sorry! You do not have permissions to access Healthkit data: " + errorObj.error);
}
}
/*****************************************************************
* Name : getSample
* Author : Kony
* Purpose : To get sample of a particular field for example height
******************************************************************/
function getSample(hkQuantityIdentifier, unitType, unitValue, startDate, endDate, metaData) {
var identifierType = HKObjectType.quantityTypeForIdentifier(hkQuantityIdentifier);
var identifierQuantity = HKQuantity.quantityWithUnitDoubleValue(unitType, unitValue);
return HKQuantitySample.quantitySampleWithTypeQuantityStartDateEndDateMetadata(identifierType, identifierQuantity, startDate, endDate, metaData);
}
function getSampleCategory(hkQuantityIdentifier, unitType, startDate, endDate, metaData) {
print("2");
var identifierType = HKObjectType.categoryTypeForIdentifier(hkQuantityIdentifier);
print("3");
//var identifierQuantity = HKQuantity.quantityWithUnitDoubleValue(unitType, unitValue);
print("4");
return HKCategorySample.categorySampleWithTypeValueStartDateEndDateMetadata(identifierType, unitType, startDate, endDate, metaData);
}
/*****************************************************************
* Name : executeQueryLimitSortDescriptors
* Author : Kony
* Purpose : Execute query to read a field value from native health app for example height.
******************************************************************/
function executeQueryLimitSortDescriptors(hkQuantityIdentifier, isAscend, sortIdentifierEndDate, resultHandler) {
var identifierType = HKQuantityType.quantityTypeForIdentifier(hkQuantityIdentifier);
// Since we are interested in retrieving the user's latest sample
// we sort the samples in descending order by end date
// and set the limit to 1
var timeSortDescriptor = NSSortDescriptor.alloc().initWithKeyAscending(sortIdentifierEndDate, isAscend);
var sortDescriptors = [timeSortDescriptor];
// construct the query & since we are not filtering the data the predicate is set to null
var query = HKSampleQuery.alloc().initWithSampleTypePredicateLimitSortDescriptorsResultsHandler(identifierType, null, 1, sortDescriptors, resultHandler);
// do not forget to execute the query after its constructed
healthStore.executeQuery(query);
}
function executeQueryLimitSortDescriptorsCategory(hkQuantityIdentifier, isAscend, sortIdentifierEndDate, resultHandler) {
var identifierType = HKQuantityType.categoryTypeForIdentifier(hkQuantityIdentifier);
// Since we are interested in retrieving the user's latest sample
// we sort the samples in descending order by end date
// and set the limit to 1
var timeSortDescriptor = NSSortDescriptor.alloc().initWithKeyAscending(sortIdentifierEndDate, isAscend);
var sortDescriptors = [timeSortDescriptor];
print("executeQueryLimitSortDescriptorsCategory")
// construct the query & since we are not filtering the data the predicate is set to null
var query = HKSampleQuery.alloc().initWithSampleTypePredicateLimitSortDescriptorsResultsHandler(identifierType, null, 1, sortDescriptors, resultHandler);
// do not forget to execute the query after its constructed
print("2"+healthStore)
healthStore.executeQuery(query);
} |
const assert = require('assert')
function assertErrorMessage(...args) {
const report = args[0]
let index
let message
if (args.length === 3) {
index = args[1]
message = args[2]
} else {
index = 0
message = args[1]
}
const errorMessage = `Report should contain message with text "${message}" at ${index} pos. ${printReport(
report
)}`
assert.ok(report.messages[index].message.includes(message), errorMessage)
}
function assertNoErrors(report) {
assert.equal(report.errorCount, 0, `Report must not contain errors. ${printReport(report)}`)
}
function assertNoWarnings(report) {
assert.equal(report.warningCount, 0, `Report must not contain warnings. ${printReport(report)}`)
}
function assertErrorCount(report, count) {
assert.equal(
report.errorCount,
count,
`Report must contains ${count} errors. ${printReport(report)}`
)
}
function assertWarnsCount(report, count) {
assert.equal(
report.warningCount,
count,
`Report must contains ${count} warnings. ${printReport(report)}`
)
}
function assertLineNumber(report, line) {
assert.equal(report.line, line, `Report must be in line ${line}.`)
}
function printReport(report) {
const messages = report.messages.map((i, index) => `${index + 1}. ${i.message}`)
return ['Errors / Warnings:', ...messages, ''].join('\n' + ' '.repeat(8))
}
module.exports = {
assertErrorMessage,
assertNoWarnings,
assertNoErrors,
assertErrorCount,
assertWarnsCount,
assertLineNumber
}
|
document.write('<h1>Hello World</h1>'); |
import { UserIsAuthenticated } from 'utils/router'
export default UserIsAuthenticated // redirect to /login if user is not authenticated
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/sql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sql_highlight_rules', 'ace/range'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var SqlHighlightRules = require("./sql_highlight_rules").SqlHighlightRules;
var Range = require("../range").Range;
var Mode = function() {
this.$tokenizer = new Tokenizer(new SqlHighlightRules().getRules());
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
var outentedRows = [];
var re = /^(\s*)--/;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "--");
}
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/sql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var SqlHighlightRules = function() {
var keywords = (
"select|from|where|and|or|group|by|order|limit|offset|having|as|case|" +
"when|else|end|type|left|right|join|on|outer|desc|asc"
);
var builtinConstants = (
"true|false|null"
);
var builtinFunctions = (
"count|min|max|avg|sum|rank|now|coalesce"
);
var keywordMapper = this.createKeywordMapper({
"support.function": builtinFunctions,
"keyword": keywords,
"constant.language": builtinConstants
}, "identifier", true);
this.$rules = {
"start" : [ {
token : "comment",
regex : "--.*$"
}, {
token : "string", // " string
regex : '".*?"'
}, {
token : "string", // ' string
regex : "'.*?'"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
}, {
token : "paren.lparen",
regex : "[\\(]"
}, {
token : "paren.rparen",
regex : "[\\)]"
}, {
token : "text",
regex : "\\s+"
} ]
};
};
oop.inherits(SqlHighlightRules, TextHighlightRules);
exports.SqlHighlightRules = SqlHighlightRules;
});
|
/*
* /MathJax/localization/cdo/HTML-CSS.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.
*/
MathJax.Localization.addTranslation("cdo","HTML-CSS",{version:"2.7.0",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/cdo/HTML-CSS.js");
|
module.exports = {
filter: require('./filter'),
includeCount: require('./include-count'),
pagination: require('./pagination'),
collision: require('./collision'),
transactionEvents: require('./transaction-events')
};
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.9.5_A36_T1;
* @section: 15.9.5;
* @assertion: The Date.prototype has the property "setDate";
* @description: The Date.prototype has the property "setDate";
*/
if(Date.prototype.hasOwnProperty("setDate") !== true){
$ERROR('#1: The Date.prototype has the property "setDate"');
}
|
'use strict';
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} fractionSize Number of decimal places to round the number to.
* If this is not provided then the fraction size is computed from the current locale's number
* formatting pattern. In the case of the default locale, it will be 3.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
numStr = '0';
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
} else {
if (fractionSize > 0 && number > -1 && number < 1) {
formatedText = number.toFixed(fractionSize);
}
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
offset = offset || 0;
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset();
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
sss: dateGetter('Milliseconds', 3),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\-?\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h 'o''clock'"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
// 1 2 3 4 5 6 7 8 9 10 11
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0,
dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
var h = int(match[4]||0) - tzHour;
var m = int(match[5]||0) - tzMin
var s = int(match[6]||0);
var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
var a = '1', b = 1;
b = a;
/***/ })
/******/ ]); |
import React from"react";import createSvgIcon from"./createSvgIcon";export default createSvgIcon(React.createElement("path",{d:"M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"}),"KeyboardArrowRight"); |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.11_A3_T4;
* @section: 12.11;
* @assertion: Syntax constructions of switch statement;
* @description: Using "case" that has no Expresson after it. "CaseClause: case Expression : [StatementList]";
* @negative;
*/
function SwitchTest(value){
var result = 0;
switch(value) {
case:
result += 2;
default:
result += 32;
break;
}
return result;
}
var x = SwitchTest(0);
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.7.1_A3_T2.7;
* @section: 11.7.1;
* @assertion: Operator x << y returns ToNumber(x) << ToNumber(y);
* @description: Type(x) is different from Type(y) and both types vary between String (primitive or object) and Null;
*/
//CHECK#1
if ("1" << null !== 1) {
$ERROR('#1: "1" << null === 1. Actual: ' + ("1" << null));
}
//CHECK#2
if (null << "1" !== 0) {
$ERROR('#2: null << "1" === 0. Actual: ' + (null << "1"));
}
//CHECK#3
if (new String("1") << null !== 1) {
$ERROR('#3: new String("1") << null === 1. Actual: ' + (new String("1") << null));
}
//CHECK#4
if (null << new String("1") !== 0) {
$ERROR('#4: null << new String("1") === 0. Actual: ' + (null << new String("1")));
}
|
angular.module('merchello.resources').factory('backOfficeCheckoutResource',
['$http', '$q', 'umbRequestHelper', 'customerItemCacheDisplayBuilder', 'invoiceDisplayBuilder', 'shipmentRateQuoteDisplayBuilder',
function($http, $q, umbRequestHelper, customerItemCacheDisplayBuilder, invoiceDisplayBuilder, shipmentRateQuoteDisplayBuilder) {
var baseUrl = Umbraco.Sys.ServerVariables['merchelloUrls']['merchelloBackOfficeCheckoutApiBaseUrl'];
return {
addItemCacheItem : function(instruction) {
var url = baseUrl + 'AddItemCacheItem';
return umbRequestHelper.resourcePromise(
$http.post(url,
instruction
),
'Failed to add item to the item cache');
},
removeItemCacheItem : function(instruction) {
var url = baseUrl + 'RemoveItemCacheItem';
return umbRequestHelper.resourcePromise(
$http.post(url,
instruction
),
'Failed to remove item from the item cache');
},
updateLineItemQuantity : function(instruction) {
var url = baseUrl + 'UpdateLineItemQuantity';
return umbRequestHelper.resourcePromise(
$http.post(url, instruction),
'Failed to update item quantity');
},
createCheckoutInvoice: function(model) {
var url = baseUrl + 'CreateCheckoutInvoice';
var defer = $q.defer();
umbRequestHelper.resourcePromise(
$http.post(url, model),
'Failed to update item quantity')
.then(function(result) {
var invoice = invoiceDisplayBuilder.transform(result);
defer.resolve(invoice);
});
return defer.promise;
},
moveToWishlist : function(instruction) {
var url = baseUrl + 'MoveToWishlist';
return umbRequestHelper.resourcePromise(
$http.post(url,
instruction
),
'Failed to move item to wish list');
},
moveToBasket : function(instruction) {
var url = baseUrl + 'MoveToBasket';
return umbRequestHelper.resourcePromise(
$http.post(url,
instruction
),
'Failed to move item to basket');
},
getShipmentRateQuotes: function(customerKey) {
var url = baseUrl + 'GetShipmentRateQuotes';
var defer = $q.defer();
umbRequestHelper.resourcePromise(
$http({
url: url,
method: "GET",
params: { customerKey: customerKey }
}),
'Failed to quote shipments for customer basket')
.then(function(result) {
var quotes = shipmentRateQuoteDisplayBuilder.transform(result);
defer.resolve(quotes);
});
return defer.promise;
},
getCheckoutStages: function() {
return umbRequestHelper.resourcePromise(
$http({
url: baseUrl + 'GetCheckoutStages',
method: "GET"
}),
'Failed to get checkout stages');
}
};
}]);
|
Package.describe({
name: "telescope:sitemap",
summary: "Sitemap package for Telescope",
version: "0.20.6",
git: "https://github.com/TelescopeJS/telescope-sitemap.git"
});
Package.onUse(function(api) {
api.versionsFrom("METEOR@1.0");
api.use([
"telescope:core@0.20.6",
"gadicohen:sitemaps@0.0.20"
]);
// server
api.addFiles([
"lib/server/sitemaps.js"
], ["server"]);
});
|
import { IS_DART, StringWrapper } from 'angular2/src/facade/lang';
export var MODULE_SUFFIX = IS_DART ? '.dart' : '';
var CAMEL_CASE_REGEXP = /([A-Z])/g;
var DASH_CASE_REGEXP = /-([a-z])/g;
export function camelCaseToDashCase(input) {
return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, (m) => { return '-' + m[1].toLowerCase(); });
}
export function dashCaseToCamelCase(input) {
return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, (m) => { return m[1].toUpperCase(); });
}
export function splitAtColon(input, defaultValues) {
var parts = StringWrapper.split(input.trim(), /\s*:\s*/g);
if (parts.length > 1) {
return parts;
}
else {
return defaultValues;
}
}
export function sanitizeIdentifier(name) {
return StringWrapper.replaceAll(name, /\W/g, '_');
}
|
Clazz.declarePackage ("JM");
Clazz.load (["JM.PhosphorusPolymer"], "JM.NucleicPolymer", ["JU.Measure", "$.P4", "$.V3", "JM.HBond"], function () {
c$ = Clazz.decorateAsClass (function () {
this.isDssrSet = false;
Clazz.instantialize (this, arguments);
}, JM, "NucleicPolymer", JM.PhosphorusPolymer);
Clazz.makeConstructor (c$,
function (monomers) {
Clazz.superConstructor (this, JM.NucleicPolymer, [monomers]);
this.type = 2;
this.hasWingPoints = true;
}, "~A");
Clazz.defineMethod (c$, "getNucleicPhosphorusAtom",
function (monomerIndex) {
return this.monomers[monomerIndex].getLeadAtom ();
}, "~N");
Clazz.overrideMethod (c$, "calcEtaThetaAngles",
function () {
var eta = NaN;
for (var i = 0; i < this.monomerCount - 2; ++i) {
var m1 = this.monomers[i];
var m2 = this.monomers[i + 1];
var p1 = m1.getP ();
var c41 = m1.getC4P ();
var p2 = m2.getP ();
var c42 = m2.getC4P ();
if (i > 0) {
var m0 = this.monomers[i - 1];
var c40 = m0.getC4P ();
eta = JU.Measure.computeTorsion (c40, p1, c41, p2, true);
}var theta = JU.Measure.computeTorsion (p1, c41, p2, c42, true);
if (eta < 0) eta += 360;
if (theta < 0) theta += 360;
m1.setGroupParameter (1112539141, eta);
m1.setGroupParameter (1112539152, theta);
}
return true;
});
Clazz.overrideMethod (c$, "calcRasmolHydrogenBonds",
function (polymer, bsA, bsB, vAtoms, nMaxPerResidue, min, checkDistances, dsspIgnoreHydrogens) {
var other = polymer;
var vNorm = new JU.V3 ();
var vAB = new JU.V3 ();
for (var i = this.monomerCount; --i >= 0; ) {
var myNucleotide = this.monomers[i];
if (!myNucleotide.isPurine ()) continue;
var myN3 = myNucleotide.getN3 ();
var isInA = bsA.get (myN3.i);
if (!isInA && !bsB.get (myN3.i)) continue;
var myN1 = myNucleotide.getN1 ();
var myN9 = myNucleotide.getN0 ();
var plane = JU.Measure.getPlaneThroughPoints (myN3, myN1, myN9, vNorm, vAB, new JU.P4 ());
var bestN3 = null;
var minDist2 = 25;
var bestNucleotide = null;
for (var j = other.monomerCount; --j >= 0; ) {
var otherNucleotide = other.monomers[j];
if (!otherNucleotide.isPyrimidine ()) continue;
var otherN3 = otherNucleotide.getN3 ();
if (isInA ? !bsB.get (otherN3.i) : !bsA.get (otherN3.i)) continue;
var otherN1 = otherNucleotide.getN0 ();
var dist2 = myN1.distanceSquared (otherN3);
if (dist2 < minDist2 && myN9.distanceSquared (otherN1) > 50 && Math.abs (JU.Measure.distanceToPlane (plane, otherN3)) < 1) {
bestNucleotide = otherNucleotide;
bestN3 = otherN3;
minDist2 = dist2;
}}
var n = 0;
if (bestN3 != null) {
n += JM.NucleicPolymer.addHydrogenBond (vAtoms, myN1, bestN3);
if (n >= nMaxPerResidue) continue;
if (myNucleotide.isGuanine ()) {
n += JM.NucleicPolymer.addHydrogenBond (vAtoms, myNucleotide.getN2 (), bestNucleotide.getO2 ());
if (n >= nMaxPerResidue) continue;
n += JM.NucleicPolymer.addHydrogenBond (vAtoms, myNucleotide.getO6 (), bestNucleotide.getN4 ());
if (n >= nMaxPerResidue) continue;
} else {
n += JM.NucleicPolymer.addHydrogenBond (vAtoms, myNucleotide.getN6 (), bestNucleotide.getO4 ());
}}}
}, "JM.BioPolymer,JU.BS,JU.BS,JU.Lst,~N,~A,~B,~B");
c$.addHydrogenBond = Clazz.defineMethod (c$, "addHydrogenBond",
function (vAtoms, atom1, atom2) {
if (atom1 == null || atom2 == null) return 0;
vAtoms.addLast ( new JM.HBond (atom1, atom2, 18432, 1, 0, 0));
return 1;
}, "JU.Lst,JM.Atom,JM.Atom");
Clazz.defineStatics (c$,
"htGroup1", null);
});
|
import { settings } from '../../settings';
settings.add('Accounts_OAuth_Dolphin_URL', '', { type: 'string', group: 'OAuth', public: true, section: 'Dolphin', i18nLabel: 'URL' });
settings.add('Accounts_OAuth_Dolphin', false, { type: 'boolean', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Enable' });
settings.add('Accounts_OAuth_Dolphin_id', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_id' });
settings.add('Accounts_OAuth_Dolphin_secret', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Secret', secret: true });
settings.add('Accounts_OAuth_Dolphin_login_style', 'redirect', { type: 'select', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [{ key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' }] });
settings.add('Accounts_OAuth_Dolphin_button_label_text', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true });
settings.add('Accounts_OAuth_Dolphin_button_label_color', '#FFFFFF', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true });
settings.add('Accounts_OAuth_Dolphin_button_color', '#1d74f5', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true });
|
---
---
var index = lunr(function () {
this.field('body');
this.ref('url');
});
var documentTitles = {};
<% for file in @manifest.files: %>
<% for section in file.sections: %>
documentTitles["<%= @baseUrl + file.slug %>.html#<%= section.slug %>"] = "<%= section.title.replace(/"/g, '\\"') %>";
index.add({
url: "<%= @baseUrl + file.slug %>.html#<%= section.slug %>",
title: "<%= section.title.replace(/"/g, '\\"') %>",
body: "<%= section.markdown.replace(/(\n|\r)/g, " ").replace(/"/g, '\\"') %>"
});
<% end %>
<% end %>
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'bidi', 'pt-br', {
ltr: 'Direção do texto da esquerda para a direita',
rtl: 'Direção do texto da direita para a esquerda'
});
|
/**
* Copyright 2015 Google Inc. 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
*
* 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.
*/
/* jshint maxlen: false */
'use strict';
var createAPIRequest = require('../../lib/apirequest');
var utils = require('../../lib/utils');
/**
* Google Service User API
*
* Enables services that service consumers want to use on Google Cloud Platform, lists the available or enabled services, or disables services that service consumers no longer use.
*
* @example
* var google = require('googleapis');
* var serviceuser = google.serviceuser('v1');
*
* @namespace serviceuser
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Serviceuser
*/
function Serviceuser(options) { // eslint-disable-line
var self = this;
self._options = options || {};
self.projects = {
services: {
/**
* serviceuser.projects.services.disable
*
* @desc Disable a service so it can no longer be used with a project. This prevents unintended usage that may cause unexpected billing charges or security leaks. Operation<response: google.protobuf.Empty>
*
* @alias serviceuser.projects.services.disable
* @memberOf! serviceuser(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name Name of the consumer and the service to disable for that consumer. The Service User implementation accepts the following forms for consumer: - "project:<project_id>" A valid path would be: - /v1/projects/my-project/services/servicemanagement.googleapis.com:disable
* @param {serviceuser(v1).DisableServiceRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
disable: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://serviceuser.googleapis.com/v1/{name}:disable',
method: 'POST'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* serviceuser.projects.services.enable
*
* @desc Enable a service so it can be used with a project. See [Cloud Auth Guide](https://cloud.google.com/docs/authentication) for more information. Operation<response: google.protobuf.Empty>
*
* @alias serviceuser.projects.services.enable
* @memberOf! serviceuser(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name Name of the consumer and the service to enable for that consumer. A valid path would be: - /v1/projects/my-project/services/servicemanagement.googleapis.com:enable
* @param {serviceuser(v1).EnableServiceRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
enable: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://serviceuser.googleapis.com/v1/{name}:enable',
method: 'POST'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* serviceuser.projects.services.list
*
* @desc List enabled services for the specified consumer.
*
* @alias serviceuser.projects.services.list
* @memberOf! serviceuser(v1)
*
* @param {object} params Parameters for request
* @param {string} params.parent List enabled services for the specified parent. An example valid parent would be: - projects/my-project
* @param {string=} params.pageToken Token identifying which result to start with; returned by a previous list call.
* @param {integer=} params.pageSize Requested size of the next page of data.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://serviceuser.googleapis.com/v1/{parent}/services',
method: 'GET'
}, options),
params: params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: self
};
return createAPIRequest(parameters, callback);
}
}
};
self.services = {
/**
* serviceuser.services.search
*
* @desc Search available services. When no filter is specified, returns all accessible services. For authenticated users, also returns all services the calling user has "servicemanagement.services.bind" permission for.
*
* @alias serviceuser.services.search
* @memberOf! serviceuser(v1)
*
* @param {object} params Parameters for request
* @param {string=} params.pageToken Token identifying which result to start with; returned by a previous list call.
* @param {integer=} params.pageSize Requested size of the next page of data.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
search: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://serviceuser.googleapis.com/v1/services:search',
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* @typedef Option
* @memberOf! serviceuser(v1)
* @type object
* @property {object} value The option's value packed in an Any message. If the value is a primitive,
the corresponding wrapper type defined in google/protobuf/wrappers.proto
should be used. If the value is an enum, it should be stored as an int32
value using the google.protobuf.Int32Value type.
* @property {string} name The option's name. For protobuf built-in options (options defined in
descriptor.proto), this is the short name. For example, `"map_entry"`.
For custom options, it should be the fully-qualified name. For example,
`"google.api.http"`.
*/
/**
* @typedef Logging
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).LoggingDestination[]} consumerDestinations Logging configurations for sending logs to the consumer project.
There can be multiple consumer destinations, each one must have a
different monitored resource type. A log can be used in at most
one consumer destination.
* @property {serviceuser(v1).LoggingDestination[]} producerDestinations Logging configurations for sending logs to the producer project.
There can be multiple producer destinations, each one must have a
different monitored resource type. A log can be used in at most
one producer destination.
*/
/**
* @typedef QuotaLimit
* @memberOf! serviceuser(v1)
* @type object
* @property {string} defaultLimit Default number of tokens that can be consumed during the specified
duration. This is the number of tokens assigned when a client
application developer activates the service for his/her project.
Specifying a value of 0 will block all requests. This can be used if you
are provisioning quota to selected consumers and blocking others.
Similarly, a value of -1 will indicate an unlimited quota. No other
negative values are allowed.
Used by group-based quotas only.
* @property {string} displayName User-visible display name for this limit.
Optional. If not set, the UI will provide a default display name based on
the quota configuration. This field can be used to override the default
display name generated from the configuration.
* @property {string} description Optional. User-visible, extended description for this quota limit.
Should be used only when more context is needed to understand this limit
than provided by the limit's display name (see: `display_name`).
* @property {string} metric The name of the metric this quota limit applies to. The quota limits with
the same metric will be checked together during runtime. The metric must be
defined within the service config.
Used by metric-based quotas only.
* @property {object} values Tiered limit values. Also allows for regional or zone overrides for these
values if "/{region}" or "/{zone}" is specified in the unit field.
Currently supported tiers from low to high:
VERY_LOW, LOW, STANDARD, HIGH, VERY_HIGH
To apply different limit values for users according to their tiers, specify
the values for the tiers you want to differentiate. For example:
{LOW:100, STANDARD:500, HIGH:1000, VERY_HIGH:5000}
The limit value for each tier is optional except for the tier STANDARD.
The limit value for an unspecified tier falls to the value of its next
tier towards tier STANDARD. For the above example, the limit value for tier
STANDARD is 500.
To apply the same limit value for all users, just specify limit value for
tier STANDARD. For example: {STANDARD:500}.
To apply a regional overide for a tier, add a map entry with key
"<TIER>/<region>", where <region> is a region name. Similarly, for a zone
override, add a map entry with key "<TIER>/{zone}".
Further, a wildcard can be used at the end of a zone name in order to
specify zone level overrides. For example:
LOW: 10, STANDARD: 50, HIGH: 100,
LOW/us-central1: 20, STANDARD/us-central1: 60, HIGH/us-central1: 200,
LOW/us-central1-*: 10, STANDARD/us-central1-*: 20, HIGH/us-central1-*: 80
The regional overrides tier set for each region must be the same as
the tier set for default limit values. Same rule applies for zone overrides
tier as well.
Used by metric-based quotas only.
* @property {string} unit Specify the unit of the quota limit. It uses the same syntax as
Metric.unit. The supported unit kinds are determined by the quota
backend system.
The [Google Service Control](https://cloud.google.com/service-control)
supports the following unit components:
* One of the time intevals:
* "/min" for quota every minute.
* "/d" for quota every 24 hours, starting 00:00 US Pacific Time.
* Otherwise the quota won't be reset by time, such as storage limit.
* One and only one of the granted containers:
* "/{organization}" quota for an organization.
* "/{project}" quota for a project.
* "/{folder}" quota for a folder.
* "/{resource}" quota for a universal resource.
* Zero or more quota segmentation dimension. Not all combos are valid.
* "/{user}" quota for every user GAIA ID or client ip address.
User GAIA ID has precedence over client ip address.
* "/{region}" quota for every region. Not to be used with time intervals.
* Otherwise the resources granted on the target is not segmented.
* "/{zone}" quota for every zone. Not to be used with time intervals.
* Otherwise the resources granted on the target is not segmented.
* "/{resource}" quota for a resource associated with a project or org.
Here are some examples:
* "1/min/{project}" for quota per minute per project.
* "1/min/{user}" for quota per minute per user.
* "1/min/{organization}" for quota per minute per organization.
Note: the order of unit components is insignificant.
The "1" at the beginning is required to follow the metric unit syntax.
Used by metric-based quotas only.
* @property {string} maxLimit Maximum number of tokens that can be consumed during the specified
duration. Client application developers can override the default limit up
to this maximum. If specified, this value cannot be set to a value less
than the default limit. If not specified, it is set to the default limit.
To allow clients to apply overrides with no upper bound, set this to -1,
indicating unlimited maximum quota.
Used by group-based quotas only.
* @property {string} name Name of the quota limit. The name is used to refer to the limit when
overriding the default limit on per-consumer basis.
For group-based quota limits, the name must be unique within the quota
group. If a name is not provided, it will be generated from the limit_by
and duration fields.
For metric-based quota limits, the name must be provided, and it must be
unique within the service. The name can only include alphanumeric
characters as well as '-'.
The maximum length of the limit name is 64 characters.
The name of a limit is used as a unique identifier for this limit.
Therefore, once a limit has been put into use, its name should be
immutable. You can use the display_name field to provide a user-friendly
name for the limit. The display name can be evolved over time without
affecting the identity of the limit.
* @property {string} duration Duration of this limit in textual notation. Example: "100s", "24h", "1d".
For duration longer than a day, only multiple of days is supported. We
support only "100s" and "1d" for now. Additional support will be added in
the future. "0" indicates indefinite duration.
Used by group-based quotas only.
* @property {string} freeTier Free tier value displayed in the Developers Console for this limit.
The free tier is the number of tokens that will be subtracted from the
billed amount when billing is enabled.
This field can only be set on a limit with duration "1d", in a billable
group; it is invalid on any other limit. If this field is not set, it
defaults to 0, indicating that there is no free tier for this service.
Used by group-based quotas only.
*/
/**
* @typedef Method
* @memberOf! serviceuser(v1)
* @type object
* @property {boolean} responseStreaming If true, the response is streamed.
* @property {string} name The simple name of this method.
* @property {string} requestTypeUrl A URL of the input message type.
* @property {boolean} requestStreaming If true, the request is streamed.
* @property {string} syntax The source syntax of this method.
* @property {string} responseTypeUrl The URL of the output message type.
* @property {serviceuser(v1).Option[]} options Any metadata attached to the method.
*/
/**
* @typedef Mixin
* @memberOf! serviceuser(v1)
* @type object
* @property {string} root If non-empty specifies a path under which inherited HTTP paths
are rooted.
* @property {string} name The fully qualified name of the API which is included.
*/
/**
* @typedef CustomError
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).CustomErrorRule[]} rules The list of custom error rules that apply to individual API messages.
**NOTE:** All service configuration rules follow "last one wins" order.
* @property {string[]} types The list of custom error detail types, e.g. 'google.foo.v1.CustomError'.
*/
/**
* @typedef Http
* @memberOf! serviceuser(v1)
* @type object
* @property {boolean} fullyDecodeReservedExpansion When set to true, URL path parmeters will be fully URI-decoded except in
cases of single segment matches in reserved expansion, where "%2F" will be
left encoded.
The default behavior is to not decode RFC 6570 reserved characters in multi
segment matches.
* @property {serviceuser(v1).HttpRule[]} rules A list of HTTP configuration rules that apply to individual API methods.
**NOTE:** All service configuration rules follow "last one wins" order.
*/
/**
* @typedef SourceInfo
* @memberOf! serviceuser(v1)
* @type object
* @property {object[]} sourceFiles All files used during config generation.
*/
/**
* @typedef Control
* @memberOf! serviceuser(v1)
* @type object
* @property {string} environment The service control environment to use. If empty, no control plane
feature (like quota and billing) will be enabled.
*/
/**
* @typedef SystemParameter
* @memberOf! serviceuser(v1)
* @type object
* @property {string} name Define the name of the parameter, such as "api_key" . It is case sensitive.
* @property {string} urlQueryParameter Define the URL query parameter name to use for the parameter. It is case
sensitive.
* @property {string} httpHeader Define the HTTP header name to use for the parameter. It is case
insensitive.
*/
/**
* @typedef Monitoring
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).MonitoringDestination[]} consumerDestinations Monitoring configurations for sending metrics to the consumer project.
There can be multiple consumer destinations, each one must have a
different monitored resource type. A metric can be used in at most
one consumer destination.
* @property {serviceuser(v1).MonitoringDestination[]} producerDestinations Monitoring configurations for sending metrics to the producer project.
There can be multiple producer destinations, each one must have a
different monitored resource type. A metric can be used in at most
one producer destination.
*/
/**
* @typedef Field
* @memberOf! serviceuser(v1)
* @type object
* @property {string} typeUrl The field type URL, without the scheme, for message or enumeration
types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
* @property {integer} number The field number.
* @property {string} kind The field type.
* @property {string} jsonName The field JSON name.
* @property {serviceuser(v1).Option[]} options The protocol buffer options.
* @property {integer} oneofIndex The index of the field type in `Type.oneofs`, for message or enumeration
types. The first type has index 1; zero means the type is not in the list.
* @property {boolean} packed Whether to use alternative packed wire representation.
* @property {string} cardinality The field cardinality.
* @property {string} defaultValue The string value of the default value of this field. Proto2 syntax only.
* @property {string} name The field name.
*/
/**
* @typedef Enum
* @memberOf! serviceuser(v1)
* @type object
* @property {string} name Enum type name.
* @property {serviceuser(v1).EnumValue[]} enumvalue Enum value definitions.
* @property {serviceuser(v1).Option[]} options Protocol buffer options.
* @property {serviceuser(v1).SourceContext} sourceContext The source context.
* @property {string} syntax The source syntax.
*/
/**
* @typedef EnableServiceRequest
* @memberOf! serviceuser(v1)
* @type object
*/
/**
* @typedef LabelDescriptor
* @memberOf! serviceuser(v1)
* @type object
* @property {string} key The label key.
* @property {string} description A human-readable description for the label.
* @property {string} valueType The type of data that can be assigned to the label.
*/
/**
* @typedef Type
* @memberOf! serviceuser(v1)
* @type object
* @property {string} syntax The source syntax.
* @property {serviceuser(v1).SourceContext} sourceContext The source context.
* @property {serviceuser(v1).Option[]} options The protocol buffer options.
* @property {serviceuser(v1).Field[]} fields The list of fields.
* @property {string} name The fully qualified message name.
* @property {string[]} oneofs The list of types appearing in `oneof` definitions in this type.
*/
/**
* @typedef Experimental
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).AuthorizationConfig} authorization Authorization configuration.
*/
/**
* @typedef Backend
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).BackendRule[]} rules A list of API backend rules that apply to individual API methods.
**NOTE:** All service configuration rules follow "last one wins" order.
*/
/**
* @typedef AuthorizationConfig
* @memberOf! serviceuser(v1)
* @type object
* @property {string} provider The name of the authorization provider, such as
firebaserules.googleapis.com.
*/
/**
* @typedef DocumentationRule
* @memberOf! serviceuser(v1)
* @type object
* @property {string} deprecationDescription Deprecation description of the selected element(s). It can be provided if an
element is marked as `deprecated`.
* @property {string} selector The selector is a comma-separated list of patterns. Each pattern is a
qualified name of the element which may end in "*", indicating a wildcard.
Wildcards are only allowed at the end and for a whole component of the
qualified name, i.e. "foo.*" is ok, but not "foo.b*" or "foo.*.bar". To
specify a default for all applicable elements, the whole pattern "*"
is used.
* @property {string} description Description of the selected API(s).
*/
/**
* @typedef ContextRule
* @memberOf! serviceuser(v1)
* @type object
* @property {string} selector Selects the methods to which this rule applies.
Refer to selector for syntax details.
* @property {string[]} provided A list of full type names of provided contexts.
* @property {string[]} requested A list of full type names of requested contexts.
*/
/**
* @typedef MetricDescriptor
* @memberOf! serviceuser(v1)
* @type object
* @property {string} metricKind Whether the metric records instantaneous values, changes to a value, etc.
Some combinations of `metric_kind` and `value_type` might not be supported.
* @property {string} description A detailed description of the metric, which can be used in documentation.
* @property {string} displayName A concise name for the metric, which can be displayed in user interfaces.
Use sentence case without an ending period, for example "Request count".
* @property {string} unit The unit in which the metric value is reported. It is only applicable
if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The
supported units are a subset of [The Unified Code for Units of
Measure](http://unitsofmeasure.org/ucum.html) standard:
**Basic units (UNIT)**
* `bit` bit
* `By` byte
* `s` second
* `min` minute
* `h` hour
* `d` day
**Prefixes (PREFIX)**
* `k` kilo (10**3)
* `M` mega (10**6)
* `G` giga (10**9)
* `T` tera (10**12)
* `P` peta (10**15)
* `E` exa (10**18)
* `Z` zetta (10**21)
* `Y` yotta (10**24)
* `m` milli (10**-3)
* `u` micro (10**-6)
* `n` nano (10**-9)
* `p` pico (10**-12)
* `f` femto (10**-15)
* `a` atto (10**-18)
* `z` zepto (10**-21)
* `y` yocto (10**-24)
* `Ki` kibi (2**10)
* `Mi` mebi (2**20)
* `Gi` gibi (2**30)
* `Ti` tebi (2**40)
**Grammar**
The grammar includes the dimensionless unit `1`, such as `1/s`.
The grammar also includes these connectors:
* `/` division (as an infix operator, e.g. `1/s`).
* `.` multiplication (as an infix operator, e.g. `GBy.d`)
The grammar for a unit is as follows:
Expression = Component { "." Component } { "/" Component } ;
Component = [ PREFIX ] UNIT [ Annotation ]
| Annotation
| "1"
;
Annotation = "{" NAME "}" ;
Notes:
* `Annotation` is just a comment if it follows a `UNIT` and is
equivalent to `1` if it is used alone. For examples,
`{requests}/s == 1/s`, `By{transmitted}/s == By/s`.
* `NAME` is a sequence of non-blank printable ASCII characters not
containing '{' or '}'.
* @property {serviceuser(v1).LabelDescriptor[]} labels The set of labels that can be used to describe a specific
instance of this metric type. For example, the
`appengine.googleapis.com/http/server/response_latencies` metric
type has a label for the HTTP response code, `response_code`, so
you can look at latencies for successful responses or just
for responses that failed.
* @property {string} name The resource name of the metric descriptor. Depending on the
implementation, the name typically includes: (1) the parent resource name
that defines the scope of the metric type or of its data; and (2) the
metric's URL-encoded type, which also appears in the `type` field of this
descriptor. For example, following is the resource name of a custom
metric within the GCP project `my-project-id`:
"projects/my-project-id/metricDescriptors/custom.googleapis.com%2Finvoice%2Fpaid%2Famount"
* @property {string} type The metric type, including its DNS name prefix. The type is not
URL-encoded. All user-defined custom metric types have the DNS name
`custom.googleapis.com`. Metric types should use a natural hierarchical
grouping. For example:
"custom.googleapis.com/invoice/paid/amount"
"appengine.googleapis.com/http/server/response_latencies"
* @property {string} valueType Whether the measurement is an integer, a floating-point number, etc.
Some combinations of `metric_kind` and `value_type` might not be supported.
*/
/**
* @typedef SourceContext
* @memberOf! serviceuser(v1)
* @type object
* @property {string} fileName The path-qualified name of the .proto file that contained the associated
protobuf element. For example: `"google/protobuf/source_context.proto"`.
*/
/**
* @typedef Endpoint
* @memberOf! serviceuser(v1)
* @type object
* @property {boolean} allowCors Allowing
[CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), aka
cross-domain traffic, would allow the backends served from this endpoint to
receive and respond to HTTP OPTIONS requests. The response will be used by
the browser to determine whether the subsequent cross-origin request is
allowed to proceed.
* @property {string[]} aliases DEPRECATED: This field is no longer supported. Instead of using aliases,
please specify multiple google.api.Endpoint for each of the intented
alias.
Additional names that this endpoint will be hosted on.
* @property {string} target The specification of an Internet routable address of API frontend that will
handle requests to this [API Endpoint](https://cloud.google.com/apis/design/glossary).
It should be either a valid IPv4 address or a fully-qualified domain name.
For example, "8.8.8.8" or "myservice.appspot.com".
* @property {string} name The canonical name of this endpoint.
* @property {string[]} features The list of features enabled on this endpoint.
* @property {string[]} apis The list of APIs served by this endpoint.
*/
/**
* @typedef ListEnabledServicesResponse
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).PublishedService[]} services Services enabled for the specified parent.
* @property {string} nextPageToken Token that can be passed to `ListEnabledServices` to resume a paginated
query.
*/
/**
* @typedef OAuthRequirements
* @memberOf! serviceuser(v1)
* @type object
* @property {string} canonicalScopes The list of publicly documented OAuth scopes that are allowed access. An
OAuth token containing any of these scopes will be accepted.
Example:
canonical_scopes: https://www.googleapis.com/auth/calendar,
https://www.googleapis.com/auth/calendar.read
*/
/**
* @typedef Usage
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).UsageRule[]} rules A list of usage rules that apply to individual API methods.
**NOTE:** All service configuration rules follow "last one wins" order.
* @property {string[]} requirements Requirements that must be satisfied before a consumer project can use the
service. Each requirement is of the form <service.name>/<requirement-id>;
for example 'serviceusage.googleapis.com/billing-enabled'.
* @property {string} producerNotificationChannel The full resource name of a channel used for sending notifications to the
service producer.
Google Service Management currently only supports
[Google Cloud Pub/Sub](https://cloud.google.com/pubsub) as a notification
channel. To use Google Cloud Pub/Sub as the channel, this must be the name
of a Cloud Pub/Sub topic that uses the Cloud Pub/Sub topic name format
documented in https://cloud.google.com/pubsub/docs/overview.
*/
/**
* @typedef Context
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).ContextRule[]} rules A list of RPC context rules that apply to individual API methods.
**NOTE:** All service configuration rules follow "last one wins" order.
*/
/**
* @typedef LogDescriptor
* @memberOf! serviceuser(v1)
* @type object
* @property {string} description A human-readable description of this log. This information appears in
the documentation and can contain details.
* @property {string} displayName The human-readable name for this log. This information appears on
the user interface and should be concise.
* @property {serviceuser(v1).LabelDescriptor[]} labels The set of labels that are available to describe a specific log entry.
Runtime requests that contain labels not specified here are
considered invalid.
* @property {string} name The name of the log. It must be less than 512 characters long and can
include the following characters: upper- and lower-case alphanumeric
characters [A-Za-z0-9], and punctuation characters including
slash, underscore, hyphen, period [/_-.].
*/
/**
* @typedef MonitoredResourceDescriptor
* @memberOf! serviceuser(v1)
* @type object
* @property {string} name Optional. The resource name of the monitored resource descriptor:
`"projects/{project_id}/monitoredResourceDescriptors/{type}"` where
{type} is the value of the `type` field in this object and
{project_id} is a project ID that provides API-specific context for
accessing the type. APIs that do not use project information can use the
resource name format `"monitoredResourceDescriptors/{type}"`.
* @property {string} displayName Optional. A concise name for the monitored resource type that might be
displayed in user interfaces. It should be a Title Cased Noun Phrase,
without any article or other determiners. For example,
`"Google Cloud SQL Database"`.
* @property {string} description Optional. A detailed description of the monitored resource type that might
be used in documentation.
* @property {string} type Required. The monitored resource type. For example, the type
`"cloudsql_database"` represents databases in Google Cloud SQL.
The maximum length of this value is 256 characters.
* @property {serviceuser(v1).LabelDescriptor[]} labels Required. A set of labels used to describe instances of this monitored
resource type. For example, an individual Google Cloud SQL database is
identified by values for the labels `"database_id"` and `"zone"`.
*/
/**
* @typedef CustomErrorRule
* @memberOf! serviceuser(v1)
* @type object
* @property {boolean} isErrorType Mark this message as possible payload in error response. Otherwise,
objects of this type will be filtered when they appear in error payload.
* @property {string} selector Selects messages to which this rule applies.
Refer to selector for syntax details.
*/
/**
* @typedef MediaDownload
* @memberOf! serviceuser(v1)
* @type object
* @property {boolean} enabled Whether download is enabled.
* @property {string} downloadService DO NOT USE THIS FIELD UNTIL THIS WARNING IS REMOVED.
Specify name of the download service if one is used for download.
*/
/**
* @typedef DisableServiceRequest
* @memberOf! serviceuser(v1)
* @type object
*/
/**
* @typedef SearchServicesResponse
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).PublishedService[]} services Services available publicly or available to the authenticated caller.
* @property {string} nextPageToken Token that can be passed to `ListAvailableServices` to resume a paginated
query.
*/
/**
* @typedef MediaUpload
* @memberOf! serviceuser(v1)
* @type object
* @property {string} uploadService DO NOT USE THIS FIELD UNTIL THIS WARNING IS REMOVED.
Specify name of the upload service if one is used for upload.
* @property {boolean} enabled Whether upload is enabled.
*/
/**
* @typedef UsageRule
* @memberOf! serviceuser(v1)
* @type object
* @property {boolean} allowUnregisteredCalls True, if the method allows unregistered calls; false otherwise.
* @property {string} selector Selects the methods to which this rule applies. Use '*' to indicate all
methods in all APIs.
Refer to selector for syntax details.
*/
/**
* @typedef AuthRequirement
* @memberOf! serviceuser(v1)
* @type object
* @property {string} audiences NOTE: This will be deprecated soon, once AuthProvider.audiences is
implemented and accepted in all the runtime components.
The list of JWT
[audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
that are allowed to access. A JWT containing any of these audiences will
be accepted. When this setting is absent, only JWTs with audience
"https://Service_name/API_name"
will be accepted. For example, if no audiences are in the setting,
LibraryService API will only accept JWTs with the following audience
"https://library-example.googleapis.com/google.example.library.v1.LibraryService".
Example:
audiences: bookstore_android.apps.googleusercontent.com,
bookstore_web.apps.googleusercontent.com
* @property {string} providerId id from authentication provider.
Example:
provider_id: bookstore_auth
*/
/**
* @typedef Documentation
* @memberOf! serviceuser(v1)
* @type object
* @property {string} summary A short summary of what the service does. Can only be provided by
plain text.
* @property {string} documentationRootUrl The URL to the root of documentation.
* @property {serviceuser(v1).DocumentationRule[]} rules A list of documentation rules that apply to individual API elements.
**NOTE:** All service configuration rules follow "last one wins" order.
* @property {string} overview Declares a single overview page. For example:
<pre><code>documentation:
summary: ...
overview: &#40;== include overview.md ==&#41;
</code></pre>
This is a shortcut for the following declaration (using pages style):
<pre><code>documentation:
summary: ...
pages:
- name: Overview
content: &#40;== include overview.md ==&#41;
</code></pre>
Note: you cannot specify both `overview` field and `pages` field.
* @property {serviceuser(v1).Page[]} pages The top level pages for the documentation set.
*/
/**
* @typedef BackendRule
* @memberOf! serviceuser(v1)
* @type object
* @property {string} address The address of the API backend.
* @property {string} selector Selects the methods to which this rule applies.
Refer to selector for syntax details.
* @property {number} deadline The number of seconds to wait for a response from a request. The
default depends on the deployment context.
*/
/**
* @typedef AuthenticationRule
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).OAuthRequirements} oauth The requirements for OAuth credentials.
* @property {serviceuser(v1).AuthRequirement[]} requirements Requirements for additional authentication providers.
* @property {string} selector Selects the methods to which this rule applies.
Refer to selector for syntax details.
* @property {boolean} allowWithoutCredential Whether to allow requests without a credential. The credential can be
an OAuth token, Google cookies (first-party auth) or EndUserCreds.
For requests without credentials, if the service control environment is
specified, each incoming request **must** be associated with a service
consumer. This can be done by passing an API key that belongs to a consumer
project.
*/
/**
* @typedef Api
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).Option[]} options Any metadata attached to the API.
* @property {serviceuser(v1).Method[]} methods The methods of this api, in unspecified order.
* @property {string} name The fully qualified name of this api, including package name
followed by the api's simple name.
* @property {serviceuser(v1).SourceContext} sourceContext Source context for the protocol buffer service represented by this
message.
* @property {string} syntax The source syntax of the service.
* @property {string} version A version string for this api. If specified, must have the form
`major-version.minor-version`, as in `1.10`. If the minor version
is omitted, it defaults to zero. If the entire version field is
empty, the major version is derived from the package name, as
outlined below. If the field is not empty, the version in the
package name will be verified to be consistent with what is
provided here.
The versioning schema uses [semantic
versioning](http://semver.org) where the major version number
indicates a breaking change and the minor version an additive,
non-breaking change. Both version numbers are signals to users
what to expect from different versions, and should be carefully
chosen based on the product plan.
The major version is also reflected in the package name of the
API, which must end in `v<major-version>`, as in
`google.feature.v1`. For major versions 0 and 1, the suffix can
be omitted. Zero major versions must only be used for
experimental, none-GA apis.
* @property {serviceuser(v1).Mixin[]} mixins Included APIs. See Mixin.
*/
/**
* @typedef MetricRule
* @memberOf! serviceuser(v1)
* @type object
* @property {string} selector Selects the methods to which this rule applies.
Refer to selector for syntax details.
* @property {object} metricCosts Metrics to update when the selected methods are called, and the associated
cost applied to each metric.
The key of the map is the metric name, and the values are the amount
increased for the metric against which the quota limits are defined.
The value must not be negative.
*/
/**
* @typedef Authentication
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).AuthProvider[]} providers Defines a set of authentication providers that a service supports.
* @property {serviceuser(v1).AuthenticationRule[]} rules A list of authentication rules that apply to individual API methods.
**NOTE:** All service configuration rules follow "last one wins" order.
*/
/**
* @typedef Operation
* @memberOf! serviceuser(v1)
* @type object
* @property {boolean} done If the value is `false`, it means the operation is still in progress.
If true, the operation is completed, and either `error` or `response` is
available.
* @property {object} response The normal response of the operation in case of success. If the original
method returns no data on success, such as `Delete`, the response is
`google.protobuf.Empty`. If the original method is standard
`Get`/`Create`/`Update`, the response should be the resource. For other
methods, the response should have the type `XxxResponse`, where `Xxx`
is the original method name. For example, if the original method name
is `TakeSnapshot()`, the inferred response type is
`TakeSnapshotResponse`.
* @property {string} name The server-assigned name, which is only unique within the same service that
originally returns it. If you use the default HTTP mapping, the
`name` should have the format of `operations/some/unique/name`.
* @property {serviceuser(v1).Status} error The error result of the operation in case of failure or cancellation.
* @property {object} metadata Service-specific metadata associated with the operation. It typically
contains progress information and common metadata such as create time.
Some services might not provide such metadata. Any method that returns a
long-running operation should document the metadata type, if any.
*/
/**
* @typedef Page
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).Page[]} subpages Subpages of this page. The order of subpages specified here will be
honored in the generated docset.
* @property {string} name The name of the page. It will be used as an identity of the page to
generate URI of the page, text of the link to this page in navigation,
etc. The full page name (start from the root page name to this page
concatenated with `.`) can be used as reference to the page in your
documentation. For example:
<pre><code>pages:
- name: Tutorial
content: &#40;== include tutorial.md ==&#41;
subpages:
- name: Java
content: &#40;== include tutorial_java.md ==&#41;
</code></pre>
You can reference `Java` page using Markdown reference link syntax:
`Java`.
* @property {string} content The Markdown content of the page. You can use <code>&#40;== include {path} ==&#41;</code>
to include content from a Markdown file.
*/
/**
* @typedef Status
* @memberOf! serviceuser(v1)
* @type object
* @property {integer} code The status code, which should be an enum value of google.rpc.Code.
* @property {string} message A developer-facing error message, which should be in English. Any
user-facing error message should be localized and sent in the
google.rpc.Status.details field, or localized by the client.
* @property {object[]} details A list of messages that carry the error details. There will be a
common set of message types for APIs to use.
*/
/**
* @typedef AuthProvider
* @memberOf! serviceuser(v1)
* @type object
* @property {string} jwksUri URL of the provider's public key set to validate signature of the JWT. See
[OpenID Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata).
Optional if the key set document:
- can be retrieved from
[OpenID Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html
of the issuer.
- can be inferred from the email domain of the issuer (e.g. a Google service account).
Example: https://www.googleapis.com/oauth2/v1/certs
* @property {string} audiences The list of JWT
[audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
that are allowed to access. A JWT containing any of these audiences will
be accepted. When this setting is absent, only JWTs with audience
"https://Service_name/API_name"
will be accepted. For example, if no audiences are in the setting,
LibraryService API will only accept JWTs with the following audience
"https://library-example.googleapis.com/google.example.library.v1.LibraryService".
Example:
audiences: bookstore_android.apps.googleusercontent.com,
bookstore_web.apps.googleusercontent.com
* @property {string} id The unique identifier of the auth provider. It will be referred to by
`AuthRequirement.provider_id`.
Example: "bookstore_auth".
* @property {string} issuer Identifies the principal that issued the JWT. See
https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1
Usually a URL or an email address.
Example: https://securetoken.google.com
Example: 1234567-compute@developer.gserviceaccount.com
*/
/**
* @typedef EnumValue
* @memberOf! serviceuser(v1)
* @type object
* @property {string} name Enum value name.
* @property {serviceuser(v1).Option[]} options Protocol buffer options.
* @property {integer} number Enum value number.
*/
/**
* @typedef Service
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).CustomError} customError Custom error configuration.
* @property {string} title The product title associated with this service.
* @property {serviceuser(v1).Endpoint[]} endpoints Configuration for network endpoints. If this is empty, then an endpoint
with the same name as the service is automatically generated to service all
defined APIs.
* @property {serviceuser(v1).LogDescriptor[]} logs Defines the logs used by this service.
* @property {serviceuser(v1).Api[]} apis A list of API interfaces exported by this service. Only the `name` field
of the google.protobuf.Api needs to be provided by the configuration
author, as the remaining fields will be derived from the IDL during the
normalization process. It is an error to specify an API interface here
which cannot be resolved against the associated IDL files.
* @property {serviceuser(v1).Type[]} types A list of all proto message types included in this API service.
Types referenced directly or indirectly by the `apis` are
automatically included. Messages which are not referenced but
shall be included, such as types used by the `google.protobuf.Any` type,
should be listed here by name. Example:
types:
- name: google.protobuf.Int32
* @property {serviceuser(v1).SourceInfo} sourceInfo Output only. The source information for this configuration if available.
* @property {serviceuser(v1).Http} http HTTP configuration.
* @property {serviceuser(v1).Backend} backend API backend configuration.
* @property {serviceuser(v1).SystemParameters} systemParameters System parameter configuration.
* @property {serviceuser(v1).Documentation} documentation Additional API documentation.
* @property {serviceuser(v1).Logging} logging Logging configuration.
* @property {serviceuser(v1).MonitoredResourceDescriptor[]} monitoredResources Defines the monitored resources used by this service. This is required
by the Service.monitoring and Service.logging configurations.
* @property {serviceuser(v1).Enum[]} enums A list of all enum types included in this API service. Enums
referenced directly or indirectly by the `apis` are automatically
included. Enums which are not referenced but shall be included
should be listed here by name. Example:
enums:
- name: google.someapi.v1.SomeEnum
* @property {serviceuser(v1).Context} context Context configuration.
* @property {string} id A unique ID for a specific instance of this message, typically assigned
by the client for tracking purpose. If empty, the server may choose to
generate one instead.
* @property {serviceuser(v1).Usage} usage Configuration controlling usage of this service.
* @property {serviceuser(v1).MetricDescriptor[]} metrics Defines the metrics used by this service.
* @property {serviceuser(v1).Authentication} authentication Auth configuration.
* @property {serviceuser(v1).Experimental} experimental Experimental configuration.
* @property {serviceuser(v1).Control} control Configuration for the service control plane.
* @property {integer} configVersion The version of the service configuration. The config version may
influence interpretation of the configuration, for example, to
determine defaults. This is documented together with applicable
options. The current default for the config version itself is `3`.
* @property {serviceuser(v1).Monitoring} monitoring Monitoring configuration.
* @property {string} producerProjectId The id of the Google developer project that owns the service.
Members of this project can manage the service configuration,
manage consumption of the service, etc.
* @property {serviceuser(v1).Type[]} systemTypes A list of all proto message types included in this API service.
It serves similar purpose as [google.api.Service.types], except that
these types are not needed by user-defined APIs. Therefore, they will not
show up in the generated discovery doc. This field should only be used
to define system APIs in ESF.
* @property {serviceuser(v1).Visibility} visibility API visibility configuration.
* @property {serviceuser(v1).Quota} quota Quota configuration.
* @property {string} name The DNS address at which this service is available,
e.g. `calendar.googleapis.com`.
*/
/**
* @typedef CustomHttpPattern
* @memberOf! serviceuser(v1)
* @type object
* @property {string} path The path matched by this custom verb.
* @property {string} kind The name of this custom HTTP verb.
*/
/**
* @typedef OperationMetadata
* @memberOf! serviceuser(v1)
* @type object
* @property {string[]} resourceNames The full name of the resources that this operation is directly
associated with.
* @property {serviceuser(v1).Step[]} steps Detailed status information for each step. The order is undetermined.
* @property {integer} progressPercentage Percentage of completion of this operation, ranging from 0 to 100.
* @property {string} startTime The start time of the operation.
*/
/**
* @typedef SystemParameterRule
* @memberOf! serviceuser(v1)
* @type object
* @property {string} selector Selects the methods to which this rule applies. Use '*' to indicate all
methods in all APIs.
Refer to selector for syntax details.
* @property {serviceuser(v1).SystemParameter[]} parameters Define parameters. Multiple names may be defined for a parameter.
For a given method call, only one of them should be used. If multiple
names are used the behavior is implementation-dependent.
If none of the specified names are present the behavior is
parameter-dependent.
*/
/**
* @typedef PublishedService
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).Service} service The service's published configuration.
* @property {string} name The resource name of the service.
A valid name would be:
- services/serviceuser.googleapis.com
*/
/**
* @typedef HttpRule
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).CustomHttpPattern} custom Custom pattern is used for defining custom verbs.
* @property {string} patch Used for updating a resource.
* @property {string} get Used for listing and getting information about resources.
* @property {string} put Used for updating a resource.
* @property {string} delete Used for deleting a resource.
* @property {string} body The name of the request field whose value is mapped to the HTTP body, or
`*` for mapping all fields not captured by the path pattern to the HTTP
body. NOTE: the referred field must not be a repeated field and must be
present at the top-level of request message type.
* @property {serviceuser(v1).MediaDownload} mediaDownload Use this only for Scotty Requests. Do not use this for bytestream methods.
For media support, add instead [][google.bytestream.RestByteStream] as an
API to your configuration.
* @property {string} post Used for creating a resource.
* @property {serviceuser(v1).HttpRule[]} additionalBindings Additional HTTP bindings for the selector. Nested bindings must
not contain an `additional_bindings` field themselves (that is,
the nesting may only be one level deep).
* @property {string} responseBody The name of the response field whose value is mapped to the HTTP body of
response. Other response fields are ignored. This field is optional. When
not set, the response message will be used as HTTP body of response.
NOTE: the referred field must be not a repeated field and must be present
at the top-level of response message type.
* @property {serviceuser(v1).MediaUpload} mediaUpload Use this only for Scotty Requests. Do not use this for media support using
Bytestream, add instead
[][google.bytestream.RestByteStream] as an API to your
configuration for Bytestream methods.
* @property {string} selector Selects methods to which this rule applies.
Refer to selector for syntax details.
*/
/**
* @typedef VisibilityRule
* @memberOf! serviceuser(v1)
* @type object
* @property {string} restriction A comma-separated list of visibility labels that apply to the `selector`.
Any of the listed labels can be used to grant the visibility.
If a rule has multiple labels, removing one of the labels but not all of
them can break clients.
Example:
visibility:
rules:
- selector: google.calendar.Calendar.EnhancedSearch
restriction: GOOGLE_INTERNAL, TRUSTED_TESTER
Removing GOOGLE_INTERNAL from this restriction will break clients that
rely on this method and only had access to it through GOOGLE_INTERNAL.
* @property {string} selector Selects methods, messages, fields, enums, etc. to which this rule applies.
Refer to selector for syntax details.
*/
/**
* @typedef MonitoringDestination
* @memberOf! serviceuser(v1)
* @type object
* @property {string} monitoredResource The monitored resource type. The type must be defined in
Service.monitored_resources section.
* @property {string[]} metrics Names of the metrics to report to this monitoring destination.
Each name must be defined in Service.metrics section.
*/
/**
* @typedef Visibility
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).VisibilityRule[]} rules A list of visibility rules that apply to individual API elements.
**NOTE:** All service configuration rules follow "last one wins" order.
*/
/**
* @typedef SystemParameters
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).SystemParameterRule[]} rules Define system parameters.
The parameters defined here will override the default parameters
implemented by the system. If this field is missing from the service
config, default system parameters will be used. Default system parameters
and names is implementation-dependent.
Example: define api key for all methods
system_parameters
rules:
- selector: "*"
parameters:
- name: api_key
url_query_parameter: api_key
Example: define 2 api key names for a specific method.
system_parameters
rules:
- selector: "/ListShelves"
parameters:
- name: api_key
http_header: Api-Key1
- name: api_key
http_header: Api-Key2
**NOTE:** All service configuration rules follow "last one wins" order.
*/
/**
* @typedef Quota
* @memberOf! serviceuser(v1)
* @type object
* @property {serviceuser(v1).QuotaLimit[]} limits List of `QuotaLimit` definitions for the service.
Used by metric-based quotas only.
* @property {serviceuser(v1).MetricRule[]} metricRules List of `MetricRule` definitions, each one mapping a selected method to one
or more metrics.
Used by metric-based quotas only.
*/
/**
* @typedef Step
* @memberOf! serviceuser(v1)
* @type object
* @property {string} status The status code.
* @property {string} description The short description of the step.
*/
/**
* @typedef LoggingDestination
* @memberOf! serviceuser(v1)
* @type object
* @property {string} monitoredResource The monitored resource type. The type must be defined in the
Service.monitored_resources section.
* @property {string[]} logs Names of the logs to be sent to this destination. Each name must
be defined in the Service.logs section. If the log name is
not a domain scoped name, it will be automatically prefixed with
the service name followed by "/".
*/
module.exports = Serviceuser;
|
import { LineLinkedShadow } from "./LineLinkedShadow";
import { Color } from "./Color";
export class LineLinked {
constructor() {
this.blink = false;
this.color = new Color();
this.consent = false;
this.distance = 100;
this.enable = false;
this.opacity = 1;
this.shadow = new LineLinkedShadow();
this.width = 1;
}
load(data) {
if (data !== undefined) {
if (data.blink !== undefined) {
this.blink = data.blink;
}
if (data.color !== undefined) {
if (typeof this.color === "string") {
this.color = data.color;
}
else {
this.color.load(data.color);
}
}
if (data.consent !== undefined) {
this.consent = data.consent;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
this.shadow.load(data.shadow);
if (data.width !== undefined) {
this.width = data.width;
}
}
}
}
//# sourceMappingURL=LineLinked.js.map |
"use strict";
module.exports = function (t, a) {
a.throws(function () {
t(undefined);
}, TypeError, "Undefined");
a.throws(function () {
t(null);
}, TypeError, "Null");
a(t(2), 2, "Number");
a.throws(function () {
t(-2);
}, TypeError, "Negative");
a.throws(function () {
t(2.34);
}, TypeError, "Float");
a(t("23"), 23, "Numeric string");
a.throws(function () {
t(NaN);
}, TypeError, "NaN");
a.throws(function () {
t(Infinity);
}, TypeError, "Infinity");
};
|
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/ar",[],function(){return{errorLoading:function(){return"لا يمكن تحميل النتائج"},inputTooLong:function(n){return"الرجاء حذف "+(n.input.length-n.maximum)+" عناصر"},inputTooShort:function(n){return"الرجاء إضافة "+(n.minimum-n.input.length)+" عناصر"},loadingMore:function(){return"جاري تحميل نتائج إضافية..."},maximumSelected:function(n){return"تستطيع إختيار "+n.maximum+" بنود فقط"},noResults:function(){return"لم يتم العثور على أي نتائج"},searching:function(){return"جاري البحث…"}}}),n.define,n.require}(); |
'use strict';
var once = require('once');
var helpers = require('./helpers');
function mapSeries(values, iterator, extensions, done) {
// Allow for extensions to not be specified
if (typeof extensions === 'function') {
done = extensions;
extensions = {};
}
// Handle no callback case
if (typeof done !== 'function') {
done = helpers.noop;
}
done = once(done);
// Will throw if non-object
var keys = Object.keys(values);
var length = keys.length;
var idx = 0;
// Return the same type as passed in
var results = helpers.initializeResults(values);
var exts = helpers.defaultExtensions(extensions);
var key = keys[idx];
next(key);
function next(key) {
var value = values[key];
var storage = exts.create(value, key) || {};
exts.before(storage);
iterator(value, once(handler));
function handler(err, result) {
if (err) {
exts.error(err, storage);
return done(err, results);
}
exts.after(result, storage);
results[key] = result;
if (++idx >= length) {
done(err, results);
} else {
next(keys[idx]);
}
}
}
}
module.exports = mapSeries;
|
/*!
* jQuery & Zepto Lazy - AJAX Plugin - v1.3
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// load data by ajax request and pass them to elements inner html, like:
// <div data-loader="ajax" data-src="url.html" data-method="post" data-type="html"></div>
$.lazy('ajax', function(element, response) {
ajaxRequest(this, element, response, element.attr('data-method'));
});
// load data by ajax get request and pass them to elements inner html, like:
// <div data-loader="get" data-src="url.html" data-type="html"></div>
$.lazy('get', function(element, response) {
ajaxRequest(this, element, response, 'GET');
});
// load data by ajax post request and pass them to elements inner html, like:
// <div data-loader="post" data-src="url.html" data-type="html"></div>
$.lazy('post', function(element, response) {
ajaxRequest(this, element, response, 'POST');
});
// load data by ajax put request and pass them to elements inner html, like:
// <div data-loader="put" data-src="url.html" data-type="html"></div>
$.lazy('put', function(element, response) {
ajaxRequest(this, element, response, 'PUT');
});
/**
* execute ajax request and handle response
* @param {object} instance
* @param {jQuery|object} element
* @param {function} response
* @param {string} [method]
*/
function ajaxRequest(instance, element, response, method) {
method = method.toUpperCase();
var data;
if ((method === 'POST' || method === 'PUT') && instance.config('ajaxCreateData')) {
data = instance.config('ajaxCreateData').apply(instance, [element]);
}
$.ajax({
url: element.attr('data-src'),
type: method === 'POST' || method === 'PUT' ? method : 'GET',
data: data,
dataType: element.attr('data-type') || 'html',
/**
* success callback
* @access private
* @param {*} content
* @return {void}
*/
success: function(content) {
// set responded data to element's inner html
element.html(content);
// use response function for Zepto
response(true);
// remove attributes
if (instance.config('removeAttribute')) {
element.removeAttr('data-src data-method data-type');
}
},
/**
* error callback
* @access private
* @return {void}
*/
error: function() {
// pass error state to lazy
// use response function for Zepto
response(false);
}
});
}
})(window.jQuery || window.Zepto);
/*!
* jQuery & Zepto Lazy - AV Plugin - v1.4
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// loads audio and video tags including tracks by two ways, like:
// <audio>
// <data-src src="audio.ogg" type="video/ogg"></data-src>
// <data-src src="audio.mp3" type="video/mp3"></data-src>
// </audio>
// <video data-poster="poster.jpg">
// <data-src src="video.ogv" type="video/ogv"></data-src>
// <data-src src="video.webm" type="video/webm"></data-src>
// <data-src src="video.mp4" type="video/mp4"></data-src>
// <data-track kind="captions" src="captions.vtt" srclang="en"></data-track>
// <data-track kind="descriptions" src="descriptions.vtt" srclang="en"></data-track>
// <data-track kind="subtitles" src="subtitles.vtt" srclang="de"></data-track>
// </video>
//
// or:
// <audio data-src="audio.ogg|video/ogg,video.mp3|video/mp3"></video>
// <video data-poster="poster.jpg" data-src="video.ogv|video/ogv,video.webm|video/webm,video.mp4|video/mp4">
// <data-track kind="captions" src="captions.vtt" srclang="en"></data-track>
// <data-track kind="descriptions" src="descriptions.vtt" srclang="en"></data-track>
// <data-track kind="subtitles" src="subtitles.vtt" srclang="de"></data-track>
// </video>
$.lazy(['av', 'audio', 'video'], ['audio', 'video'], function(element, response) {
var elementTagName = element[0].tagName.toLowerCase();
if (elementTagName === 'audio' || elementTagName === 'video') {
var srcAttr = 'data-src',
sources = element.find(srcAttr),
tracks = element.find('data-track'),
sourcesInError = 0,
// create on error callback for sources
onError = function() {
if (++sourcesInError === sources.length) {
response(false);
}
},
// create callback to handle a source or track entry
handleSource = function() {
var source = $(this),
type = source[0].tagName.toLowerCase(),
attributes = source.prop('attributes'),
target = $(type === srcAttr ? '<source>' : '<track>');
if (type === srcAttr) {
target.one('error', onError);
}
$.each(attributes, function(index, attribute) {
target.attr(attribute.name, attribute.value);
});
source.replaceWith(target);
};
// create event for successfull load
element.one('loadedmetadata', function() {
response(true);
})
// remove default callbacks to ignore loading poster image
.off('load error')
// load poster image
.attr('poster', element.attr('data-poster'));
// load by child tags
if (sources.length) {
sources.each(handleSource);
}
// load by attribute
else if (element.attr(srcAttr)) {
// split for every entry by comma
$.each(element.attr(srcAttr).split(','), function(index, value) {
// split again for file and file type
var parts = value.split('|');
// create a source entry
element.append($('<source>')
.one('error', onError)
.attr({src: parts[0].trim(), type: parts[1].trim()}));
});
// remove now obsolete attribute
if (this.config('removeAttribute')) {
element.removeAttr(srcAttr);
}
}
else {
// pass error state
// use response function for Zepto
response(false);
}
// load optional tracks
if (tracks.length) {
tracks.each(handleSource);
}
}
else {
// pass error state
// use response function for Zepto
response(false);
}
});
})(window.jQuery || window.Zepto);
/*!
* jQuery & Zepto Lazy - iFrame Plugin - v1.5
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// load iframe content, like:
// <iframe data-src="iframe.html"></iframe>
//
// enable content error check with:
// <iframe data-src="iframe.html" data-error-detect="true"></iframe>
$.lazy(['frame', 'iframe'], 'iframe', function(element, response) {
var instance = this;
if (element[0].tagName.toLowerCase() === 'iframe') {
var srcAttr = 'data-src',
errorDetectAttr = 'data-error-detect',
errorDetect = element.attr(errorDetectAttr);
// default way, just replace the 'src' attribute
if (errorDetect !== 'true' && errorDetect !== '1') {
// set iframe source
element.attr('src', element.attr(srcAttr));
// remove attributes
if (instance.config('removeAttribute')) {
element.removeAttr(srcAttr + ' ' + errorDetectAttr);
}
}
// extended way, even check if the document is available
else {
$.ajax({
url: element.attr(srcAttr),
dataType: 'html',
crossDomain: true,
xhrFields: {withCredentials: true},
/**
* success callback
* @access private
* @param {*} content
* @return {void}
*/
success: function(content) {
// set responded data to element's inner html
element.html(content)
// change iframe src
.attr('src', element.attr(srcAttr));
// remove attributes
if (instance.config('removeAttribute')) {
element.removeAttr(srcAttr + ' ' + errorDetectAttr);
}
},
/**
* error callback
* @access private
* @return {void}
*/
error: function() {
// pass error state to lazy
// use response function for Zepto
response(false);
}
});
}
}
else {
// pass error state to lazy
// use response function for Zepto
response(false);
}
});
})(window.jQuery || window.Zepto);
/*!
* jQuery & Zepto Lazy - NOOP Plugin - v1.2
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// will do nothing, used to disable elements or for development
// use like:
// <div data-loader="noop"></div>
// does not do anything, just a 'no-operation' helper ;)
$.lazy('noop', function() {});
// does nothing, but response a successfull loading
$.lazy('noop-success', function(element, response) {
// use response function for Zepto
response(true);
});
// does nothing, but response a failed loading
$.lazy('noop-error', function(element, response) {
// use response function for Zepto
response(false);
});
})(window.jQuery || window.Zepto);
/*!
* jQuery & Zepto Lazy - Picture Plugin - v1.3
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
var srcAttr = 'data-src',
srcsetAttr = 'data-srcset',
mediaAttr = 'data-media',
sizesAttr = 'data-sizes',
typeAttr = 'data-type';
// loads picture elements like:
// <picture>
// <data-src srcset="1x.jpg 1x, 2x.jpg 2x, 3x.jpg 3x" media="(min-width: 600px)" type="image/jpeg"></data-src>
// <data-src srcset="1x.jpg 1x, 2x.jpg 2x, 3x.jpg 3x" media="(min-width: 400px)" type="image/jpeg"></data-src>
// <data-img src="default.jpg" >
// </picture>
//
// or:
// <picture data-src="default.jpg">
// <data-src srcset="1x.jpg 1x, 2x.jpg 2x, 3x.jpg 3x" media="(min-width: 600px)" type="image/jpeg"></data-src>
// <data-src srcset="1x.jpg 1x, 2x.jpg 2x, 3x.jpg 3x" media="(min-width: 400px)" type="image/jpeg"></data-src>
// </picture>
//
// or just with attributes in one line:
// <picture data-src="default.jpg" data-srcset="1x.jpg 1x, 2x.jpg 2x, 3x.jpg 3x" data-media="(min-width: 600px)" data-sizes="" data-type="image/jpeg" />
$.lazy(['pic', 'picture'], ['picture'], function(element, response) {
var elementTagName = element[0].tagName.toLowerCase();
if (elementTagName === 'picture') {
var sources = element.find(srcAttr),
image = element.find('data-img'),
imageBase = this.config('imageBase') || '';
// handle as child elements
if (sources.length) {
sources.each(function() {
renameElementTag($(this), 'source', imageBase);
});
// create img tag from child
if (image.length === 1) {
image = renameElementTag(image, 'img', imageBase);
// bind event callbacks to new image tag
image.on('load', function() {
response(true);
}).on('error', function() {
response(false);
});
image.attr('src', image.attr(srcAttr));
if (this.config('removeAttribute')) {
image.removeAttr(srcAttr);
}
}
// create img tag from attribute
else if (element.attr(srcAttr)) {
// create image tag
createImageObject(element, imageBase + element.attr(srcAttr), response);
if (this.config('removeAttribute')) {
element.removeAttr(srcAttr);
}
}
// pass error state
else {
// use response function for Zepto
response(false);
}
}
// handle as attributes
else if( element.attr(srcsetAttr) ) {
// create source elements before img tag
$('<source>').attr({
media: element.attr(mediaAttr),
sizes: element.attr(sizesAttr),
type: element.attr(typeAttr),
srcset: getCorrectedSrcSet(element.attr(srcsetAttr), imageBase)
})
.appendTo(element);
// create image tag
createImageObject(element, imageBase + element.attr(srcAttr), response);
// remove attributes from parent picture element
if (this.config('removeAttribute')) {
element.removeAttr(srcAttr + ' ' + srcsetAttr + ' ' + mediaAttr + ' ' + sizesAttr + ' ' + typeAttr);
}
}
// pass error state
else {
// use response function for Zepto
response(false);
}
}
else {
// pass error state
// use response function for Zepto
response(false);
}
});
/**
* create a new child element and copy attributes
* @param {jQuery|object} element
* @param {string} toType
* @param {string} imageBase
* @return {jQuery|object}
*/
function renameElementTag(element, toType, imageBase) {
var attributes = element.prop('attributes'),
target = $('<' + toType + '>');
$.each(attributes, function(index, attribute) {
// build srcset with image base
if (attribute.name === 'srcset' || attribute.name === srcAttr) {
attribute.value = getCorrectedSrcSet(attribute.value, imageBase);
}
target.attr(attribute.name, attribute.value);
});
element.replaceWith(target);
return target;
}
/**
* create a new image element inside parent element
* @param {jQuery|object} parent
* @param {string} src
* @param {function} response
* @return void
*/
function createImageObject(parent, src, response) {
// create image tag
var imageObj = $('<img>')
// create image tag an bind callbacks for correct response
.one('load', function() {
response(true);
})
.one('error', function() {
response(false);
})
// set into picture element
.appendTo(parent)
// set src attribute at last to prevent early kick-in
.attr('src', src);
// call after load even on cached image
imageObj.complete && imageObj.load(); // jshint ignore : line
}
/**
* prepend image base to all srcset entries
* @param {string} srcset
* @param {string} imageBase
* @returns {string}
*/
function getCorrectedSrcSet(srcset, imageBase) {
if (imageBase) {
// trim, remove unnecessary spaces and split entries
var entries = srcset.split(',');
srcset = '';
for (var i = 0, l = entries.length; i < l; i++) {
srcset += imageBase + entries[i].trim() + (i !== l - 1 ? ',' : '');
}
}
return srcset;
}
})(window.jQuery || window.Zepto);
/*!
* jQuery & Zepto Lazy - Script Plugin - v1.2
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// loads javascript files for script tags, like:
// <script data-src="file.js" type="text/javascript"></script>
$.lazy(['js', 'javascript', 'script'], 'script', function(element, response) {
if (element[0].tagName.toLowerCase() === 'script') {
element.attr('src', element.attr('data-src'));
// remove attribute
if (this.config('removeAttribute')) {
element.removeAttr('data-src');
}
}
else {
// use response function for Zepto
response(false);
}
});
})(window.jQuery || window.Zepto);
/*!
* jQuery & Zepto Lazy - Vimeo Plugin - v1.1
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// load vimeo video iframe, like:
// <iframe data-loader="vimeo" data-src="176894130" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
$.lazy('vimeo', function(element, response) {
if (element[0].tagName.toLowerCase() === 'iframe') {
// pass source to iframe
element.attr('src', 'https://player.vimeo.com/video/' + element.attr('data-src'));
// remove attribute
if (this.config('removeAttribute')) {
element.removeAttr('data-src');
}
}
else {
// pass error state
// use response function for Zepto
response(false);
}
});
})(window.jQuery || window.Zepto);
/*!
* jQuery & Zepto Lazy - YouTube Plugin - v1.4
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// load youtube video iframe, like:
// <iframe data-loader="yt" data-src="1AYGnw6MwFM" width="560" height="315" frameborder="0" allowfullscreen></iframe>
$.lazy(['yt', 'youtube'], function(element, response) {
if (element[0].tagName.toLowerCase() === 'iframe') {
// pass source to iframe
element.attr('src', 'https://www.youtube.com/embed/' + element.attr('data-src') + '?rel=0&showinfo=0');
// remove attribute
if (this.config('removeAttribute')) {
element.removeAttr('data-src');
}
}
else {
// pass error state
// use response function for Zepto
response(false);
}
});
})(window.jQuery || window.Zepto); |
define({
"timeout": "انتهاء",
"highlightLocation": "تمييز الموقع",
"useTracking": "لاحظ تغييرات المواقع",
"warning": "مدخلات غير صحيحة",
"zoomScale": "مقياس التكبير/التصغير"
}); |
define(['mout/lang/isNull'], function (isNull) {
describe('lang/isNull()', function () {
it('should detect if value is a Null', function () {
expect( isNull(null) ).toBe( true );
expect( isNull('') ).toBe( false );
expect( isNull(123) ).toBe( false );
expect( isNull([]) ).toBe( false );
expect( isNull({}) ).toBe( false );
});
});
});
|
/**
* Autoinsert script tags (or other filebased tags) in an html file.
*
* ---------------------------------------------------------------
*
* Automatically inject <script> tags for javascript files and <link> tags
* for css files. Also automatically links an output file containing precompiled
* templates using a <script> tag.
*
* For usage docs see:
* https://github.com/Zolmeister/grunt-sails-linker
*
*/
module.exports = function(grunt) {
grunt.config.set('sails-linker', {
devJs: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script src="%s"></script>',
appRoot: '.tmp/public'
},
files: {
'.tmp/public/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.ejs': require('../pipeline').jsFilesToInject
}
},
devJsRelative: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script src="%s"></script>',
appRoot: '.tmp/public',
relative: true
},
files: {
'.tmp/public/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.ejs': require('../pipeline').jsFilesToInject
}
},
prodJs: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script src="%s"></script>',
appRoot: '.tmp/public'
},
files: {
'.tmp/public/**/*.html': ['.tmp/public/min/production.js'],
'views/**/*.html': ['.tmp/public/min/production.js'],
'views/**/*.ejs': ['.tmp/public/min/production.js']
}
},
prodJsRelative: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script src="%s"></script>',
appRoot: '.tmp/public',
relative: true
},
files: {
'.tmp/public/**/*.html': ['.tmp/public/min/production.js'],
'views/**/*.html': ['.tmp/public/min/production.js'],
'views/**/*.ejs': ['.tmp/public/min/production.js']
}
},
devStyles: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="%s">',
appRoot: '.tmp/public'
},
files: {
'.tmp/public/**/*.html': require('../pipeline').cssFilesToInject,
'views/**/*.html': require('../pipeline').cssFilesToInject,
'views/**/*.ejs': require('../pipeline').cssFilesToInject
}
},
devStylesRelative: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="%s">',
appRoot: '.tmp/public',
relative: true
},
files: {
'.tmp/public/**/*.html': require('../pipeline').cssFilesToInject,
'views/**/*.html': require('../pipeline').cssFilesToInject,
'views/**/*.ejs': require('../pipeline').cssFilesToInject
}
},
prodStyles: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="%s">',
appRoot: '.tmp/public'
},
files: {
'.tmp/public/index.html': ['.tmp/public/min/production.css'],
'views/**/*.html': ['.tmp/public/min/production.css'],
'views/**/*.ejs': ['.tmp/public/min/production.css']
}
},
prodStylesRelative: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="%s">',
appRoot: '.tmp/public',
relative: true
},
files: {
'.tmp/public/index.html': ['.tmp/public/min/production.css'],
'views/**/*.html': ['.tmp/public/min/production.css'],
'views/**/*.ejs': ['.tmp/public/min/production.css']
}
},
// Bring in html2js/angular template cache template object
devTpl: {
options: {
startTag: '<!--TEMPLATES-->',
endTag: '<!--TEMPLATES END-->',
fileTmpl: '<script type="text/javascript" src="%s"></script>',
appRoot: '.tmp/public'
},
files: {
'.tmp/public/index.html': ['.tmp/public/templates.js'],
'views/**/*.html': ['.tmp/public/templates.js'],
'views/**/*.ejs': ['.tmp/public/templates.js']
}
}
});
grunt.loadNpmTasks('grunt-sails-linker');
};
|
import { ReactiveVar } from 'meteor/reactive-var';
export let mainReady = new ReactiveVar(false); // eslint-disable-line
|
/**
* Globalize Runtime v1.4.0-alpha.2
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2018-03-09T13:51Z
*/
/*!
* Globalize Runtime v1.4.0-alpha.2 2018-03-09T13:51Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
"use strict";
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"../globalize-runtime"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "../globalize-runtime" ) );
} else {
// Extend global
factory( root.Globalize );
}
}(this, function( Globalize ) {
var runtimeKey = Globalize._runtimeKey,
validateParameterType = Globalize._validateParameterType;
/**
* Function inspired by jQuery Core, but reduced to our use case.
*/
var isPlainObject = function( obj ) {
return obj !== null && "" + obj === "[object Object]";
};
var validateParameterTypeMessageVariables = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || isPlainObject( value ) || Array.isArray( value ),
"Array or Plain Object"
);
};
var messageFormatterFn = function( formatter ) {
return function messageFormatter( variables ) {
if ( typeof variables === "number" || typeof variables === "string" ) {
variables = [].slice.call( arguments, 0 );
}
validateParameterTypeMessageVariables( variables, "variables" );
return formatter( variables );
};
};
Globalize._messageFormatterFn = messageFormatterFn;
/* jshint ignore:start */
Globalize._messageFormat = (function() {
var number = function (value, offset) {
if (isNaN(value)) throw new Error("'" + value + "' isn't a number.");
return value - (offset || 0);
};
var plural = function (value, offset, lcfunc, data, isOrdinal) {
if ({}.hasOwnProperty.call(data, value)) return data[value]();
if (offset) value -= offset;
var key = lcfunc(value, isOrdinal);
if (key in data) return data[key]();
return data.other();
};
var select = function (value, data) {
if ({}.hasOwnProperty.call(data, value)) return data[value]();
return data.other()
};
return {number: number, plural: plural, select: select};
}());
/* jshint ignore:end */
Globalize._validateParameterTypeMessageVariables = validateParameterTypeMessageVariables;
Globalize.messageFormatter =
Globalize.prototype.messageFormatter = function( /* path */ ) {
return Globalize[
runtimeKey( "messageFormatter", this._locale, [].slice.call( arguments, 0 ) )
];
};
Globalize.formatMessage =
Globalize.prototype.formatMessage = function( path /* , variables */ ) {
return this.messageFormatter( path ).apply( {}, [].slice.call( arguments, 1 ) );
};
return Globalize;
}));
|
/*! @license ScrollReveal v4.0.0-beta.26
Copyright 2018 Fisssion LLC.
Licensed under the GNU General Public License 3.0 for
compatible open source projects and non-commercial use.
For commercial sites, themes, projects, and applications,
keep your source code private/proprietary by purchasing
a commercial license from https://scrollrevealjs.org/
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ScrollReveal = factory());
}(this, (function () { 'use strict';
var defaults = {
delay: 0,
distance: '0',
duration: 600,
easing: 'cubic-bezier(0.6, 0.2, 0.1, 1)',
opacity: 0,
origin: 'bottom',
rotate: {
x: 0,
y: 0,
z: 0
},
scale: 1,
container: document.documentElement,
desktop: true,
mobile: true,
reset: false,
useDelay: 'always',
viewFactor: 0.0,
viewOffset: {
top: 0,
right: 0,
bottom: 0,
left: 0
},
afterReset: function afterReset() {},
afterReveal: function afterReveal() {},
beforeReset: function beforeReset() {},
beforeReveal: function beforeReveal() {}
}
var noop = {
clean: function clean() {},
destroy: function destroy() {},
reveal: function reveal() {},
sync: function sync() {},
get noop() {
return true
}
}
/*! @license is-dom-node v1.0.4
Copyright 2018 Fisssion LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function isDomNode(x) {
return typeof window.Node === 'object'
? x instanceof window.Node
: x !== null &&
typeof x === 'object' &&
typeof x.nodeType === 'number' &&
typeof x.nodeName === 'string'
}
/*! @license is-dom-node-list v1.2.1
Copyright 2018 Fisssion LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function isDomNodeList(x) {
var prototypeToString = Object.prototype.toString.call(x);
var regex = /^\[object (HTMLCollection|NodeList|Object)\]$/;
return typeof window.NodeList === 'object'
? x instanceof window.NodeList
: x !== null &&
typeof x === 'object' &&
typeof x.length === 'number' &&
regex.test(prototypeToString) &&
(x.length === 0 || isDomNode(x[0]))
}
/*! @license Tealight v0.3.0
Copyright 2018 Fisssion LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function index(target, context) {
if ( context === void 0 ) { context = document; }
if (target instanceof Array) { return target.filter(isDomNode) }
if (isDomNode(target)) { return [target] }
if (isDomNodeList(target)) { return Array.prototype.slice.call(target) }
if (typeof target === 'string') {
try {
var query = context.querySelectorAll(target);
return Array.prototype.slice.call(query)
} catch (err) {
return []
}
}
return []
}
function isObject(x) {
return (
x !== null &&
x instanceof Object &&
(x.constructor === Object ||
Object.prototype.toString.call(x) === '[object Object]')
)
}
function each(collection, callback) {
if (isObject(collection)) {
var keys = Object.keys(collection);
return keys.forEach(function (key) { return callback(collection[key], key, collection); })
}
if (collection instanceof Array) {
return collection.forEach(function (item, i) { return callback(item, i, collection); })
}
throw new TypeError('Expected either an array or object literal.')
}
function logger(message) {
var details = [], len = arguments.length - 1;
while ( len-- > 0 ) details[ len ] = arguments[ len + 1 ];
if (this.constructor.debug && console) {
var report = "%cScrollReveal: " + message;
details.forEach(function (detail) { return (report += "\n — " + detail); });
console.log(report, 'color: #ea654b;'); // eslint-disable-line no-console
}
}
function rinse() {
var this$1 = this;
var struct = function () { return ({
active: [],
stale: []
}); };
var elementIds = struct();
var sequenceIds = struct();
var containerIds = struct();
/**
* Take stock of active element IDs.
*/
try {
each(index('[data-sr-id]'), function (node) {
var id = parseInt(node.getAttribute('data-sr-id'));
elementIds.active.push(id);
});
} catch (e) {
throw e
}
/**
* Destroy stale elements.
*/
each(this.store.elements, function (element) {
if (elementIds.active.indexOf(element.id) === -1) {
elementIds.stale.push(element.id);
}
});
each(elementIds.stale, function (staleId) { return delete this$1.store.elements[staleId]; });
/**
* Take stock of active container and sequence IDs.
*/
each(this.store.elements, function (element) {
if (containerIds.active.indexOf(element.containerId) === -1) {
containerIds.active.push(element.containerId);
}
if (element.hasOwnProperty('sequence')) {
if (sequenceIds.active.indexOf(element.sequence.id) === -1) {
sequenceIds.active.push(element.sequence.id);
}
}
});
/**
* Destroy stale containers.
*/
each(this.store.containers, function (container) {
if (containerIds.active.indexOf(container.id) === -1) {
containerIds.stale.push(container.id);
}
});
each(containerIds.stale, function (staleId) {
var stale = this$1.store.containers[staleId].node;
stale.removeEventListener('scroll', this$1.delegate);
stale.removeEventListener('resize', this$1.delegate);
delete this$1.store.containers[staleId];
});
/**
* Destroy stale sequences.
*/
each(this.store.sequences, function (sequence) {
if (sequenceIds.active.indexOf(sequence.id) === -1) {
sequenceIds.stale.push(sequence.id);
}
});
each(sequenceIds.stale, function (staleId) { return delete this$1.store.sequences[staleId]; });
}
function clean(target) {
var this$1 = this;
var dirty;
try {
each(index(target), function (node) {
var id = node.getAttribute('data-sr-id');
if (id !== null) {
dirty = true;
var element = this$1.store.elements[id];
if (element.callbackTimer) {
window.clearTimeout(element.callbackTimer.clock);
}
node.setAttribute('style', element.styles.inline.generated);
node.removeAttribute('data-sr-id');
delete this$1.store.elements[id];
}
});
} catch (e) {
return logger.call(this, 'Clean failed.', e.stack || e.message)
}
if (dirty) {
try {
rinse.call(this);
} catch (e) {
return logger.call(this, 'Clean failed.', e.stack || e.message)
}
}
}
function destroy() {
var this$1 = this;
/**
* Remove all generated styles and element ids
*/
each(this.store.elements, function (element) {
element.node.setAttribute('style', element.styles.inline);
element.node.removeAttribute('data-sr-id');
});
/**
* Remove all event listeners.
*/
each(this.store.containers, function (container) {
var target =
container.node === document.documentElement ? window : container.node;
target.removeEventListener('scroll', this$1.delegate);
target.removeEventListener('resize', this$1.delegate);
});
/**
* Clear all data from the store
*/
this.store = {
containers: {},
elements: {},
history: [],
sequences: {}
};
}
/*! @license Rematrix v0.2.2
Copyright 2018 Fisssion LLC.
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.
*/
/**
* @module Rematrix
*/
/**
* Transformation matrices in the browser come in two flavors:
*
* - `matrix` using 6 values (short)
* - `matrix3d` using 16 values (long)
*
* This utility follows this [conversion guide](https://goo.gl/EJlUQ1)
* to expand short form matrices to their equivalent long form.
*
* @param {array} source - Accepts both short and long form matrices.
* @return {array}
*/
function format(source) {
if (source.constructor !== Array) {
throw new TypeError('Expected array.')
}
if (source.length === 16) {
return source
}
if (source.length === 6) {
var matrix = identity();
matrix[0] = source[0];
matrix[1] = source[1];
matrix[4] = source[2];
matrix[5] = source[3];
matrix[12] = source[4];
matrix[13] = source[5];
return matrix
}
throw new RangeError('Expected array with either 6 or 16 values.')
}
/**
* Returns a matrix representing no transformation. The product of any matrix
* multiplied by the identity matrix will be the original matrix.
*
* > **Tip:** Similar to how `5 * 1 === 5`, where `1` is the identity.
*
* @return {array}
*/
function identity() {
var matrix = [];
for (var i = 0; i < 16; i++) {
i % 5 == 0 ? matrix.push(1) : matrix.push(0);
}
return matrix
}
/**
* Returns a 4x4 matrix describing the combined transformations
* of both arguments.
*
* > **Note:** Order is very important. For example, rotating 45°
* along the Z-axis, followed by translating 500 pixels along the
* Y-axis... is not the same as translating 500 pixels along the
* Y-axis, followed by rotating 45° along on the Z-axis.
*
* @param {array} m - Accepts both short and long form matrices.
* @param {array} x - Accepts both short and long form matrices.
* @return {array}
*/
function multiply(m, x) {
var fm = format(m);
var fx = format(x);
var product = [];
for (var i = 0; i < 4; i++) {
var row = [fm[i], fm[i + 4], fm[i + 8], fm[i + 12]];
for (var j = 0; j < 4; j++) {
var k = j * 4;
var col = [fx[k], fx[k + 1], fx[k + 2], fx[k + 3]];
var result =
row[0] * col[0] + row[1] * col[1] + row[2] * col[2] + row[3] * col[3];
product[i + k] = result;
}
}
return product
}
/**
* Attempts to return a 4x4 matrix describing the CSS transform
* matrix passed in, but will return the identity matrix as a
* fallback.
*
* **Tip:** In virtually all cases, this method is used to convert
* a CSS matrix (retrieved as a `string` from computed styles) to
* its equivalent array format.
*
* @param {string} source - String containing a valid CSS `matrix` or `matrix3d` property.
* @return {array}
*/
function parse(source) {
if (typeof source === 'string') {
var match = source.match(/matrix(3d)?\(([^)]+)\)/);
if (match) {
var raw = match[2].split(', ').map(parseFloat);
return format(raw)
}
}
return identity()
}
/**
* Returns a 4x4 matrix describing X-axis rotation.
*
* @param {number} angle - Measured in degrees.
* @return {array}
*/
function rotateX(angle) {
var theta = Math.PI / 180 * angle;
var matrix = identity();
matrix[5] = matrix[10] = Math.cos(theta);
matrix[6] = matrix[9] = Math.sin(theta);
matrix[9] *= -1;
return matrix
}
/**
* Returns a 4x4 matrix describing Y-axis rotation.
*
* @param {number} angle - Measured in degrees.
* @return {array}
*/
function rotateY(angle) {
var theta = Math.PI / 180 * angle;
var matrix = identity();
matrix[0] = matrix[10] = Math.cos(theta);
matrix[2] = matrix[8] = Math.sin(theta);
matrix[2] *= -1;
return matrix
}
/**
* Returns a 4x4 matrix describing Z-axis rotation.
*
* @param {number} angle - Measured in degrees.
* @return {array}
*/
function rotateZ(angle) {
var theta = Math.PI / 180 * angle;
var matrix = identity();
matrix[0] = matrix[5] = Math.cos(theta);
matrix[1] = matrix[4] = Math.sin(theta);
matrix[4] *= -1;
return matrix
}
/**
* Returns a 4x4 matrix describing 2D scaling. The first argument
* is used for both X and Y-axis scaling, unless an optional
* second argument is provided to explicitly define Y-axis scaling.
*
* @param {number} scalar - Decimal multiplier.
* @param {number} [scalarY] - Decimal multiplier.
* @return {array}
*/
function scale(scalar, scalarY) {
var matrix = identity();
matrix[0] = scalar;
matrix[5] = typeof scalarY === 'number' ? scalarY : scalar;
return matrix
}
/**
* Returns a 4x4 matrix describing X-axis translation.
*
* @param {number} distance - Measured in pixels.
* @return {array}
*/
function translateX(distance) {
var matrix = identity();
matrix[12] = distance;
return matrix
}
/**
* Returns a 4x4 matrix describing Y-axis translation.
*
* @param {number} distance - Measured in pixels.
* @return {array}
*/
function translateY(distance) {
var matrix = identity();
matrix[13] = distance;
return matrix
}
var getPrefixedCssProp = (function () {
var properties = {};
var style = document.documentElement.style;
function getPrefixedCssProperty(name, source) {
if ( source === void 0 ) source = style;
if (name && typeof name === 'string') {
if (properties[name]) {
return properties[name]
}
if (typeof source[name] === 'string') {
return (properties[name] = name)
}
if (typeof source[("-webkit-" + name)] === 'string') {
return (properties[name] = "-webkit-" + name)
}
throw new RangeError(("Unable to find \"" + name + "\" style property."))
}
throw new TypeError('Expected a string.')
}
getPrefixedCssProperty.clearCache = function () { return (properties = {}); };
return getPrefixedCssProperty
})();
function style(element) {
var computed = window.getComputedStyle(element.node);
var position = computed.position;
var config = element.config;
/**
* Generate inline styles
*/
var inline = {};
var inlineStyle = element.node.getAttribute('style') || '';
var inlineMatch = inlineStyle.match(/[\w-]+\s*:\s*[^;]+\s*/gi) || [];
inline.computed = inlineMatch ? inlineMatch.map(function (m) { return m.trim(); }).join('; ') + ';' : '';
inline.generated = inlineMatch.some(function (m) { return m.match(/visibility\s?:\s?visible/i); })
? inline.computed
: inlineMatch.concat( ['visibility: visible']).map(function (m) { return m.trim(); }).join('; ') + ';';
/**
* Generate opacity styles
*/
var computedOpacity = parseFloat(computed.opacity);
var configOpacity = !isNaN(parseFloat(config.opacity))
? parseFloat(config.opacity)
: parseFloat(computed.opacity);
var opacity = {
computed: computedOpacity !== configOpacity ? ("opacity: " + computedOpacity + ";") : '',
generated: computedOpacity !== configOpacity ? ("opacity: " + configOpacity + ";") : ''
};
/**
* Generate transformation styles
*/
var transformations = [];
if (parseFloat(config.distance)) {
var axis = config.origin === 'top' || config.origin === 'bottom' ? 'Y' : 'X';
/**
* Let’s make sure our our pixel distances are negative for top and left.
* e.g. { origin: 'top', distance: '25px' } starts at `top: -25px` in CSS.
*/
var distance = config.distance;
if (config.origin === 'top' || config.origin === 'left') {
distance = /^-/.test(distance) ? distance.substr(1) : ("-" + distance);
}
var ref = distance.match(/(^-?\d+\.?\d?)|(em$|px$|%$)/g);
var value = ref[0];
var unit = ref[1];
switch (unit) {
case 'em':
distance = parseInt(computed.fontSize) * value;
break
case 'px':
distance = value;
break
case '%':
/**
* Here we use `getBoundingClientRect` instead of
* the existing data attached to `element.geometry`
* because only the former includes any transformations
* current applied to the element.
*
* If that behavior ends up being unintuitive, this
* logic could instead utilize `element.geometry.height`
* and `element.geoemetry.width` for the distaince calculation
*/
distance =
axis === 'Y'
? element.node.getBoundingClientRect().height * value / 100
: element.node.getBoundingClientRect().width * value / 100;
break
default:
throw new RangeError('Unrecognized or missing distance unit.')
}
if (axis === 'Y') {
transformations.push(translateY(distance));
} else {
transformations.push(translateX(distance));
}
}
if (config.rotate.x) { transformations.push(rotateX(config.rotate.x)); }
if (config.rotate.y) { transformations.push(rotateY(config.rotate.y)); }
if (config.rotate.z) { transformations.push(rotateZ(config.rotate.z)); }
if (config.scale !== 1) {
if (config.scale === 0) {
/**
* The CSS Transforms matrix interpolation specification
* basically disallows transitions of non-invertible
* matrixes, which means browsers won't transition
* elements with zero scale.
*
* That’s inconvenient for the API and developer
* experience, so we simply nudge their value
* slightly above zero; this allows browsers
* to transition our element as expected.
*
* `0.0002` was the smallest number
* that performed across browsers.
*/
transformations.push(scale(0.0002));
} else {
transformations.push(scale(config.scale));
}
}
var transform = {};
if (transformations.length) {
transform.property = getPrefixedCssProp('transform');
/**
* The default computed transform value should be one of:
* undefined || 'none' || 'matrix()' || 'matrix3d()'
*/
transform.computed = {
raw: computed[transform.property],
matrix: parse(computed[transform.property])
};
transformations.unshift(transform.computed.matrix);
var product = transformations.reduce(multiply);
transform.generated = {
initial: ((transform.property) + ": matrix3d(" + (product.join(', ')) + ");"),
final: ((transform.property) + ": matrix3d(" + (transform.computed.matrix.join(
', '
)) + ");")
};
} else {
transform.generated = {
initial: '',
final: ''
};
}
/**
* Generate transition styles
*/
var transition = {};
if (opacity.generated || transform.generated.initial) {
transition.property = getPrefixedCssProp('transition');
transition.computed = computed[transition.property];
transition.fragments = [];
var delay = config.delay;
var duration = config.duration;
var easing = config.easing;
if (opacity.generated) {
transition.fragments.push({
delayed: ("opacity " + (duration / 1000) + "s " + easing + " " + (delay / 1000) + "s"),
instant: ("opacity " + (duration / 1000) + "s " + easing + " 0s")
});
}
if (transform.generated.initial) {
transition.fragments.push({
delayed: ((transform.property) + " " + (duration / 1000) + "s " + easing + " " + (delay /
1000) + "s"),
instant: ((transform.property) + " " + (duration / 1000) + "s " + easing + " 0s")
});
}
/**
* The default computed transition property should be one of:
* undefined || '' || 'all 0s ease 0s' || 'all 0s 0s cubic-bezier()'
*/
if (transition.computed && !transition.computed.match(/all 0s/)) {
transition.fragments.unshift({
delayed: transition.computed,
instant: transition.computed
});
}
var composed = transition.fragments.reduce(
function (composition, fragment, i) {
composition.delayed +=
i === 0 ? fragment.delayed : (", " + (fragment.delayed));
composition.instant +=
i === 0 ? fragment.instant : (", " + (fragment.instant));
return composition
},
{
delayed: '',
instant: ''
}
);
transition.generated = {
delayed: ((transition.property) + ": " + (composed.delayed) + ";"),
instant: ((transition.property) + ": " + (composed.instant) + ";")
};
} else {
transition.generated = {
delayed: '',
instant: ''
};
}
return {
inline: inline,
opacity: opacity,
position: position,
transform: transform,
transition: transition
}
}
function animate(element, force) {
if ( force === void 0 ) force = {};
var pristine = force.pristine || this.pristine;
var delayed =
element.config.useDelay === 'always' ||
(element.config.useDelay === 'onload' && pristine) ||
(element.config.useDelay === 'once' && !element.seen);
var shouldReveal = element.visible && !element.revealed;
var shouldReset = !element.visible && element.revealed && element.config.reset;
if (force.reveal || shouldReveal) {
return triggerReveal.call(this, element, delayed)
}
if (force.reset || shouldReset) {
return triggerReset.call(this, element)
}
}
function triggerReveal(element, delayed) {
var styles = [
element.styles.inline.generated,
element.styles.opacity.computed,
element.styles.transform.generated.final
];
if (delayed) {
styles.push(element.styles.transition.generated.delayed);
} else {
styles.push(element.styles.transition.generated.instant);
}
element.revealed = element.seen = true;
element.node.setAttribute('style', styles.filter(function (s) { return s !== ''; }).join(' '));
registerCallbacks.call(this, element, delayed);
}
function triggerReset(element) {
var styles = [
element.styles.inline.generated,
element.styles.opacity.generated,
element.styles.transform.generated.initial,
element.styles.transition.generated.instant
];
element.revealed = false;
element.node.setAttribute('style', styles.filter(function (s) { return s !== ''; }).join(' '));
registerCallbacks.call(this, element);
}
function registerCallbacks(element, isDelayed) {
var this$1 = this;
var duration = isDelayed
? element.config.duration + element.config.delay
: element.config.duration;
var beforeCallback = element.revealed
? element.config.beforeReveal
: element.config.beforeReset;
var afterCallback = element.revealed
? element.config.afterReveal
: element.config.afterReset;
var elapsed = 0;
if (element.callbackTimer) {
elapsed = Date.now() - element.callbackTimer.start;
window.clearTimeout(element.callbackTimer.clock);
}
beforeCallback(element.node);
element.callbackTimer = {
start: Date.now(),
clock: window.setTimeout(function () {
afterCallback(element.node);
element.callbackTimer = null;
if (element.revealed && !element.config.reset) {
clean.call(this$1, element.node);
}
}, duration - elapsed)
};
}
var nextUniqueId = (function () {
var uid = 0;
return function () { return uid++; }
})();
function sequence(element, pristine) {
if ( pristine === void 0 ) pristine = this.pristine;
/**
* We first check if the element should reset.
*/
if (!element.visible && element.revealed && element.config.reset) {
return animate.call(this, element, { reset: true })
}
var store = this.store;
var seq = store.sequences[element.sequence.id];
var i = element.sequence.index;
if (seq) {
var visible = new SequenceModel(seq, 'visible', store);
var revealed = new SequenceModel(seq, 'revealed', store);
seq.models = { visible: visible, revealed: revealed };
/**
* At any given time, the sequencer
* needs to find these 3 elements:
*/
var currentElement;
var nextHeadElement;
var nextFootElement;
/**
* When no elements within a sequence are revealed,
* these 3 elements are easily pulled from the
* current visible sequence model.
*/
if (!revealed.body.length) {
currentElement = getElement(seq, visible.body.shift(), store);
nextHeadElement = getElement(seq, visible.head.pop(), store);
nextFootElement = getElement(seq, visible.body.shift(), store);
} else {
/**
* More typically though, something will be revealed
* and we need to model the unrevealed elements.
*/
var unrevealed = {
head: visible.body.filter(function (x) { return revealed.head.indexOf(x) >= 0; }),
foot: visible.body.filter(function (x) { return revealed.foot.indexOf(x) >= 0; })
};
/**
* Now we can compare the current sequence index
* against our new model to determine the current element.
*/
if (!seq.blocked.head && i === [].concat( unrevealed.head ).pop()) {
currentElement = getElement(seq, unrevealed.head.pop(), store);
} else if (!seq.blocked.foot && i === [].concat( unrevealed.foot ).shift()) {
currentElement = getElement(seq, unrevealed.foot.shift(), store);
}
/**
* And the next head and foot elements are
* easily pulled from our custom unrevealed model.
*/
nextHeadElement = getElement(seq, unrevealed.head.pop(), store);
nextFootElement = getElement(seq, unrevealed.foot.shift(), store);
}
/**
* Verify and animate!
*/
if (currentElement) {
if (nextHeadElement) { cue.call(this, seq, nextHeadElement, 'head', pristine); }
if (nextFootElement) { cue.call(this, seq, nextFootElement, 'foot', pristine); }
return animate.call(this, currentElement, { reveal: true, pristine: pristine })
}
}
}
function Sequence(interval) {
this.id = nextUniqueId();
this.interval = interval;
this.members = [];
this.models = {};
this.blocked = {
head: false,
foot: false
};
}
function SequenceModel(seq, prop, store) {
var this$1 = this;
this.head = []; // Elements before the body with a falsey prop.
this.body = []; // Elements with a truthy prop.
this.foot = []; // Elements after the body with a falsey prop.
each(seq.members, function (id, index) {
var element = store.elements[id];
if (element && element[prop]) {
this$1.body.push(index);
}
});
if (this.body.length) {
each(seq.members, function (id, index) {
var element = store.elements[id];
if (element && !element[prop]) {
if (index < this$1.body[0]) {
this$1.head.push(index);
} else {
this$1.foot.push(index);
}
}
});
}
}
function cue(seq, element, direction, pristine) {
var this$1 = this;
seq.blocked[direction] = true;
setTimeout(function () {
seq.blocked[direction] = false;
sequence.call(this$1, element, pristine);
}, seq.interval);
}
function getElement(seq, index, store) {
var id = seq.members[index];
return store.elements[id]
}
function initialize() {
var this$1 = this;
rinse.call(this);
each(this.store.elements, function (element) {
var styles = [element.styles.inline.generated];
if (element.visible) {
styles.push(element.styles.opacity.computed);
styles.push(element.styles.transform.generated.final);
} else {
styles.push(element.styles.opacity.generated);
styles.push(element.styles.transform.generated.initial);
}
element.node.setAttribute('style', styles.filter(function (s) { return s !== ''; }).join(' '));
});
each(this.store.containers, function (container) {
var target =
container.node === document.documentElement ? window : container.node;
target.addEventListener('scroll', this$1.delegate);
target.addEventListener('resize', this$1.delegate);
});
/**
* Manually invoke delegate once to capture
* element and container dimensions, container
* scroll position, and trigger any valid reveals
*/
this.delegate();
/**
* Wipe any existing `setTimeout` now
* that initialization has completed.
*/
this.initTimeout = null;
}
function isMobile(agent) {
if ( agent === void 0 ) agent = navigator.userAgent;
return /Android|iPhone|iPad|iPod/i.test(agent)
}
function deepAssign(target) {
var sources = [], len = arguments.length - 1;
while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
if (isObject(target)) {
each(sources, function (source) {
each(source, function (data, key) {
if (isObject(data)) {
if (!target[key] || !isObject(target[key])) {
target[key] = {};
}
deepAssign(target[key], data);
} else {
target[key] = data;
}
});
});
return target
} else {
throw new TypeError('Target must be an object literal.')
}
}
function reveal(target, options, interval, sync) {
var this$1 = this;
/**
* The reveal method has optional 2nd and 3rd parameters,
* so we first explicitly check what was passed in.
*/
if (typeof options === 'number') {
interval = parseInt(options);
options = {};
} else {
interval = parseInt(interval);
options = options || {};
}
var containerBuffer = [];
var sequence$$1;
try {
if (interval) {
if (interval >= 16) {
sequence$$1 = new Sequence(interval);
} else {
throw new RangeError('Sequence interval must be at least 16ms.')
}
}
var nodes = index(target);
if (!nodes.length) {
throw new Error('Invalid reveal target.')
}
var elements = nodes.reduce(function (elementBuffer, elementNode) {
var element = {};
var existingId = elementNode.getAttribute('data-sr-id');
if (existingId) {
deepAssign(element, this$1.store.elements[existingId]);
/**
* In order to prevent previously generated styles
* from throwing off the new styles, the style tag
* has to be reverted to its pre-reveal state.
*/
element.node.setAttribute('style', element.styles.inline.computed);
} else {
element.id = nextUniqueId();
element.node = elementNode;
element.seen = false;
element.revealed = false;
element.visible = false;
}
var config = deepAssign({}, element.config || this$1.defaults, options);
if ((!config.mobile && isMobile()) || (!config.desktop && !isMobile())) {
if (existingId) {
clean.call(this$1, element);
}
return elementBuffer // skip elements that are disabled
}
var containerNode = index(config.container)[0];
if (!containerNode) {
throw new Error('Invalid container.')
}
if (!containerNode.contains(elementNode)) {
return elementBuffer // skip elements found outside the container
}
var containerId;
{
containerId = getContainerId(
containerNode,
containerBuffer,
this$1.store.containers
);
if (containerId === null) {
containerId = nextUniqueId();
containerBuffer.push({ id: containerId, node: containerNode });
}
}
element.config = config;
element.containerId = containerId;
element.styles = style(element);
if (sequence$$1) {
element.sequence = {
id: sequence$$1.id,
index: sequence$$1.members.length
};
sequence$$1.members.push(element.id);
}
elementBuffer.push(element);
return elementBuffer
}, []);
/**
* Modifying the DOM via setAttribute needs to be handled
* separately from reading computed styles in the map above
* for the browser to batch DOM changes (limiting reflows)
*/
each(elements, function (element) {
this$1.store.elements[element.id] = element;
element.node.setAttribute('data-sr-id', element.id);
});
} catch (e) {
return logger.call(this, 'Reveal failed.', e.stack || e.message)
}
/**
* Now that element set-up is complete...
* Let’s commit any container and sequence data we have to the store.
*/
each(containerBuffer, function (container) {
this$1.store.containers[container.id] = {
id: container.id,
node: container.node
};
});
if (sequence$$1) {
this.store.sequences[sequence$$1.id] = sequence$$1;
}
/**
* If reveal wasn't invoked by sync, we want to
* make sure to add this call to the history.
*/
if (!sync) {
this.store.history.push({ target: target, options: options, interval: interval });
/**
* Push initialization to the event queue, giving
* multiple reveal calls time to be interpreted.
*/
if (this.initTimeout) {
window.clearTimeout(this.initTimeout);
}
this.initTimeout = window.setTimeout(initialize.bind(this), 0);
}
}
function getContainerId(node) {
var collections = [], len = arguments.length - 1;
while ( len-- > 0 ) collections[ len ] = arguments[ len + 1 ];
var id = null;
each(collections, function (collection) {
each(collection, function (container) {
if (id === null && container.node === node) {
id = container.id;
}
});
});
return id
}
/**
* Re-runs the reveal method for each record stored in history,
* for capturing new content asynchronously loaded into the DOM.
*/
function sync() {
var this$1 = this;
each(this.store.history, function (record) {
reveal.call(this$1, record.target, record.options, record.interval, true);
});
initialize.call(this);
}
var polyfill = function (x) { return (x > 0) - (x < 0) || +x; };
var mathSign = Math.sign || polyfill
/*! @license miniraf v1.0.0
Copyright 2018 Fisssion LLC.
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.
*/
var polyfill$1 = (function () {
var clock = Date.now();
return function (callback) {
var currentTime = Date.now();
if (currentTime - clock > 16) {
clock = currentTime;
callback(currentTime);
} else {
setTimeout(function () { return polyfill$1(callback); }, 0);
}
}
})();
var index$1 = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
polyfill$1;
function getGeometry(target, isContainer) {
/**
* We want to ignore padding and scrollbars for container elements.
* More information here: https://goo.gl/vOZpbz
*/
var height = isContainer ? target.node.clientHeight : target.node.offsetHeight;
var width = isContainer ? target.node.clientWidth : target.node.offsetWidth;
var offsetTop = 0;
var offsetLeft = 0;
var node = target.node;
do {
if (!isNaN(node.offsetTop)) {
offsetTop += node.offsetTop;
}
if (!isNaN(node.offsetLeft)) {
offsetLeft += node.offsetLeft;
}
node = node.offsetParent;
} while (node)
return {
bounds: {
top: offsetTop,
right: offsetLeft + width,
bottom: offsetTop + height,
left: offsetLeft
},
height: height,
width: width
}
}
function getScrolled(container) {
var top, left;
if (container.node === document.documentElement) {
top = window.pageYOffset;
left = window.pageXOffset;
} else {
top = container.node.scrollTop;
left = container.node.scrollLeft;
}
return { top: top, left: left }
}
function isElementVisible(element) {
var container = this.store.containers[element.containerId];
var viewFactor = Math.max(0, Math.min(1, element.config.viewFactor));
var viewOffset = element.config.viewOffset;
var elementBounds = {
top: element.geometry.bounds.top + element.geometry.height * viewFactor,
right: element.geometry.bounds.right - element.geometry.width * viewFactor,
bottom: element.geometry.bounds.bottom - element.geometry.height * viewFactor,
left: element.geometry.bounds.left + element.geometry.width * viewFactor
};
var containerBounds = {
top: container.geometry.bounds.top + container.scroll.top + viewOffset.top,
right: container.geometry.bounds.right + container.scroll.left - viewOffset.right,
bottom:
container.geometry.bounds.bottom + container.scroll.top - viewOffset.bottom,
left: container.geometry.bounds.left + container.scroll.left + viewOffset.left
};
return (
(elementBounds.top < containerBounds.bottom &&
elementBounds.right > containerBounds.left &&
elementBounds.bottom > containerBounds.top &&
elementBounds.left < containerBounds.right) ||
element.styles.position === 'fixed'
)
}
function delegate(
event,
elements
) {
var this$1 = this;
if ( event === void 0 ) event = { type: 'init' };
if ( elements === void 0 ) elements = this.store.elements;
index$1(function () {
var stale = event.type === 'init' || event.type === 'resize';
each(this$1.store.containers, function (container) {
if (stale) {
container.geometry = getGeometry.call(this$1, container, true);
}
var scroll = getScrolled.call(this$1, container);
if (container.scroll) {
container.direction = {
x: mathSign(scroll.left - container.scroll.left),
y: mathSign(scroll.top - container.scroll.top)
};
}
container.scroll = scroll;
});
/**
* Due to how the sequencer is implemented, it’s
* important that we update the state of all
* elements, before any animation logic is
* evaluated (in the second loop below).
*/
each(elements, function (element) {
if (stale) {
element.geometry = getGeometry.call(this$1, element);
}
element.visible = isElementVisible.call(this$1, element);
});
each(elements, function (element) {
if (element.sequence) {
sequence.call(this$1, element);
} else {
animate.call(this$1, element);
}
});
this$1.pristine = false;
});
}
function transformSupported() {
var style = document.documentElement.style;
return 'transform' in style || 'WebkitTransform' in style
}
function transitionSupported() {
var style = document.documentElement.style;
return 'transition' in style || 'WebkitTransition' in style
}
var version = "4.0.0-beta.26";
var _config;
var _debug;
var _instance;
function ScrollReveal(options) {
var this$1 = this;
if ( options === void 0 ) options = {};
var invokedWithoutNew =
typeof this === 'undefined' ||
Object.getPrototypeOf(this) !== ScrollReveal.prototype;
if (invokedWithoutNew) {
return new ScrollReveal(options)
}
if (!ScrollReveal.isSupported()) {
logger.call(this, 'Instantiation aborted.', 'This browser is not supported.');
return noop
}
/**
* Here we use `buffer` to validate our configuration, before
* assigning the contents to the private variable `_config`.
*/
var buffer;
{
try {
buffer = _config
? deepAssign({}, _config, options)
: deepAssign({}, defaults, options);
} catch (e) {
logger.call(
this,
'Instantiation failed.',
'Invalid configuration.',
e.message
);
return noop
}
try {
var container = index(buffer.container)[0];
if (!container) {
throw new Error('Invalid container.')
}
if ((!buffer.mobile && isMobile()) || (!buffer.desktop && !isMobile())) {
throw new Error('This device is disabled.')
}
} catch (e) {
logger.call(this, 'Instantiation failed.', e.message);
return noop
}
_config = buffer;
}
/**
* Modify the DOM to reflect successful instantiation.
*/
document.documentElement.classList.add('sr');
if (document.body) {
document.body.style.height = '100%';
} else {
document.addEventListener('DOMContentLoaded', function () {
document.body.style.height = '100%';
});
}
this.store = {
containers: {},
elements: {},
history: [],
sequences: {}
};
this.pristine = true;
Object.defineProperty(this, 'delegate', { get: function () { return delegate.bind(this$1); } });
Object.defineProperty(this, 'destroy', { get: function () { return destroy.bind(this$1); } });
Object.defineProperty(this, 'reveal', { get: function () { return reveal.bind(this$1); } });
Object.defineProperty(this, 'clean', { get: function () { return clean.bind(this$1); } });
Object.defineProperty(this, 'sync', { get: function () { return sync.bind(this$1); } });
Object.defineProperty(this, 'defaults', { get: function () { return _config; } });
Object.defineProperty(this, 'version', { get: function () { return version; } });
Object.defineProperty(this, 'noop', { get: function () { return false; } });
return _instance ? _instance : (_instance = this)
}
/**
* Static members are available immediately during instantiation,
* so debugging and browser support details are handled here.
*/
ScrollReveal.isSupported = function () { return transformSupported() && transitionSupported(); };
Object.defineProperty(ScrollReveal, 'debug', {
get: function () { return _debug || false; },
set: function (value) {
if (typeof value === 'boolean') { _debug = value; }
}
});
ScrollReveal();
return ScrollReveal;
})));
|
import filter from './filter.js';
// Trim out all falsy values from an array.
export default function compact(array) {
return filter(array, Boolean);
}
|
var utils = require('../../../util/utils');
var teamManager = require('../../../services/teamManager');
module.exports = function(){
return new TeamRemote();
};
var TeamRemote = function(){
};
// can a player create a game copy
TeamRemote.prototype.canCreateGameCopy = function(args, cb){
var playerId = args.playerId;
var teamId = args.teamId;
var result = false;
var teamObj = teamManager.getTeamById(teamId);
if(teamObj) {
result = teamObj.isCaptainById(playerId);
}
utils.invokeCallback(cb, null, result);
};
// create a new team
TeamRemote.prototype.createTeam = function(args, cb) {
utils.myPrint('TeamRemote ~ createTeam is running ...typeof args = ', typeof args);
utils.myPrint('args = ', args);
utils.myPrint('playerInfo = ', JSON.stringify(args.playerInfo));
var ret = teamManager.createTeam(args);
utils.invokeCallback(cb, null, ret);
};
// disband a team
TeamRemote.prototype.disbandTeamById = function(args, cb){
var playerId = args.playerId;
var teamId = args.teamId;
var ret = teamManager.disbandTeamById(playerId, teamId);
utils.myPrint('TeamRemote ~ DisbandTeamById is running ~ ret = ', ret);
utils.invokeCallback(cb, null, ret);
};
// leave a team
TeamRemote.prototype.leaveTeamById = function(args, cb){
var playerId = args.playerId;
var teamId = args.teamId;
teamManager.leaveTeamById(playerId, teamId, cb);
};
// drag the team members to the game copy
TeamRemote.prototype.dragMember2gameCopy = function(args, cb) {
utils.myPrint('1 ~ DragMember2gameCopy ~ args = ', JSON.stringify(args));
teamManager.dragMember2gameCopy(args, cb);
};
// applicant apply to join the team
TeamRemote.prototype.applyJoinTeam = function(args, cb){
utils.myPrint('ApplyJoinTeam is running ... args = ', JSON.stringify(args));
var ret = teamManager.applyJoinTeam(args);
utils.invokeCallback(cb, null, ret);
};
// accept applicant join team
TeamRemote.prototype.acceptApplicantJoinTeam = function(args, cb){
utils.myPrint('AcceptApplicantJoinTeam is running ... args = ', JSON.stringify(args));
var ret = teamManager.acceptApplicantJoinTeam(args);
utils.myPrint('AcceptApplicantJoinTeam ~ ret = ', ret);
utils.invokeCallback(cb, null, ret);
};
// captain invite a player to join the team
TeamRemote.prototype.inviteJoinTeam = function(args, cb){
utils.myPrint('InviteJoinTeam is running ... args = ', JSON.stringify(args));
var ret = teamManager.inviteJoinTeam(args);
utils.invokeCallback(cb, null, ret);
};
// accept captain's invitation join team
TeamRemote.prototype.acceptInviteJoinTeam = function(args, cb){
utils.myPrint('AcceptInviteJoinTeam is running ... args = ', JSON.stringify(args));
var ret = teamManager.acceptInviteJoinTeam(args);
utils.myPrint('AcceptInviteJoinTeam ~ ret = ', ret);
utils.invokeCallback(cb, null, ret);
};
// update team member's new info
TeamRemote.prototype.updateMemberInfo = function(args, cb){
utils.myPrint('UpdateMemberInfo is running ... args = ', JSON.stringify(args));
var ret = teamManager.updateMemberInfo(args);
utils.myPrint('UpdateMemberInfo ~ ret = ', JSON.stringify(ret));
utils.invokeCallback(cb, null, ret);
};
// chat in team
TeamRemote.prototype.chatInTeam = function(args, cb){
utils.myPrint('ChatInTeam is running ... args = ', JSON.stringify(args));
var ret = teamManager.chatInTeam(args);
utils.invokeCallback(cb, null, ret);
};
// leave a team
TeamRemote.prototype.kickOut = function(args, cb){
teamManager.kickOut(args, cb);
};
|
/**
* opus-recorder plugin for videojs-record
* @version 2.1.0
* @see https://github.com/collab-project/videojs-record
* @copyright 2014-2018 Collab
* @license MIT
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.opusRecorder = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; }
/**
* @file opus-recorder-plugin.js
* @since 1.1.0
*/
var RecordEngine = videojs.getComponent('RecordEngine');
/**
* Audio-only engine for the opus-recorder library.
*
* Audio is encoded using libopus.
*
* @class
* @augments videojs.RecordEngine
*/
var OpusRecorderEngine = function (_RecordEngine) {
_inherits(OpusRecorderEngine, _RecordEngine);
function OpusRecorderEngine() {
_classCallCheck(this, OpusRecorderEngine);
return _possibleConstructorReturn(this, (OpusRecorderEngine.__proto__ || Object.getPrototypeOf(OpusRecorderEngine)).apply(this, arguments));
}
_createClass(OpusRecorderEngine, [{
key: 'setup',
/**
* Setup recording engine.
*/
value: function setup(stream, mediaType, debug) {
this.inputStream = stream;
this.mediaType = mediaType;
this.debug = debug;
// also supports 'audio/wav'; but make sure to use waveEncoder worker
// in that case
this.audioType = 'audio/ogg';
this.engine = new Recorder({
leaveStreamOpen: true,
numberOfChannels: this.audioChannels,
bufferLength: this.bufferSize,
encoderSampleRate: this.sampleRate,
encoderPath: this.audioWorkerURL
});
this.engine.ondataavailable = this.onRecordingAvailable.bind(this);
this.audioContext = new AudioContext();
this.audioSourceNode = this.audioContext.createMediaStreamSource(this.inputStream);
}
/**
* Start recording.
*/
}, {
key: 'start',
value: function start() {
var _this2 = this;
this.engine.start(this.audioSourceNode).then(function () {
// recording started ok
}).catch(function (err) {
// can't start playback
_this2.player().trigger('error', err);
});
}
/**
* Stop recording.
*/
}, {
key: 'stop',
value: function stop() {
this.engine.stop();
}
/**
* Pause recording.
*/
}, {
key: 'pause',
value: function pause() {
this.engine.pause();
}
/**
* Resume recording.
*/
}, {
key: 'resume',
value: function resume() {
this.engine.resume();
}
/**
* @private
*/
}, {
key: 'onRecordingAvailable',
value: function onRecordingAvailable(data) {
// Opus format stored in an Ogg container
var blob = new Blob([data], { type: this.audioType });
this.onStopRecording(blob);
}
}]);
return OpusRecorderEngine;
}(RecordEngine);
// expose plugin
videojs.OpusRecorderEngine = OpusRecorderEngine;
exports.default = OpusRecorderEngine;
},{}]},{},[1])(1)
}); |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.0
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.radioButton
* @description radioButton module!
*/
angular.module('material.components.radioButton', [
'material.core'
])
.directive('mdRadioGroup', mdRadioGroupDirective)
.directive('mdRadioButton', mdRadioButtonDirective);
/**
* @ngdoc directive
* @module material.components.radioButton
* @name mdRadioGroup
*
* @restrict E
*
* @description
* The `<md-radio-group>` directive identifies a grouping
* container for the 1..n grouped radio buttons; specified using nested
* `<md-radio-button>` tags.
*
* As per the [material design spec](http://www.google.com/design/spec/style/color.html#color-ui-color-application)
* the radio button is in the accent color by default. The primary color palette may be used with
* the `md-primary` class.
*
* Note: `<md-radio-group>` and `<md-radio-button>` handle tabindex differently
* than the native `<input type='radio'>` controls. Whereas the native controls
* force the user to tab through all the radio buttons, `<md-radio-group>`
* is focusable, and by default the `<md-radio-button>`s are not.
*
* @param {string} ng-model Assignable angular expression to data-bind to.
* @param {boolean=} md-no-ink Use of attribute indicates flag to disable ink ripple effects.
*
* @usage
* <hljs lang="html">
* <md-radio-group ng-model="selected">
*
* <md-radio-button
* ng-repeat="d in colorOptions"
* ng-value="d.value" aria-label="{{ d.label }}">
*
* {{ d.label }}
*
* </md-radio-button>
*
* </md-radio-group>
* </hljs>
*
*/
function mdRadioGroupDirective($mdUtil, $mdConstant, $mdTheming, $timeout) {
RadioGroupController.prototype = createRadioGroupControllerProto();
return {
restrict: 'E',
controller: ['$element', RadioGroupController],
require: ['mdRadioGroup', '?ngModel'],
link: { pre: linkRadioGroup }
};
function linkRadioGroup(scope, element, attr, ctrls) {
$mdTheming(element);
var rgCtrl = ctrls[0];
var ngModelCtrl = ctrls[1] || $mdUtil.fakeNgModel();
function setFocus() {
if (!element.hasClass('md-focused')) { element.addClass('md-focused'); }
}
function keydownListener(ev) {
var keyCode = ev.which || ev.keyCode;
switch(keyCode) {
case $mdConstant.KEY_CODE.LEFT_ARROW:
case $mdConstant.KEY_CODE.UP_ARROW:
ev.preventDefault();
rgCtrl.selectPrevious();
setFocus();
break;
case $mdConstant.KEY_CODE.RIGHT_ARROW:
case $mdConstant.KEY_CODE.DOWN_ARROW:
ev.preventDefault();
rgCtrl.selectNext();
setFocus();
break;
case $mdConstant.KEY_CODE.ENTER:
var form = angular.element($mdUtil.getClosest(element[0], 'form'));
if (form.length > 0) {
form.triggerHandler('submit');
}
break;
}
}
rgCtrl.init(ngModelCtrl);
scope.mouseActive = false;
element.attr({
'role': 'radiogroup',
'tabIndex': element.attr('tabindex') || '0'
})
.on('keydown', keydownListener)
.on('mousedown', function(event) {
scope.mouseActive = true;
$timeout(function() {
scope.mouseActive = false;
}, 100);
})
.on('focus', function() {
if(scope.mouseActive === false) { rgCtrl.$element.addClass('md-focused'); }
})
.on('blur', function() { rgCtrl.$element.removeClass('md-focused'); });
}
function RadioGroupController($element) {
this._radioButtonRenderFns = [];
this.$element = $element;
}
function createRadioGroupControllerProto() {
return {
init: function(ngModelCtrl) {
this._ngModelCtrl = ngModelCtrl;
this._ngModelCtrl.$render = angular.bind(this, this.render);
},
add: function(rbRender) {
this._radioButtonRenderFns.push(rbRender);
},
remove: function(rbRender) {
var index = this._radioButtonRenderFns.indexOf(rbRender);
if (index !== -1) {
this._radioButtonRenderFns.splice(index, 1);
}
},
render: function() {
this._radioButtonRenderFns.forEach(function(rbRender) {
rbRender();
});
},
setViewValue: function(value, eventType) {
this._ngModelCtrl.$setViewValue(value, eventType);
// update the other radio buttons as well
this.render();
},
getViewValue: function() {
return this._ngModelCtrl.$viewValue;
},
selectNext: function() {
return changeSelectedButton(this.$element, 1);
},
selectPrevious: function() {
return changeSelectedButton(this.$element, -1);
},
setActiveDescendant: function (radioId) {
this.$element.attr('aria-activedescendant', radioId);
}
};
}
/**
* Change the radio group's selected button by a given increment.
* If no button is selected, select the first button.
*/
function changeSelectedButton(parent, increment) {
// Coerce all child radio buttons into an array, then wrap then in an iterator
var buttons = $mdUtil.iterator(parent[0].querySelectorAll('md-radio-button'), true);
if (buttons.count()) {
var validate = function (button) {
// If disabled, then NOT valid
return !angular.element(button).attr("disabled");
};
var selected = parent[0].querySelector('md-radio-button.md-checked');
var target = buttons[increment < 0 ? 'previous' : 'next'](selected, validate) || buttons.first();
// Activate radioButton's click listener (triggerHandler won't create a real click event)
angular.element(target).triggerHandler('click');
}
}
}
mdRadioGroupDirective.$inject = ["$mdUtil", "$mdConstant", "$mdTheming", "$timeout"];
/**
* @ngdoc directive
* @module material.components.radioButton
* @name mdRadioButton
*
* @restrict E
*
* @description
* The `<md-radio-button>`directive is the child directive required to be used within `<md-radio-group>` elements.
*
* While similar to the `<input type="radio" ng-model="" value="">` directive,
* the `<md-radio-button>` directive provides ink effects, ARIA support, and
* supports use within named radio groups.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression which sets the value to which the expression should
* be set when selected.*
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} aria-label Adds label to radio button for accessibility.
* Defaults to radio button's text. If no text content is available, a warning will be logged.
*
* @usage
* <hljs lang="html">
*
* <md-radio-button value="1" aria-label="Label 1">
* Label 1
* </md-radio-button>
*
* <md-radio-button ng-model="color" ng-value="specialValue" aria-label="Green">
* Green
* </md-radio-button>
*
* </hljs>
*
*/
function mdRadioButtonDirective($mdAria, $mdUtil, $mdTheming) {
var CHECKED_CSS = 'md-checked';
return {
restrict: 'E',
require: '^mdRadioGroup',
transclude: true,
template: '<div class="md-container" md-ink-ripple md-ink-ripple-checkbox>' +
'<div class="md-off"></div>' +
'<div class="md-on"></div>' +
'</div>' +
'<div ng-transclude class="md-label"></div>',
link: link
};
function link(scope, element, attr, rgCtrl) {
var lastChecked;
$mdTheming(element);
configureAria(element, scope);
rgCtrl.add(render);
attr.$observe('value', render);
element
.on('click', listener)
.on('$destroy', function() {
rgCtrl.remove(render);
});
function listener(ev) {
if (element[0].hasAttribute('disabled')) return;
scope.$apply(function() {
rgCtrl.setViewValue(attr.value, ev && ev.type);
});
}
function render() {
var checked = (rgCtrl.getViewValue() == attr.value);
if (checked === lastChecked) {
return;
}
lastChecked = checked;
element.attr('aria-checked', checked);
if (checked) {
element.addClass(CHECKED_CSS);
rgCtrl.setActiveDescendant(element.attr('id'));
} else {
element.removeClass(CHECKED_CSS);
}
}
/**
* Inject ARIA-specific attributes appropriate for each radio button
*/
function configureAria( element, scope ){
scope.ariaId = buildAriaID();
element.attr({
'id' : scope.ariaId,
'role' : 'radio',
'aria-checked' : 'false'
});
$mdAria.expectWithText(element, 'aria-label');
/**
* Build a unique ID for each radio button that will be used with aria-activedescendant.
* Preserve existing ID if already specified.
* @returns {*|string}
*/
function buildAriaID() {
return attr.id || ( 'radio' + "_" + $mdUtil.nextUid() );
}
}
}
}
mdRadioButtonDirective.$inject = ["$mdAria", "$mdUtil", "$mdTheming"];
})(window, window.angular); |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["VueFire"] = factory();
else
root["VueFire"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
var Vue // late binding
/**
* Returns the key of a Firebase snapshot across SDK versions.
*
* @param {FirebaseSnapshot} snapshot
* @return {string|null}
*/
function _getKey (snapshot) {
return typeof snapshot.key === 'function'
? snapshot.key()
: snapshot.key
}
/**
* Returns the original reference of a Firebase reference or query across SDK versions.
*
* @param {FirebaseReference|FirebaseQuery} refOrQuery
* @return {FirebaseReference}
*/
function _getRef (refOrQuery) {
if (typeof refOrQuery.ref === 'function') {
refOrQuery = refOrQuery.ref()
} else if (typeof refOrQuery.ref === 'object') {
refOrQuery = refOrQuery.ref
}
return refOrQuery
}
/**
* Check if a value is an object.
*
* @param {*} val
* @return {boolean}
*/
function isObject (val) {
return Object.prototype.toString.call(val) === '[object Object]'
}
/**
* Convert firebase snapshot into a bindable data record.
*
* @param {FirebaseSnapshot} snapshot
* @return {Object}
*/
function createRecord (snapshot) {
var value = snapshot.val()
var res = isObject(value)
? value
: { '.value': value }
res['.key'] = _getKey(snapshot)
return res
}
/**
* Find the index for an object with given key.
*
* @param {array} array
* @param {string} key
* @return {number}
*/
function indexForKey (array, key) {
for (var i = 0; i < array.length; i++) {
if (array[i]['.key'] === key) {
return i
}
}
/* istanbul ignore next */
return -1
}
/**
* Bind a firebase data source to a key on a vm.
*
* @param {Vue} vm
* @param {string} key
* @param {object} source
*/
function bind (vm, key, source) {
var asObject = false
var cancelCallback = null
var readyCallback = null
// check { source, asArray, cancelCallback } syntax
if (isObject(source) && source.hasOwnProperty('source')) {
asObject = source.asObject
cancelCallback = source.cancelCallback
readyCallback = source.readyCallback
source = source.source
}
if (!isObject(source)) {
throw new Error('VueFire: invalid Firebase binding source.')
}
var ref = _getRef(source)
vm.$firebaseRefs[key] = ref
vm._firebaseSources[key] = source
if (cancelCallback) {
cancelCallback = cancelCallback.bind(vm)
}
// bind based on initial value type
if (asObject) {
bindAsObject(vm, key, source, cancelCallback)
} else {
bindAsArray(vm, key, source, cancelCallback)
}
if (readyCallback) {
source.once('value', readyCallback.bind(vm))
}
}
/**
* Define a reactive property in a given vm if it's not defined
* yet
*
* @param {Vue} vm
* @param {string} key
* @param {*} val
*/
function defineReactive (vm, key, val) {
if (key in vm) {
vm[key] = val
} else {
Vue.util.defineReactive(vm, key, val)
}
}
/**
* Bind a firebase data source to a key on a vm as an Array.
*
* @param {Vue} vm
* @param {string} key
* @param {object} source
* @param {function|null} cancelCallback
*/
function bindAsArray (vm, key, source, cancelCallback) {
var array = []
defineReactive(vm, key, array)
var onAdd = source.on('child_added', function (snapshot, prevKey) {
var index = prevKey ? indexForKey(array, prevKey) + 1 : 0
array.splice(index, 0, createRecord(snapshot))
}, cancelCallback)
var onRemove = source.on('child_removed', function (snapshot) {
var index = indexForKey(array, _getKey(snapshot))
array.splice(index, 1)
}, cancelCallback)
var onChange = source.on('child_changed', function (snapshot) {
var index = indexForKey(array, _getKey(snapshot))
array.splice(index, 1, createRecord(snapshot))
}, cancelCallback)
var onMove = source.on('child_moved', function (snapshot, prevKey) {
var index = indexForKey(array, _getKey(snapshot))
var record = array.splice(index, 1)[0]
var newIndex = prevKey ? indexForKey(array, prevKey) + 1 : 0
array.splice(newIndex, 0, record)
}, cancelCallback)
vm._firebaseListeners[key] = {
child_added: onAdd,
child_removed: onRemove,
child_changed: onChange,
child_moved: onMove
}
}
/**
* Bind a firebase data source to a key on a vm as an Object.
*
* @param {Vue} vm
* @param {string} key
* @param {Object} source
* @param {function|null} cancelCallback
*/
function bindAsObject (vm, key, source, cancelCallback) {
defineReactive(vm, key, {})
var cb = source.on('value', function (snapshot) {
vm[key] = createRecord(snapshot)
}, cancelCallback)
vm._firebaseListeners[key] = { value: cb }
}
/**
* Unbind a firebase-bound key from a vm.
*
* @param {Vue} vm
* @param {string} key
*/
function unbind (vm, key) {
var source = vm._firebaseSources && vm._firebaseSources[key]
if (!source) {
throw new Error(
'VueFire: unbind failed: "' + key + '" is not bound to ' +
'a Firebase reference.'
)
}
var listeners = vm._firebaseListeners[key]
for (var event in listeners) {
source.off(event, listeners[event])
}
vm[key] = null
vm.$firebaseRefs[key] = null
vm._firebaseSources[key] = null
vm._firebaseListeners[key] = null
}
/**
* Ensure the related bookkeeping variables on an instance.
*
* @param {Vue} vm
*/
function ensureRefs (vm) {
if (!vm.$firebaseRefs) {
vm.$firebaseRefs = Object.create(null)
vm._firebaseSources = Object.create(null)
vm._firebaseListeners = Object.create(null)
}
}
var init = function () {
var bindings = this.$options.firebase
if (typeof bindings === 'function') bindings = bindings.call(this)
if (!bindings) return
ensureRefs(this)
for (var key in bindings) {
bind(this, key, bindings[key])
}
}
var VueFireMixin = {
created: init, // 1.x and 2.x
beforeDestroy: function () {
if (!this.$firebaseRefs) return
for (var key in this.$firebaseRefs) {
if (this.$firebaseRefs[key]) {
this.$unbind(key)
}
}
this.$firebaseRefs = null
this._firebaseSources = null
this._firebaseListeners = null
}
}
/**
* Install function passed to Vue.use() in manual installation.
*
* @param {function} _Vue
*/
function install (_Vue) {
Vue = _Vue
Vue.mixin(VueFireMixin)
// use object-based merge strategy
// TODO This makes impossible to merge functions
var mergeStrats = Vue.config.optionMergeStrategies
mergeStrats.firebase = mergeStrats.provide
// extend instance methods
Vue.prototype.$bindAsObject = function (key, source, cancelCallback, readyCallback) {
ensureRefs(this)
bind(this, key, {
source: source,
asObject: true,
cancelCallback: cancelCallback,
readyCallback: readyCallback
})
}
Vue.prototype.$bindAsArray = function (key, source, cancelCallback, readyCallback) {
ensureRefs(this)
bind(this, key, {
source: source,
cancelCallback: cancelCallback,
readyCallback: readyCallback
})
}
Vue.prototype.$unbind = function (key) {
unbind(this, key)
}
}
// auto install
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
module.exports = install
/***/ })
/******/ ])
});
; |
// Copyright (c) 2015 Uber Technologies, 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.
'use strict';
var inherits = require('util').inherits;
var TChannelPeersBase = require('./peers_base.js');
var PeerHeap = require('./peer_heap.js');
function TChannelSubPeers(channel, options) {
if (!(this instanceof TChannelSubPeers)) {
return new TChannelSubPeers(channel, options);
}
var self = this;
TChannelPeersBase.call(self, channel, options);
self.peerScoreThreshold = self.options.peerScoreThreshold || 0;
self._heap = new PeerHeap();
self.choosePeerWithHeap = channel.choosePeerWithHeap;
}
inherits(TChannelSubPeers, TChannelPeersBase);
TChannelSubPeers.prototype.close = function close(callback) {
var self = this;
var peers = self.values();
TChannelPeersBase.prototype.close.call(self, peers, callback);
};
TChannelSubPeers.prototype.add = function add(hostPort, options) {
/* eslint max-statements: [2, 25]*/
var self = this;
var peer = self._map[hostPort];
if (peer) {
return peer;
}
var topChannel = self.channel.topChannel;
if (hostPort === topChannel.hostPort) {
return topChannel.peers.getSelfPeer();
}
peer = topChannel.peers.add(hostPort, options);
self._map[hostPort] = peer;
self._keys.push(hostPort);
var el = self._heap.add(peer);
peer.heapElements.push(el);
return peer;
};
TChannelSubPeers.prototype.clear = function clear() {
var self = this;
self._map = Object.create(null);
self._keys = [];
self._heap.clear();
};
TChannelSubPeers.prototype._delete = function _del(peer) {
var self = this;
var index = self._keys.indexOf(peer.hostPort);
if (index === -1) {
return;
}
delete self._map[peer.hostPort];
popout(self._keys, index);
for (var i = 0; i < peer.heapElements.length; i++) {
var el = peer.heapElements[i];
if (el.heap === self._heap) {
el.heap.remove(el.index);
popout(peer.heapElements, i);
break;
}
}
};
TChannelSubPeers.prototype.choosePeer = function choosePeer(req) {
var self = this;
if (self.choosePeerWithHeap) {
return self.chooseHeapPeer(req);
}
return self.chooseLinearPeer(req);
};
TChannelSubPeers.prototype.chooseLinearPeer = function chooseLinearPeer(req) {
/* eslint complexity: [2, 15]*/
var self = this;
var hosts = self._keys;
if (!hosts || !hosts.length) {
return null;
}
var threshold = self.peerScoreThreshold;
var selectedPeer = null;
var selectedScore = 0;
for (var i = 0; i < hosts.length; i++) {
var hostPort = hosts[i];
var peer = self._map[hostPort];
if (!req || !req.triedRemoteAddrs || !req.triedRemoteAddrs[hostPort]) {
var score = peer.handler.getScore(req);
var want = score > threshold &&
(selectedPeer === null || score > selectedScore);
if (want) {
selectedPeer = peer;
selectedScore = score;
}
}
}
return selectedPeer;
};
TChannelSubPeers.prototype.chooseHeapPeer = function chooseHeapPeer(req) {
var self = this;
if (req && req.triedRemoteAddrs) {
return self._choosePeerSkipTried(req);
}
return self._heap.choose(self.peerScoreThreshold);
};
TChannelSubPeers.prototype._choosePeerSkipTried =
function _choosePeerSkipTried(req) {
var self = this;
return self._heap.choose(self.peerScoreThreshold, filterTriedPeers);
function filterTriedPeers(peer) {
return !req.triedRemoteAddrs[peer.hostPort];
}
};
function popout(array, i) {
if (!array.length) {
return;
}
var j = array.length - 1;
if (i !== j) {
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
array.pop();
}
module.exports = TChannelSubPeers;
|
// Generated by CoffeeScript 1.12.2
(function() {
var BALANCED_PAIRS, CALL_CLOSERS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, generate, k, left, len, ref, rite,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
slice = [].slice;
generate = function(tag, value, origin) {
var tok;
tok = [tag, value];
tok.generated = true;
if (origin) {
tok.origin = origin;
}
return tok;
};
exports.Rewriter = (function() {
function Rewriter() {}
Rewriter.prototype.rewrite = function(tokens1) {
this.tokens = tokens1;
this.removeLeadingNewlines();
this.closeOpenCalls();
this.closeOpenIndexes();
this.normalizeLines();
this.tagPostfixConditionals();
this.addImplicitBracesAndParens();
this.addLocationDataToGeneratedTokens();
this.fixOutdentLocationData();
return this.tokens;
};
Rewriter.prototype.scanTokens = function(block) {
var i, token, tokens;
tokens = this.tokens;
i = 0;
while (token = tokens[i]) {
i += block.call(this, token, i, tokens);
}
return true;
};
Rewriter.prototype.detectEnd = function(i, condition, action) {
var levels, ref, ref1, token, tokens;
tokens = this.tokens;
levels = 0;
while (token = tokens[i]) {
if (levels === 0 && condition.call(this, token, i)) {
return action.call(this, token, i);
}
if (!token || levels < 0) {
return action.call(this, token, i - 1);
}
if (ref = token[0], indexOf.call(EXPRESSION_START, ref) >= 0) {
levels += 1;
} else if (ref1 = token[0], indexOf.call(EXPRESSION_END, ref1) >= 0) {
levels -= 1;
}
i += 1;
}
return i - 1;
};
Rewriter.prototype.removeLeadingNewlines = function() {
var i, k, len, ref, tag;
ref = this.tokens;
for (i = k = 0, len = ref.length; k < len; i = ++k) {
tag = ref[i][0];
if (tag !== 'TERMINATOR') {
break;
}
}
if (i) {
return this.tokens.splice(0, i);
}
};
Rewriter.prototype.closeOpenCalls = function() {
var action, condition;
condition = function(token, i) {
var ref;
return ((ref = token[0]) === ')' || ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')';
};
action = function(token, i) {
return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'CALL_START') {
this.detectEnd(i + 1, condition, action);
}
return 1;
});
};
Rewriter.prototype.closeOpenIndexes = function() {
var action, condition;
condition = function(token, i) {
var ref;
return (ref = token[0]) === ']' || ref === 'INDEX_END';
};
action = function(token, i) {
return token[0] = 'INDEX_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'INDEX_START') {
this.detectEnd(i + 1, condition, action);
}
return 1;
});
};
Rewriter.prototype.indexOfTag = function() {
var fuzz, i, j, k, pattern, ref, ref1;
i = arguments[0], pattern = 2 <= arguments.length ? slice.call(arguments, 1) : [];
fuzz = 0;
for (j = k = 0, ref = pattern.length; 0 <= ref ? k < ref : k > ref; j = 0 <= ref ? ++k : --k) {
while (this.tag(i + j + fuzz) === 'HERECOMMENT') {
fuzz += 2;
}
if (pattern[j] == null) {
continue;
}
if (typeof pattern[j] === 'string') {
pattern[j] = [pattern[j]];
}
if (ref1 = this.tag(i + j + fuzz), indexOf.call(pattern[j], ref1) < 0) {
return -1;
}
}
return i + j + fuzz - 1;
};
Rewriter.prototype.looksObjectish = function(j) {
var end, index;
if (this.indexOfTag(j, '@', null, ':') > -1 || this.indexOfTag(j, null, ':') > -1) {
return true;
}
index = this.indexOfTag(j, EXPRESSION_START);
if (index > -1) {
end = null;
this.detectEnd(index + 1, (function(token) {
var ref;
return ref = token[0], indexOf.call(EXPRESSION_END, ref) >= 0;
}), (function(token, i) {
return end = i;
}));
if (this.tag(end + 1) === ':') {
return true;
}
}
return false;
};
Rewriter.prototype.findTagsBackwards = function(i, tags) {
var backStack, ref, ref1, ref2, ref3, ref4, ref5;
backStack = [];
while (i >= 0 && (backStack.length || (ref2 = this.tag(i), indexOf.call(tags, ref2) < 0) && ((ref3 = this.tag(i), indexOf.call(EXPRESSION_START, ref3) < 0) || this.tokens[i].generated) && (ref4 = this.tag(i), indexOf.call(LINEBREAKS, ref4) < 0))) {
if (ref = this.tag(i), indexOf.call(EXPRESSION_END, ref) >= 0) {
backStack.push(this.tag(i));
}
if ((ref1 = this.tag(i), indexOf.call(EXPRESSION_START, ref1) >= 0) && backStack.length) {
backStack.pop();
}
i -= 1;
}
return ref5 = this.tag(i), indexOf.call(tags, ref5) >= 0;
};
Rewriter.prototype.addImplicitBracesAndParens = function() {
var stack, start;
stack = [];
start = null;
return this.scanTokens(function(token, i, tokens) {
var endImplicitCall, endImplicitObject, forward, inImplicit, inImplicitCall, inImplicitControl, inImplicitObject, newLine, nextTag, offset, prevTag, prevToken, ref, ref1, ref2, ref3, ref4, ref5, s, sameLine, stackIdx, stackTag, stackTop, startIdx, startImplicitCall, startImplicitObject, startsLine, tag;
tag = token[0];
prevTag = (prevToken = i > 0 ? tokens[i - 1] : [])[0];
nextTag = (i < tokens.length - 1 ? tokens[i + 1] : [])[0];
stackTop = function() {
return stack[stack.length - 1];
};
startIdx = i;
forward = function(n) {
return i - startIdx + n;
};
inImplicit = function() {
var ref, ref1;
return (ref = stackTop()) != null ? (ref1 = ref[2]) != null ? ref1.ours : void 0 : void 0;
};
inImplicitCall = function() {
var ref;
return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '(';
};
inImplicitObject = function() {
var ref;
return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '{';
};
inImplicitControl = function() {
var ref;
return inImplicit && ((ref = stackTop()) != null ? ref[0] : void 0) === 'CONTROL';
};
startImplicitCall = function(j) {
var idx;
idx = j != null ? j : i;
stack.push([
'(', idx, {
ours: true
}
]);
tokens.splice(idx, 0, generate('CALL_START', '('));
if (j == null) {
return i += 1;
}
};
endImplicitCall = function() {
stack.pop();
tokens.splice(i, 0, generate('CALL_END', ')', ['', 'end of input', token[2]]));
return i += 1;
};
startImplicitObject = function(j, startsLine) {
var idx, val;
if (startsLine == null) {
startsLine = true;
}
idx = j != null ? j : i;
stack.push([
'{', idx, {
sameLine: true,
startsLine: startsLine,
ours: true
}
]);
val = new String('{');
val.generated = true;
tokens.splice(idx, 0, generate('{', val, token));
if (j == null) {
return i += 1;
}
};
endImplicitObject = function(j) {
j = j != null ? j : i;
stack.pop();
tokens.splice(j, 0, generate('}', '}', token));
return i += 1;
};
if (inImplicitCall() && (tag === 'IF' || tag === 'TRY' || tag === 'FINALLY' || tag === 'CATCH' || tag === 'CLASS' || tag === 'SWITCH')) {
stack.push([
'CONTROL', i, {
ours: true
}
]);
return forward(1);
}
if (tag === 'INDENT' && inImplicit()) {
if (prevTag !== '=>' && prevTag !== '->' && prevTag !== '[' && prevTag !== '(' && prevTag !== ',' && prevTag !== '{' && prevTag !== 'TRY' && prevTag !== 'ELSE' && prevTag !== '=') {
while (inImplicitCall()) {
endImplicitCall();
}
}
if (inImplicitControl()) {
stack.pop();
}
stack.push([tag, i]);
return forward(1);
}
if (indexOf.call(EXPRESSION_START, tag) >= 0) {
stack.push([tag, i]);
return forward(1);
}
if (indexOf.call(EXPRESSION_END, tag) >= 0) {
while (inImplicit()) {
if (inImplicitCall()) {
endImplicitCall();
} else if (inImplicitObject()) {
endImplicitObject();
} else {
stack.pop();
}
}
start = stack.pop();
}
if ((indexOf.call(IMPLICIT_FUNC, tag) >= 0 && token.spaced || tag === '?' && i > 0 && !tokens[i - 1].spaced) && (indexOf.call(IMPLICIT_CALL, nextTag) >= 0 || indexOf.call(IMPLICIT_UNSPACED_CALL, nextTag) >= 0 && !((ref = tokens[i + 1]) != null ? ref.spaced : void 0) && !((ref1 = tokens[i + 1]) != null ? ref1.newLine : void 0))) {
if (tag === '?') {
tag = token[0] = 'FUNC_EXIST';
}
startImplicitCall(i + 1);
return forward(2);
}
if (indexOf.call(IMPLICIT_FUNC, tag) >= 0 && this.indexOfTag(i + 1, 'INDENT') > -1 && this.looksObjectish(i + 2) && !this.findTagsBackwards(i, ['CLASS', 'EXTENDS', 'IF', 'CATCH', 'SWITCH', 'LEADING_WHEN', 'FOR', 'WHILE', 'UNTIL'])) {
startImplicitCall(i + 1);
stack.push(['INDENT', i + 2]);
return forward(3);
}
if (tag === ':') {
s = (function() {
var ref2;
switch (false) {
case ref2 = this.tag(i - 1), indexOf.call(EXPRESSION_END, ref2) < 0:
return start[1];
case this.tag(i - 2) !== '@':
return i - 2;
default:
return i - 1;
}
}).call(this);
while (this.tag(s - 2) === 'HERECOMMENT') {
s -= 2;
}
this.insideForDeclaration = nextTag === 'FOR';
startsLine = s === 0 || (ref2 = this.tag(s - 1), indexOf.call(LINEBREAKS, ref2) >= 0) || tokens[s - 1].newLine;
if (stackTop()) {
ref3 = stackTop(), stackTag = ref3[0], stackIdx = ref3[1];
if ((stackTag === '{' || stackTag === 'INDENT' && this.tag(stackIdx - 1) === '{') && (startsLine || this.tag(s - 1) === ',' || this.tag(s - 1) === '{')) {
return forward(1);
}
}
startImplicitObject(s, !!startsLine);
return forward(2);
}
if (inImplicitObject() && indexOf.call(LINEBREAKS, tag) >= 0) {
stackTop()[2].sameLine = false;
}
newLine = prevTag === 'OUTDENT' || prevToken.newLine;
if (indexOf.call(IMPLICIT_END, tag) >= 0 || indexOf.call(CALL_CLOSERS, tag) >= 0 && newLine) {
while (inImplicit()) {
ref4 = stackTop(), stackTag = ref4[0], stackIdx = ref4[1], (ref5 = ref4[2], sameLine = ref5.sameLine, startsLine = ref5.startsLine);
if (inImplicitCall() && prevTag !== ',') {
endImplicitCall();
} else if (inImplicitObject() && !this.insideForDeclaration && sameLine && tag !== 'TERMINATOR' && prevTag !== ':') {
endImplicitObject();
} else if (inImplicitObject() && tag === 'TERMINATOR' && prevTag !== ',' && !(startsLine && this.looksObjectish(i + 1))) {
if (nextTag === 'HERECOMMENT') {
return forward(1);
}
endImplicitObject();
} else {
break;
}
}
}
if (tag === ',' && !this.looksObjectish(i + 1) && inImplicitObject() && !this.insideForDeclaration && (nextTag !== 'TERMINATOR' || !this.looksObjectish(i + 2))) {
offset = nextTag === 'OUTDENT' ? 1 : 0;
while (inImplicitObject()) {
endImplicitObject(i + offset);
}
}
return forward(1);
});
};
Rewriter.prototype.addLocationDataToGeneratedTokens = function() {
return this.scanTokens(function(token, i, tokens) {
var column, line, nextLocation, prevLocation, ref, ref1;
if (token[2]) {
return 1;
}
if (!(token.generated || token.explicit)) {
return 1;
}
if (token[0] === '{' && (nextLocation = (ref = tokens[i + 1]) != null ? ref[2] : void 0)) {
line = nextLocation.first_line, column = nextLocation.first_column;
} else if (prevLocation = (ref1 = tokens[i - 1]) != null ? ref1[2] : void 0) {
line = prevLocation.last_line, column = prevLocation.last_column;
} else {
line = column = 0;
}
token[2] = {
first_line: line,
first_column: column,
last_line: line,
last_column: column
};
return 1;
});
};
Rewriter.prototype.fixOutdentLocationData = function() {
return this.scanTokens(function(token, i, tokens) {
var prevLocationData;
if (!(token[0] === 'OUTDENT' || (token.generated && token[0] === 'CALL_END') || (token.generated && token[0] === '}'))) {
return 1;
}
prevLocationData = tokens[i - 1][2];
token[2] = {
first_line: prevLocationData.last_line,
first_column: prevLocationData.last_column,
last_line: prevLocationData.last_line,
last_column: prevLocationData.last_column
};
return 1;
});
};
Rewriter.prototype.normalizeLines = function() {
var action, condition, indent, outdent, starter;
starter = indent = outdent = null;
condition = function(token, i) {
var ref, ref1, ref2, ref3;
return token[1] !== ';' && (ref = token[0], indexOf.call(SINGLE_CLOSERS, ref) >= 0) && !(token[0] === 'TERMINATOR' && (ref1 = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref1) >= 0)) && !(token[0] === 'ELSE' && starter !== 'THEN') && !(((ref2 = token[0]) === 'CATCH' || ref2 === 'FINALLY') && (starter === '->' || starter === '=>')) || (ref3 = token[0], indexOf.call(CALL_CLOSERS, ref3) >= 0) && this.tokens[i - 1].newLine;
};
action = function(token, i) {
return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
};
return this.scanTokens(function(token, i, tokens) {
var j, k, ref, ref1, ref2, tag;
tag = token[0];
if (tag === 'TERMINATOR') {
if (this.tag(i + 1) === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
tokens.splice.apply(tokens, [i, 1].concat(slice.call(this.indentation())));
return 1;
}
if (ref = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref) >= 0) {
tokens.splice(i, 1);
return 0;
}
}
if (tag === 'CATCH') {
for (j = k = 1; k <= 2; j = ++k) {
if (!((ref1 = this.tag(i + j)) === 'OUTDENT' || ref1 === 'TERMINATOR' || ref1 === 'FINALLY')) {
continue;
}
tokens.splice.apply(tokens, [i + j, 0].concat(slice.call(this.indentation())));
return 2 + j;
}
}
if (indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) {
starter = tag;
ref2 = this.indentation(tokens[i]), indent = ref2[0], outdent = ref2[1];
if (starter === 'THEN') {
indent.fromThen = true;
}
tokens.splice(i + 1, 0, indent);
this.detectEnd(i + 2, condition, action);
if (tag === 'THEN') {
tokens.splice(i, 1);
}
return 1;
}
return 1;
});
};
Rewriter.prototype.tagPostfixConditionals = function() {
var action, condition, original;
original = null;
condition = function(token, i) {
var prevTag, tag;
tag = token[0];
prevTag = this.tokens[i - 1][0];
return tag === 'TERMINATOR' || (tag === 'INDENT' && indexOf.call(SINGLE_LINERS, prevTag) < 0);
};
action = function(token, i) {
if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) {
return original[0] = 'POST_' + original[0];
}
};
return this.scanTokens(function(token, i) {
if (token[0] !== 'IF') {
return 1;
}
original = token;
this.detectEnd(i + 1, condition, action);
return 1;
});
};
Rewriter.prototype.indentation = function(origin) {
var indent, outdent;
indent = ['INDENT', 2];
outdent = ['OUTDENT', 2];
if (origin) {
indent.generated = outdent.generated = true;
indent.origin = outdent.origin = origin;
} else {
indent.explicit = outdent.explicit = true;
}
return [indent, outdent];
};
Rewriter.prototype.generate = generate;
Rewriter.prototype.tag = function(i) {
var ref;
return (ref = this.tokens[i]) != null ? ref[0] : void 0;
};
return Rewriter;
})();
BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END'], ['STRING_START', 'STRING_END'], ['REGEX_START', 'REGEX_END']];
exports.INVERSES = INVERSES = {};
EXPRESSION_START = [];
EXPRESSION_END = [];
for (k = 0, len = BALANCED_PAIRS.length; k < len; k++) {
ref = BALANCED_PAIRS[k], left = ref[0], rite = ref[1];
EXPRESSION_START.push(INVERSES[rite] = left);
EXPRESSION_END.push(INVERSES[left] = rite);
}
EXPRESSION_CLOSE = ['CATCH', 'THEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);
IMPLICIT_FUNC = ['IDENTIFIER', 'PROPERTY', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];
IMPLICIT_CALL = ['IDENTIFIER', 'PROPERTY', 'NUMBER', 'INFINITY', 'NAN', 'STRING', 'STRING_START', 'REGEX', 'REGEX_START', 'JS', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'UNDEFINED', 'NULL', 'BOOL', 'UNARY', 'YIELD', 'UNARY_MATH', 'SUPER', 'THROW', '@', '->', '=>', '[', '(', '{', '--', '++'];
IMPLICIT_UNSPACED_CALL = ['+', '-'];
IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];
SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];
SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];
LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];
CALL_CLOSERS = ['.', '?.', '::', '?::'];
}).call(this);
|
/*
* GoJS v2.0.12 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-2019 by Northwoods Software Corporation. All Rights Reserved.
* THIS SOFTWARE IS LICENSED. THE LICENSE AGREEMENT IS AT: https://gojs.net/2.0.12/license.html.
*/
(function() { var t;function ba(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}}function ca(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:ba(a)}}function da(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.wA=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 va(a,b){var c=-1;return function(){var d=this,e=arguments;-1!==c&&ra.clearTimeout(c);c=wa(function(){c=-1;a.apply(d,e)},b)}}function wa(a,b){return ra.setTimeout(a,b)}function ya(a){return ra.document.createElement(a)}
function v(a){throw Error(a);}function za(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=Aa(c),void 0!==d&&(c+="."+d),Ba(a,b,c))}function z(a,b,c,d){typeof a!==b&&(c=Aa(c),void 0!==d&&(c+="."+d),Ba(a,b,c))}function B(a,b,c){"number"===typeof a&&isFinite(a)||(b=Aa(b),void 0!==c&&(b+="."+c),v(b+" must be a real number type, and not NaN or Infinity: "+a))}
function Ba(a,b,c,d){b=Aa(b);c=Aa(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 Ca(a,b,c,d){c=Aa(c);void 0!==d&&(c+="."+d);v(c+" is not in the range "+b+": "+a)}function Da(a){v(("string"===typeof a.className?a.className:"")+" constructor cannot take any arguments.")}
function Ea(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 Fa(a,b){v("No property to set for this enum value: "+b+" on "+a.toString())}function Ha(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 Ja(a){return"object"===typeof a&&null!==a}function Ka(a){return Array.isArray(a)||ra.NodeList&&a instanceof ra.NodeList||ra.HTMLCollection&&a instanceof ra.HTMLCollection}function La(a,b,c){Ka(a)||Ba(a,"Array or NodeList or HTMLCollection",b,c)}
function Ma(a){return Array.prototype.slice.call(a)}function Na(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 Oa(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 Qa(){var a=Ra.pop();return void 0===a?[]:a}function Ta(a){a.length=0;Ra.push(a)}
function Aa(a){return null===a?"*":"string"===typeof a?a:"function"===typeof a&&"string"===typeof a.className?a.className:""}function Va(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(Ja(a)&&a.constructor)return Va(a.constructor);return typeof a}
function Wa(a){var b=a;Ja(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.lA;if(c&&c[b])return!0;a=Object.getPrototypeOf(a)}return!1}
function Za(a,b,c){Object.defineProperty($a.prototype,a,{get:b,set:c})}function ab(){var a=bb;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.D&&a.push(e.parentElement.D)}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"),jb=void 0!==ra.navigator&&0<ra.navigator.userAgent.indexOf("Edge/"),kb=void 0!==ra.navigator&&void 0!==ra.navigator.platform&&0<=ra.navigator.platform.toUpperCase().indexOf("MAC"),lb=void 0!==ra.navigator&&void 0!==ra.navigator.platform&&null!==ra.navigator.platform.match(/(iPhone|iPod|iPad)/i),
Ra=[];Object.freeze([]);var bb=[];sa.className="Util";sa.Dx="32ab5ff3b26f42dc0ed90f224d2913b5";sa.adym="gojs.net";sa.vfo="28e646fdb264";sa.className="Util";function D(a,b,c){qb(this);this.l=a;this.Wa=b;this.w=c}D.prototype.toString=function(){return"EnumValue."+this.Wa};function sb(a,b){return void 0===b||null===b||""===b?null:a[b]}function tb(a,b,c,d){a.classType!==b&&(c=Aa(c),void 0!==d&&(c+="."+d),Ba(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.Wa}},value:{configurable:!0,get:function(){return this.w}}});D.className="EnumValue";function ub(){this.rw=[]}ub.prototype.toString=function(){return this.rw.join("")};ub.prototype.add=function(a){""!==a&&this.rw.push(a)};ub.className="StringBuilder";function xb(){}xb.className="PropertyCollection";
var E={Gi:!1,$u:!1,Oy:!1,nA:!1,rA:!1,tx:!1,animationExperiments:!1,mA:null,trace:function(a){ra.console&&ra.console.log(a)},uy:function(a){var b={},c;for(c in a){b.x=c;if("licenseKey"!==b.x){var d=a[b.x];if(void 0!==d.prototype){b.rm=Object.getOwnPropertyNames(d.prototype);for(var e={hk:0};e.hk<b.rm.length;e={hk:e.hk},e.hk++){var f=Object.getOwnPropertyDescriptor(d.prototype,b.rm[e.hk]);void 0!==f.get&&void 0===f.set&&Object.defineProperty(d.prototype,b.rm[e.hk],{set:function(a,b){return function(){throw Error("Property "+
a.rm[b.hk]+" of "+a.x+" is read-only.");}}(b,e)})}}}b={rm:b.rm,x:b.x}}}};function Cb(){}Cb.prototype.reset=function(){};Cb.prototype.next=function(){return!1};Cb.prototype.fd=function(){return!1};Cb.prototype.first=function(){return null};Cb.prototype.any=function(){return!1};Cb.prototype.all=function(){return!0};Cb.prototype.each=function(){return this};Cb.prototype.map=function(){return this};Cb.prototype.filter=function(){return this};Cb.prototype.zd=function(){};Cb.prototype.toString=function(){return"EmptyIterator"};
na.Object.defineProperties(Cb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return 0}}});Cb.prototype.first=Cb.prototype.first;Cb.prototype.hasNext=Cb.prototype.fd;Cb.prototype.next=Cb.prototype.next;Cb.prototype.reset=Cb.prototype.reset;var Db=null;Cb.className="EmptyIterator";Db=new Cb;function Eb(a){this.key=-1;this.value=a}Eb.prototype.reset=function(){this.key=-1};
Eb.prototype.next=function(){return-1===this.key?(this.key=0,!0):!1};Eb.prototype.fd=function(){return this.next()};Eb.prototype.first=function(){this.key=0;return this.value};Eb.prototype.any=function(a){this.key=-1;return a(this.value)};Eb.prototype.all=function(a){this.key=-1;return a(this.value)};Eb.prototype.each=function(a){this.key=-1;a(this.value);return this};Eb.prototype.map=function(a){return new Eb(a(this.value))};
Eb.prototype.filter=function(a){return a(this.value)?new Eb(this.value):Db};Eb.prototype.zd=function(){this.value=null};Eb.prototype.toString=function(){return"SingletonIterator("+this.value+")"};na.Object.defineProperties(Eb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return 1}}});Eb.prototype.first=Eb.prototype.first;Eb.prototype.hasNext=Eb.prototype.fd;Eb.prototype.next=Eb.prototype.next;
Eb.prototype.reset=Eb.prototype.reset;Eb.className="SingletonIterator";function Gb(a){this.qb=a;this.Ze=null;a.Ka=null;this.na=a.s;this.Ua=-1}Gb.prototype.reset=function(){var a=this.qb;a.Ka=null;this.na=a.s;this.Ua=-1};Gb.prototype.next=function(){var a=this.qb;if(a.s!==this.na){if(0>this.key)return!1;Ea(a)}a=a.j;var b=a.length,c=++this.Ua,d=this.Ze;if(null!==d)for(;c<b;){var e=a[c];if(d(e))return this.key=this.Ua=c,this.value=e,!0;c++}else{if(c<b)return this.key=c,this.value=a[c],!0;this.zd()}return!1};
Gb.prototype.fd=function(){return this.next()};Gb.prototype.first=function(){var a=this.qb;this.na=a.s;this.Ua=0;a=a.j;var b=a.length,c=this.Ze;if(null!==c){for(var d=0;d<b;){var e=a[d];if(c(e))return this.key=this.Ua=d,this.value=e;d++}return null}return 0<b?(a=a[0],this.key=0,this.value=a):null};Gb.prototype.any=function(a){var b=this.qb;b.Ka=null;var c=b.s;this.Ua=-1;for(var d=b.j,e=d.length,f=this.Ze,g=0;g<e;g++){var h=d[g];if(null===f||f(h)){if(a(h))return!0;b.s!==c&&Ea(b)}}return!1};
Gb.prototype.all=function(a){var b=this.qb;b.Ka=null;var c=b.s;this.Ua=-1;for(var d=b.j,e=d.length,f=this.Ze,g=0;g<e;g++){var h=d[g];if(null===f||f(h)){if(!a(h))return!1;b.s!==c&&Ea(b)}}return!0};Gb.prototype.each=function(a){var b=this.qb;b.Ka=null;var c=b.s;this.Ua=-1;for(var d=b.j,e=d.length,f=this.Ze,g=0;g<e;g++){var h=d[g];if(null===f||f(h))a(h),b.s!==c&&Ea(b)}return this};
Gb.prototype.map=function(a){var b=this.qb;b.Ka=null;var c=b.s;this.Ua=-1;for(var d=[],e=b.j,f=e.length,g=this.Ze,h=0;h<f;h++){var k=e[h];if(null===g||g(k))d.push(a(k)),b.s!==c&&Ea(b)}a=new F;a.j=d;a.lb();return a.iterator};Gb.prototype.filter=function(a){var b=this.qb;b.Ka=null;var c=b.s;this.Ua=-1;for(var d=[],e=b.j,f=e.length,g=this.Ze,h=0;h<f;h++){var k=e[h];if(null===g||g(k))a(k)&&d.push(k),b.s!==c&&Ea(b)}a=new F;a.j=d;a.lb();return a.iterator};
Gb.prototype.zd=function(){this.key=-1;this.value=null;this.na=-1;this.Ze=null;this.qb.Ka=this};Gb.prototype.toString=function(){return"ListIterator@"+this.Ua+"/"+this.qb.count};
na.Object.defineProperties(Gb.prototype,{iterator:{configurable:!0,get:function(){return this}},predicate:{configurable:!0,get:function(){return this.Ze},set:function(a){this.Ze=a}},count:{configurable:!0,get:function(){var a=this.Ze;if(null!==a){for(var b=0,c=this.qb.j,d=c.length,e=0;e<d;e++)a(c[e])&&b++;return b}return this.qb.j.length}}});Gb.prototype.first=Gb.prototype.first;Gb.prototype.hasNext=Gb.prototype.fd;Gb.prototype.next=Gb.prototype.next;
Gb.prototype.reset=Gb.prototype.reset;Gb.className="ListIterator";function Hb(a){this.qb=a;a.Ug=null;this.na=a.s;this.Ua=a.j.length}Hb.prototype.reset=function(){var a=this.qb;a.Ug=null;this.na=a.s;this.Ua=a.j.length};Hb.prototype.next=function(){var a=this.qb;if(a.s!==this.na){if(0>this.key)return!1;Ea(a)}var b=--this.Ua;if(0<=b)return this.key=b,this.value=a.j[b],!0;this.zd();return!1};Hb.prototype.fd=function(){return this.next()};
Hb.prototype.first=function(){var a=this.qb;this.na=a.s;var b=a.j;this.Ua=a=b.length-1;return 0<=a?(b=b[a],this.key=a,this.value=b):null};Hb.prototype.any=function(a){var b=this.qb;b.Ug=null;var c=b.s,d=b.j,e=d.length;this.Ua=e;for(--e;0<=e;e--){if(a(d[e]))return!0;b.s!==c&&Ea(b)}return!1};Hb.prototype.all=function(a){var b=this.qb;b.Ug=null;var c=b.s,d=b.j,e=d.length;this.Ua=e;for(--e;0<=e;e--){if(!a(d[e]))return!1;b.s!==c&&Ea(b)}return!0};
Hb.prototype.each=function(a){var b=this.qb;b.Ug=null;var c=b.s,d=b.j,e=d.length;this.Ua=e;for(--e;0<=e;e--)a(d[e]),b.s!==c&&Ea(b);return this};Hb.prototype.map=function(a){var b=this.qb;b.Ug=null;var c=b.s,d=[],e=b.j,f=e.length;this.Ua=f;for(--f;0<=f;f--)d.push(a(e[f])),b.s!==c&&Ea(b);a=new F;a.j=d;a.lb();return a.iterator};
Hb.prototype.filter=function(a){var b=this.qb;b.Ug=null;var c=b.s,d=[],e=b.j,f=e.length;this.Ua=f;for(--f;0<=f;f--){var g=e[f];a(g)&&d.push(g);b.s!==c&&Ea(b)}a=new F;a.j=d;a.lb();return a.iterator};Hb.prototype.zd=function(){this.key=-1;this.value=null;this.na=-1;this.qb.Ug=this};Hb.prototype.toString=function(){return"ListIteratorBackwards("+this.Ua+"/"+this.qb.count+")"};
na.Object.defineProperties(Hb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.qb.j.length}}});Hb.prototype.first=Hb.prototype.first;Hb.prototype.hasNext=Hb.prototype.fd;Hb.prototype.next=Hb.prototype.next;Hb.prototype.reset=Hb.prototype.reset;Hb.className="ListIteratorBackwards";
function F(a){qb(this);this.u=!1;this.j=[];this.s=0;this.Ug=this.Ka=null;void 0!==a&&("function"===typeof a||"string"===typeof a?Ia():this.addAll(a))}t=F.prototype;t.lb=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()#"+Jb(this)};t.add=function(a){if(null===a)return this;this.u&&za(this,a);this.j.push(a);this.lb();return this};t.push=function(a){this.add(a)};
t.addAll=function(a){if(null===a)return this;this.u&&za(this);var b=this.j;if(Ka(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.lb();return this};t.clear=function(){this.u&&za(this);this.j.length=0;this.lb()};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&&B(a,F,"elt:i");var b=this.j;(0>a||a>=b.length)&&Ca(a,"0 <= i < length",F,"elt:i");return b[a]};t.get=function(a){return this.O(a)};t.jd=function(a,b){E&&B(a,F,"setElt:i");var c=this.j;(0>a||a>=c.length)&&Ca(a,"0 <= i < length",F,"setElt:i");this.u&&za(this,a);c[a]=b};t.set=function(a,b){this.jd(a,b)};t.first=function(){var a=this.j;return 0===a.length?null:a[0]};t.Ub=function(){var a=this.j,b=a.length;return 0<b?a[b-1]:null};
t.pop=function(){this.u&&za(this);var a=this.j;return 0<a.length?a.pop():null};F.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&&Ea(this)}return!1};F.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&&Ea(this)}return!0};F.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&&Ea(this);return this};
F.prototype.map=function(a){for(var b=new F,c=[],d=this.j,e=this.s,f=d.length,g=0;g<f;g++)c.push(a(d[g])),this.s!==e&&Ea(this);b.j=c;b.lb();return b};F.prototype.filter=function(a){for(var b=new F,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&&Ea(this)}b.j=c;b.lb();return b};t=F.prototype;t.Lb=function(a,b){E&&B(a,F,"insertAt:i");0>a&&Ca(a,">= 0",F,"insertAt:i");this.u&&za(this,a);var c=this.j;a>=c.length?c.push(b):c.splice(a,0,b);this.lb()};
t.remove=function(a){if(null===a)return!1;this.u&&za(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.lb();return!0};t.delete=function(a){return this.remove(a)};t.nb=function(a){E&&B(a,F,"removeAt:i");var b=this.j;(0>a||a>=b.length)&&Ca(a,"0 <= i < length",F,"removeAt:i");this.u&&za(this,a);a===b.length-1?b.pop():b.splice(a,1);this.lb()};
t.removeRange=function(a,b){E&&(B(a,F,"removeRange:from"),B(b,F,"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&&za(this);for(var e=a,f=b+1;f<d;)c[e++]=c[f++];c.length=d-(b-a+1);this.lb();return this};F.prototype.copy=function(){var a=new F,b=this.j;0<b.length&&(a.j=Array.prototype.slice.call(b));return a};t=F.prototype;t.Oa=function(){for(var a=this.j,b=this.count,c=Array(b),d=0;d<b;d++)c[d]=a[d];return c};
t.Xv=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",F,"sort:sortfunc");this.u&&za(this);this.j.sort(a);this.lb();return this};
t.$i=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",F,"sortRange:sortfunc"),B(b,F,"sortRange:from"),B(c,F,"sortRange:to"));this.u&&za(this);var f=c-b;if(1>=f)return this;(0>b||b>=e-1)&&Ca(b,"0 <= from < length",F,"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.lb()),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.lb();return this};t.reverse=function(){this.u&&za(this);this.j.reverse();this.lb();return this};
na.Object.defineProperties(F.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 Db;var a=this.Ka;return null!==a?(a.reset(),a):new Gb(this)}},iteratorBackwards:{configurable:!0,
enumerable:!0,get:function(){if(0>=this.j.length)return Db;var a=this.Ug;return null!==a?(a.reset(),a):new Hb(this)}}});F.prototype.reverse=F.prototype.reverse;F.prototype.sortRange=F.prototype.$i;F.prototype.sort=F.prototype.sort;F.prototype.toSet=F.prototype.Xv;F.prototype.toArray=F.prototype.Oa;F.prototype.removeRange=F.prototype.removeRange;F.prototype.removeAt=F.prototype.nb;F.prototype["delete"]=F.prototype.delete;F.prototype.remove=F.prototype.remove;F.prototype.insertAt=F.prototype.Lb;
F.prototype.pop=F.prototype.pop;F.prototype.last=F.prototype.Ub;F.prototype.first=F.prototype.first;F.prototype.set=F.prototype.set;F.prototype.setElt=F.prototype.jd;F.prototype.get=F.prototype.get;F.prototype.elt=F.prototype.O;F.prototype.indexOf=F.prototype.indexOf;F.prototype.has=F.prototype.has;F.prototype.contains=F.prototype.contains;F.prototype.clear=F.prototype.clear;F.prototype.addAll=F.prototype.addAll;F.prototype.push=F.prototype.push;F.prototype.add=F.prototype.add;F.prototype.thaw=F.prototype.ja;
F.prototype.freeze=F.prototype.freeze;F.className="List";function Kb(a){this.hg=a;a.Ka=null;this.na=a.s;this.pa=null}Kb.prototype.reset=function(){var a=this.hg;a.Ka=null;this.na=a.s;this.pa=null};Kb.prototype.next=function(){var a=this.hg;if(a.s!==this.na){if(null===this.key)return!1;Ea(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.zd();return!1};Kb.prototype.fd=function(){return this.next()};
Kb.prototype.first=function(){var a=this.hg;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};Kb.prototype.any=function(a){var b=this.hg;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&&Ea(b);d=d.qa}return!1};Kb.prototype.all=function(a){var b=this.hg;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&&Ea(b);d=d.qa}return!0};
Kb.prototype.each=function(a){var b=this.hg;b.Ka=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;)a(d.value),b.s!==c&&Ea(b),d=d.qa;return this};Kb.prototype.map=function(a){var b=this.hg;b.Ka=null;for(var c=new F,d=b.s,e=b.ga;null!==e;)c.add(a(e.value)),b.s!==d&&Ea(b),e=e.qa;return c.iterator};Kb.prototype.filter=function(a){var b=this.hg;b.Ka=null;for(var c=new F,d=b.s,e=b.ga;null!==e;){var f=e.value;a(f)&&c.add(f);b.s!==d&&Ea(b);e=e.qa}return c.iterator};
Kb.prototype.zd=function(){this.value=this.key=null;this.na=-1;this.hg.Ka=this};Kb.prototype.toString=function(){return null!==this.pa?"SetIterator@"+this.pa.value:"SetIterator"};na.Object.defineProperties(Kb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.hg.Fb}}});Kb.prototype.first=Kb.prototype.first;Kb.prototype.hasNext=Kb.prototype.fd;Kb.prototype.next=Kb.prototype.next;Kb.prototype.reset=Kb.prototype.reset;
Kb.className="SetIterator";function H(a){qb(this);this.u=!1;this.Gb={};this.Fb=0;this.Ka=null;this.s=0;this.Ve=this.ga=null;void 0!==a&&("function"===typeof a||"string"===typeof a?Ia():this.addAll(a))}t=H.prototype;t.lb=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()#"+Jb(this)};
t.add=function(a){if(null===a)return this;this.u&&za(this,a);var b=a;Ja(a)&&(b=Nb(a));void 0===this.Gb[b]&&(this.Fb++,a=new Ob(a,a),this.Gb[b]=a,b=this.Ve,null===b?this.ga=a:(a.Bl=b,b.qa=a),this.Ve=a,this.lb());return this};t.addAll=function(a){if(null===a)return this;this.u&&za(this);if(Ka(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 Ja(a)&&(b=Jb(a),void 0===b)?!1:void 0!==this.Gb[b]};t.has=function(a){return this.contains(a)};t.Ay=function(a){if(null===a)return!0;for(a=a.iterator;a.next();)if(!this.contains(a.value))return!1;return!0};t.By=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&&Ea(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&&Ea(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&&Ea(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&&Ea(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&&Ea(this);d=d.qa}return b};t=H.prototype;t.remove=function(a){if(null===a)return!1;this.u&&za(this,a);var b=a;if(Ja(a)&&(b=Jb(a),void 0===b))return!1;a=this.Gb[b];if(void 0===a)return!1;var c=a.qa,d=a.Bl;null!==c&&(c.Bl=d);null!==d&&(d.qa=c);this.ga===a&&(this.ga=c);this.Ve===a&&(this.Ve=d);delete this.Gb[b];this.Fb--;this.lb();return!0};t.delete=function(a){return this.remove(a)};
t.vq=function(a){if(null===a)return this;this.u&&za(this);if(Ka(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.Zz=function(a){if(null===a||0===this.count)return this;this.u&&za(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.vq(a);return this};t.clear=function(){this.u&&za(this);this.Gb={};this.Fb=0;null!==this.Ka&&this.Ka.reset();this.Ve=this.ga=null;this.lb()};
H.prototype.copy=function(){var a=new H,b=this.Gb,c;for(c in b)a.add(b[c].value);return a};H.prototype.Oa=function(){var a=Array(this.Fb),b=this.Gb,c=0,d;for(d in b)a[c]=b[d].value,c++;return a};H.prototype.Wv=function(){var a=new F,b=this.Gb,c;for(c in b)a.add(b[c].value);return a};function qb(a){a.__gohashid=Pb++}function Nb(a){var b=a.__gohashid;void 0===b&&(b=Pb++,a.__gohashid=b);return b}function Jb(a){return a.__gohashid}
na.Object.defineProperties(H.prototype,{count:{configurable:!0,get:function(){return this.Fb}},size:{configurable:!0,get:function(){return this.Fb}},iterator:{configurable:!0,get:function(){if(0>=this.Fb)return Db;var a=this.Ka;return null!==a?(a.reset(),a):new Kb(this)}}});H.prototype.toList=H.prototype.Wv;H.prototype.toArray=H.prototype.Oa;H.prototype.clear=H.prototype.clear;H.prototype.retainAll=H.prototype.Zz;H.prototype.removeAll=H.prototype.vq;
H.prototype["delete"]=H.prototype.delete;H.prototype.remove=H.prototype.remove;H.prototype.first=H.prototype.first;H.prototype.containsAny=H.prototype.By;H.prototype.containsAll=H.prototype.Ay;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 Pb=1;H.className="Set";H.uniqueHash=qb;H.hashIdUnique=Nb;H.hashId=Jb;
function Qb(a){this.la=a;this.na=a.s;this.pa=null}Qb.prototype.reset=function(){this.na=this.la.s;this.pa=null};Qb.prototype.next=function(){var a=this.la;if(a.s!==this.na){if(null===this.key)return!1;Ea(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.zd();return!1};Qb.prototype.fd=function(){return this.next()};Qb.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};
Qb.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&&Ea(b);d=d.qa}return!1};Qb.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&&Ea(b);d=d.qa}return!0};Qb.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&&Ea(b),d=d.qa;return this};
Qb.prototype.map=function(a){var b=this.la,c=b.s;this.pa=null;for(var d=new F,e=b.ga;null!==e;)d.add(a(e.key)),b.s!==c&&Ea(b),e=e.qa;return d.iterator};Qb.prototype.filter=function(a){var b=this.la,c=b.s;this.pa=null;for(var d=new F,e=b.ga;null!==e;){var f=e.key;a(f)&&d.add(f);b.s!==c&&Ea(b);e=e.qa}return d.iterator};Qb.prototype.zd=function(){this.value=this.key=null;this.na=-1};Qb.prototype.toString=function(){return null!==this.pa?"MapKeySetIterator@"+this.pa.value:"MapKeySetIterator"};
na.Object.defineProperties(Qb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.la.Fb}}});Qb.prototype.first=Qb.prototype.first;Qb.prototype.hasNext=Qb.prototype.fd;Qb.prototype.next=Qb.prototype.next;Qb.prototype.reset=Qb.prototype.reset;Qb.className="MapKeySetIterator";function Rb(a){H.call(this);qb(this);this.u=!0;this.la=a}ma(Rb,H);t=Rb.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};
Rb.prototype.any=function(a){for(var b=this.la.ga;null!==b;){if(a(b.key))return!0;b=b.qa}return!1};Rb.prototype.all=function(a){for(var b=this.la.ga;null!==b;){if(!a(b.key))return!1;b=b.qa}return!0};Rb.prototype.each=function(a){for(var b=this.la.ga;null!==b;)a(b.key),b=b.qa;return this};Rb.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};Rb.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};
Rb.prototype.copy=function(){return new Rb(this.la)};Rb.prototype.Xv=function(){var a=new H,b=this.la.Gb,c;for(c in b)a.add(b[c].key);return a};Rb.prototype.Oa=function(){var a=this.la.Gb,b=Array(this.la.Fb),c=0,d;for(d in a)b[c]=a[d].key,c++;return b};Rb.prototype.Wv=function(){var a=new F,b=this.la.Gb,c;for(c in b)a.add(b[c].key);return a};
na.Object.defineProperties(Rb.prototype,{count:{configurable:!0,get:function(){return this.la.Fb}},size:{configurable:!0,get:function(){return this.la.Fb}},iterator:{configurable:!0,get:function(){return 0>=this.la.Fb?Db:new Qb(this.la)}}});Rb.prototype.toList=Rb.prototype.Wv;Rb.prototype.toArray=Rb.prototype.Oa;Rb.prototype.toSet=Rb.prototype.Xv;Rb.prototype.first=Rb.prototype.first;Rb.prototype.clear=Rb.prototype.clear;Rb.prototype["delete"]=Rb.prototype.delete;
Rb.prototype.remove=Rb.prototype.remove;Rb.prototype.has=Rb.prototype.has;Rb.prototype.contains=Rb.prototype.contains;Rb.prototype.add=Rb.prototype.add;Rb.prototype.thaw=Rb.prototype.ja;Rb.prototype.freeze=Rb.prototype.freeze;Rb.className="MapKeySet";function Sb(a){this.la=a;a.Ue=null;this.na=a.s;this.pa=null}Sb.prototype.reset=function(){var a=this.la;a.Ue=null;this.na=a.s;this.pa=null};
Sb.prototype.next=function(){var a=this.la;if(a.s!==this.na){if(null===this.key)return!1;Ea(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.zd();return!1};Sb.prototype.fd=function(){return this.next()};Sb.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};
Sb.prototype.any=function(a){var b=this.la;b.Ue=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(a(d.value))return!0;b.s!==c&&Ea(b);d=d.qa}return!1};Sb.prototype.all=function(a){var b=this.la;b.Ue=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(!a(d.value))return!1;b.s!==c&&Ea(b);d=d.qa}return!0};Sb.prototype.each=function(a){var b=this.la;b.Ue=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;)a(d.value),b.s!==c&&Ea(b),d=d.qa;return this};
Sb.prototype.map=function(a){var b=this.la;b.Ue=null;var c=b.s;this.pa=null;for(var d=new F,e=b.ga;null!==e;)d.add(a(e.value)),b.s!==c&&Ea(b),e=e.qa;return d.iterator};Sb.prototype.filter=function(a){var b=this.la;b.Ue=null;var c=b.s;this.pa=null;for(var d=new F,e=b.ga;null!==e;){var f=e.value;a(f)&&d.add(f);b.s!==c&&Ea(b);e=e.qa}return d.iterator};Sb.prototype.zd=function(){this.value=this.key=null;this.na=-1;this.la.Ue=this};
Sb.prototype.toString=function(){return null!==this.pa?"MapValueSetIterator@"+this.pa.value:"MapValueSetIterator"};na.Object.defineProperties(Sb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.la.Fb}}});Sb.prototype.first=Sb.prototype.first;Sb.prototype.hasNext=Sb.prototype.fd;Sb.prototype.next=Sb.prototype.next;Sb.prototype.reset=Sb.prototype.reset;Sb.className="MapValueSetIterator";
function Ob(a,b){this.key=a;this.value=b;this.Bl=this.qa=null}Ob.prototype.toString=function(){return"{"+this.key+":"+this.value+"}"};Ob.className="KeyValuePair";function Tb(a){this.la=a;a.Ka=null;this.na=a.s;this.pa=null}Tb.prototype.reset=function(){var a=this.la;a.Ka=null;this.na=a.s;this.pa=null};
Tb.prototype.next=function(){var a=this.la;if(a.s!==this.na){if(null===this.key)return!1;Ea(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.zd();return!1};Tb.prototype.fd=function(){return this.next()};Tb.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};
Tb.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&&Ea(b);d=d.qa}return!1};Tb.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&&Ea(b);d=d.qa}return!0};Tb.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&&Ea(b),d=d.qa;return this};
Tb.prototype.map=function(a){var b=this.la;b.Ka=null;var c=b.s;this.pa=null;for(var d=new F,e=b.ga;null!==e;)d.add(a(e)),b.s!==c&&Ea(b),e=e.qa;return d.iterator};Tb.prototype.filter=function(a){var b=this.la;b.Ka=null;var c=b.s;this.pa=null;for(var d=new F,e=b.ga;null!==e;)a(e)&&d.add(e),b.s!==c&&Ea(b),e=e.qa;return d.iterator};Tb.prototype.zd=function(){this.value=this.key=null;this.na=-1;this.la.Ka=this};Tb.prototype.toString=function(){return null!==this.pa?"MapIterator@"+this.pa:"MapIterator"};
na.Object.defineProperties(Tb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.la.Fb}}});Tb.prototype.first=Tb.prototype.first;Tb.prototype.hasNext=Tb.prototype.fd;Tb.prototype.next=Tb.prototype.next;Tb.prototype.reset=Tb.prototype.reset;Tb.className="MapIterator";
function Ub(a){qb(this);this.u=!1;this.Gb={};this.Fb=0;this.Ue=this.Ka=null;this.s=0;this.Ve=this.ga=null;void 0!==a&&("function"===typeof a||"string"===typeof a?Ia():this.addAll(a))}t=Ub.prototype;t.lb=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()#"+Jb(this)};
t.add=function(a,b){this.u&&za(this,a);var c=a;Ja(a)&&(c=Nb(a));var d=this.Gb[c];void 0===d?(this.Fb++,a=new Ob(a,b),this.Gb[c]=a,c=this.Ve,null===c?this.ga=a:(a.Bl=c,c.qa=a),this.Ve=a,this.lb()):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(Ka(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};
Ub.prototype.any=function(a){for(var b=this.s,c=this.ga;null!==c;){if(a(c))return!0;this.s!==b&&Ea(this);c=c.qa}return!1};Ub.prototype.all=function(a){for(var b=this.s,c=this.ga;null!==c;){if(!a(c))return!1;this.s!==b&&Ea(this);c=c.qa}return!0};Ub.prototype.each=function(a){for(var b=this.s,c=this.ga;null!==c;)a(c),this.s!==b&&Ea(this),c=c.qa;return this};Ub.prototype.map=function(a){for(var b=new Ub,c=this.s,d=this.ga;null!==d;)b.add(d.key,a(d)),this.s!==c&&Ea(this),d=d.qa;return b};
Ub.prototype.filter=function(a){for(var b=new Ub,c=this.s,d=this.ga;null!==d;)a(d)&&b.add(d.key,d.value),this.s!==c&&Ea(this),d=d.qa;return b};t=Ub.prototype;t.contains=function(a){var b=a;return Ja(a)&&(b=Jb(a),void 0===b)?!1:void 0!==this.Gb[b]};t.has=function(a){return this.contains(a)};t.K=function(a){var b=a;if(Ja(a)&&(b=Jb(a),void 0===b))return null;a=this.Gb[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&&za(this,a);var b=a;if(Ja(a)&&(b=Jb(a),void 0===b))return!1;a=this.Gb[b];if(void 0===a)return!1;var c=a.qa,d=a.Bl;null!==c&&(c.Bl=d);null!==d&&(d.qa=c);this.ga===a&&(this.ga=c);this.Ve===a&&(this.Ve=d);delete this.Gb[b];this.Fb--;this.lb();return!0};t.delete=function(a){return this.remove(a)};t.clear=function(){this.u&&za(this);this.Gb={};this.Fb=0;null!==this.Ka&&this.Ka.reset();null!==this.Ue&&this.Ue.reset();this.Ve=this.ga=null;this.lb()};
Ub.prototype.copy=function(){var a=new Ub,b=this.Gb,c;for(c in b){var d=b[c];a.add(d.key,d.value)}return a};Ub.prototype.Oa=function(){var a=this.Gb,b=Array(this.Fb),c=0,d;for(d in a){var e=a[d];b[c]=new Ob(e.key,e.value);c++}return b};Ub.prototype.$d=function(){return new Rb(this)};
na.Object.defineProperties(Ub.prototype,{count:{configurable:!0,get:function(){return this.Fb}},size:{configurable:!0,get:function(){return this.Fb}},iterator:{configurable:!0,get:function(){if(0>=this.count)return Db;var a=this.Ka;return null!==a?(a.reset(),a):new Tb(this)}},iteratorKeys:{configurable:!0,get:function(){return 0>=this.count?Db:new Qb(this)}},iteratorValues:{configurable:!0,get:function(){if(0>=this.count)return Db;
var a=this.Ue;return null!==a?(a.reset(),a):new Sb(this)}}});Ub.prototype.toKeySet=Ub.prototype.$d;Ub.prototype.toArray=Ub.prototype.Oa;Ub.prototype.clear=Ub.prototype.clear;Ub.prototype["delete"]=Ub.prototype.delete;Ub.prototype.remove=Ub.prototype.remove;Ub.prototype.get=Ub.prototype.get;Ub.prototype.getValue=Ub.prototype.K;Ub.prototype.has=Ub.prototype.has;Ub.prototype.contains=Ub.prototype.contains;Ub.prototype.first=Ub.prototype.first;Ub.prototype.addAll=Ub.prototype.addAll;
Ub.prototype.set=Ub.prototype.set;Ub.prototype.add=Ub.prototype.add;Ub.prototype.thaw=Ub.prototype.ja;Ub.prototype.freeze=Ub.prototype.freeze;Ub.className="Map";function J(a,b){void 0===a?this.H=this.G=0:"number"===typeof a&&"number"===typeof b?(this.G=a,this.H=b):v("Invalid arguments to Point constructor: "+a+", "+b);this.u=!1}J.prototype.assign=function(a){this.G=a.G;this.H=a.H;return this};J.prototype.h=function(a,b){this.G=a;this.H=b;return this};
J.prototype.wg=function(a,b){E&&(z(a,"number",J,"setTo:x"),z(b,"number",J,"setTo:y"),this.ha());this.G=a;this.H=b;return this};J.prototype.set=function(a){E&&(w(a,J,J,"set:p"),this.ha());this.G=a.G;this.H=a.H;return this};J.prototype.copy=function(){var a=new J;a.G=this.G;a.H=this.H;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 Vb(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 Xb(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.G===a.x&&this.H===a.y:!1};t.Ii=function(a,b){return this.G===a&&this.H===b};t.Sa=function(a){return K.B(this.G,a.x)&&K.B(this.H,a.y)};t.add=function(a){E&&(w(a,J,J,"add:p"),this.ha());this.G+=a.x;this.H+=a.y;return this};t.Zd=function(a){E&&(w(a,J,J,"subtract:p"),this.ha());this.G-=a.x;this.H-=a.y;return this};
t.offset=function(a,b){E&&(B(a,J,"offset:dx"),B(b,J,"offset:dy"),this.ha());this.G+=a;this.H+=b;return this};J.prototype.rotate=function(a){E&&(B(a,J,"rotate:angle"),this.ha());if(0===a)return this;var b=this.G,c=this.H;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.G=a*b-d*c;this.H=d*b+a*c;return this};t=J.prototype;
t.scale=function(a,b){E&&(B(a,J,"scale:sx"),B(b,J,"scale:sy"),this.ha());this.G*=a;this.H*=b;return this};t.Ee=function(a){E&&w(a,J,J,"distanceSquaredPoint:p");var b=a.x-this.G;a=a.y-this.H;return b*b+a*a};t.ed=function(a,b){E&&(B(a,J,"distanceSquared:px"),B(b,J,"distanceSquared:py"));a-=this.G;b-=this.H;return a*a+b*b};t.normalize=function(){E&&this.ha();var a=this.G,b=this.H,c=Math.sqrt(a*a+b*b);0<c&&(this.G=a/c,this.H=b/c);return this};
t.Xa=function(a){E&&w(a,J,J,"directionPoint:p");return Yb(a.x-this.G,a.y-this.H)};t.direction=function(a,b){E&&(B(a,J,"direction:px"),B(b,J,"direction:py"));return Yb(a-this.G,b-this.H)};function Yb(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.Sz=function(a,b,c,d){E&&(B(a,J,"projectOntoLineSegment:px"),B(b,J,"projectOntoLineSegment:py"),B(c,J,"projectOntoLineSegment:qx"),B(d,J,"projectOntoLineSegment:qy"));K.Wi(a,b,c,d,this.G,this.H,this);return this};t.Tz=function(a,b){E&&(w(a,J,J,"projectOntoLineSegmentPoint:p"),w(b,J,J,"projectOntoLineSegmentPoint:q"));K.Wi(a.x,a.y,b.x,b.y,this.G,this.H,this);return this};
t.dA=function(a,b,c,d){E&&(B(a,J,"snapToGrid:originx"),B(b,J,"snapToGrid:originy"),B(c,J,"snapToGrid:cellwidth"),B(d,J,"snapToGrid:cellheight"));K.bq(this.G,this.H,a,b,c,d,this);return this};t.eA=function(a,b){E&&(w(a,J,J,"snapToGridPoint:p"),w(b,Zb,J,"snapToGridPoint:q"));K.bq(this.G,this.H,a.x,a.y,b.width,b.height,this);return this};t.Yi=function(a,b){E&&(w(a,L,J,"setRectSpot:r"),w(b,M,J,"setRectSpot:spot"),this.ha());this.G=a.x+b.x*a.width+b.offsetX;this.H=a.y+b.y*a.height+b.offsetY;return this};
t.vk=function(a,b,c,d,e){E&&(B(a,J,"setSpot:x"),B(b,J,"setSpot:y"),B(c,J,"setSpot:w"),B(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.G=a+e.x*c+e.offsetX;this.H=b+e.y*d+e.offsetY;return this};t.transform=function(a){E&&w(a,$b,J,"transform:t");a.va(this);return this};function ac(a,b){E&&w(b,$b,J,"transformInverted:t");b.Wd(a);return a}
function cc(a,b,c,d,e,f){E&&(B(a,J,"distanceLineSegmentSquared:px"),B(b,J,"distanceLineSegmentSquared:py"),B(c,J,"distanceLineSegmentSquared:ax"),B(d,J,"distanceLineSegmentSquared:ay"),B(e,J,"distanceLineSegmentSquared:bx"),B(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 dc(a,b,c,d){E&&(B(a,J,"distanceSquared:px"),B(b,J,"distanceSquared:py"),B(c,J,"distanceSquared:qx"),B(d,J,"distanceSquared:qy"));a=c-a;b=d-b;return a*a+b*b}function ec(a,b,c,d){E&&(B(a,J,"direction:px"),B(b,J,"direction:py"),B(c,J,"direction:qx"),B(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=fc.pop();return void 0===a?new J:a};J.allocAt=function(a,b){var c=fc.pop();if(void 0===c)return new J(a,b);c.x=a;c.y=b;return c};J.free=function(a){fc.push(a)};
na.Object.defineProperties(J.prototype,{x:{configurable:!0,get:function(){return this.G},set:function(a){E&&(z(a,"number",J,"x"),this.ha(a));this.G=a}},y:{configurable:!0,get:function(){return this.H},set:function(a){E&&(z(a,"number",J,"y"),this.ha(a));this.H=a}}});J.prototype.isReal=J.prototype.o;J.prototype.setSpot=J.prototype.vk;J.prototype.setRectSpot=J.prototype.Yi;J.prototype.snapToGridPoint=J.prototype.eA;J.prototype.snapToGrid=J.prototype.dA;
J.prototype.projectOntoLineSegmentPoint=J.prototype.Tz;J.prototype.projectOntoLineSegment=J.prototype.Sz;J.prototype.direction=J.prototype.direction;J.prototype.directionPoint=J.prototype.Xa;J.prototype.normalize=J.prototype.normalize;J.prototype.distanceSquared=J.prototype.ed;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.Zd;J.prototype.add=J.prototype.add;
J.prototype.equalsApprox=J.prototype.Sa;J.prototype.equalTo=J.prototype.Ii;J.prototype.equals=J.prototype.A;J.prototype.set=J.prototype.set;J.prototype.setTo=J.prototype.wg;var gc=null,hc=null,ic=null,jc=null,qc=null,fc=[];J.className="Point";J.parse=Vb;J.stringify=Xb;J.distanceLineSegmentSquared=cc;J.distanceSquared=dc;J.direction=ec;J.Origin=gc=(new J(0,0)).ia();J.InfiniteTopLeft=hc=(new J(-Infinity,-Infinity)).ia();J.InfiniteBottomRight=ic=(new J(Infinity,Infinity)).ia();
J.SixPoint=jc=(new J(6,6)).ia();J.NoPoint=qc=(new J(NaN,NaN)).ia();J.parse=Vb;J.stringify=Xb;J.distanceLineSegmentSquared=cc;J.distanceSquared=dc;J.direction=ec;function Zb(a,b){void 0===a?this.$=this.aa=0:"number"===typeof a&&(0<=a||isNaN(a))&&"number"===typeof b&&(0<=b||isNaN(b))?(this.aa=a,this.$=b):v("Invalid arguments to Size constructor: "+a+", "+b);this.u=!1}var rc,sc,tc,uc,vc,wc,xc;Zb.prototype.assign=function(a){this.aa=a.aa;this.$=a.$;return this};
Zb.prototype.h=function(a,b){this.aa=a;this.$=b;return this};Zb.prototype.wg=function(a,b){E&&(z(a,"number",Zb,"setTo:w"),z(b,"number",Zb,"setTo:h"),0>a&&Ca(a,">= 0",Zb,"setTo:w"),0>b&&Ca(b,">= 0",Zb,"setTo:h"),this.ha());this.aa=a;this.$=b;return this};Zb.prototype.set=function(a){E&&(w(a,Zb,Zb,"set:s"),this.ha());this.aa=a.aa;this.$=a.$;return this};Zb.prototype.copy=function(){var a=new Zb;a.aa=this.aa;a.$=this.$;return a};t=Zb.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 yc(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 Zb(c,e)}return new Zb}function Ac(a){E&&w(a,Zb);return a.width.toString()+" "+a.height.toString()}t.toString=function(){return"Size("+this.width+","+this.height+")"};t.A=function(a){return a instanceof Zb?this.aa===a.width&&this.$===a.height:!1};t.Ii=function(a,b){return this.aa===a&&this.$===b};
t.Sa=function(a){return K.B(this.aa,a.width)&&K.B(this.$,a.height)};t.o=function(){return isFinite(this.width)&&isFinite(this.height)};Zb.alloc=function(){var a=Bc.pop();return void 0===a?new Zb:a};Zb.free=function(a){Bc.push(a)};
na.Object.defineProperties(Zb.prototype,{width:{configurable:!0,get:function(){return this.aa},set:function(a){E&&(z(a,"number",Zb,"width"),this.ha(a));0>a&&Ca(a,">= 0",Zb,"width");this.aa=a}},height:{configurable:!0,get:function(){return this.$},set:function(a){E&&(z(a,"number",Zb,"height"),this.ha(a));0>a&&Ca(a,">= 0",Zb,"height");this.$=a}}});Zb.prototype.isReal=Zb.prototype.o;Zb.prototype.equalsApprox=Zb.prototype.Sa;Zb.prototype.equalTo=Zb.prototype.Ii;
Zb.prototype.equals=Zb.prototype.A;Zb.prototype.set=Zb.prototype.set;Zb.prototype.setTo=Zb.prototype.wg;var Bc=[];Zb.className="Size";Zb.parse=yc;Zb.stringify=Ac;Zb.ZeroSize=rc=(new Zb(0,0)).ia();Zb.OneSize=sc=(new Zb(1,1)).ia();Zb.SixSize=tc=(new Zb(6,6)).ia();Zb.EightSize=uc=(new Zb(8,8)).ia();Zb.TenSize=vc=(new Zb(10,10)).ia();Zb.InfiniteSize=wc=(new Zb(Infinity,Infinity)).ia();Zb.NoSize=xc=(new Zb(NaN,NaN)).ia();Zb.parse=yc;Zb.stringify=Ac;
function L(a,b,c,d){void 0===a?this.$=this.aa=this.H=this.G=0:a instanceof J?(c=a.x,a=a.y,b instanceof J?(d=b.x,b=b.y,this.G=Math.min(c,d),this.H=Math.min(a,b),this.aa=Math.abs(c-d),this.$=Math.abs(a-b)):b instanceof Zb?(this.G=c,this.H=a,this.aa=b.aa,this.$=b.$):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.G=a,this.H=b,this.aa=c,this.$=d):v("Invalid arguments to Rect constructor: "+
a+", "+b+", "+c+", "+d);this.u=!1}t=L.prototype;t.assign=function(a){this.G=a.G;this.H=a.H;this.aa=a.aa;this.$=a.$;return this};t.h=function(a,b,c,d){this.G=a;this.H=b;this.aa=c;this.$=d;return this};function Cc(a,b,c){a.aa=b;a.$=c}t.wg=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&&Ca(c,">= 0",L,"setTo:w"),0>d&&Ca(d,">= 0",L,"setTo:h"),this.ha());this.G=a;this.H=b;this.aa=c;this.$=d;return this};
t.set=function(a){E&&(w(a,L,L,"set:r"),this.ha());this.G=a.G;this.H=a.H;this.aa=a.aa;this.$=a.$;return this};t.ld=function(a){E&&(w(a,J,L,"setPoint:p"),this.ha());this.G=a.x;this.H=a.y;return this};t.bA=function(a){E&&(w(a,Zb,L,"setSize:s"),this.ha());this.aa=a.aa;this.$=a.$;return this};L.prototype.copy=function(){var a=new L;a.G=this.G;a.H=this.H;a.aa=this.aa;a.$=this.$;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 Dc(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 Ec(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.G===a.x&&this.H===a.y&&this.aa===a.width&&this.$===a.height:!1};t.Ii=function(a,b,c,d){return this.G===a&&this.H===b&&this.aa===c&&this.$===d};t.Sa=function(a){return K.B(this.G,a.x)&&K.B(this.H,a.y)&&K.B(this.aa,a.width)&&K.B(this.$,a.height)};function Fc(a,b){return K.da(a.G,b.x)&&K.da(a.H,b.y)&&K.da(a.aa,b.width)&&K.da(a.$,b.height)}
t.ea=function(a){E&&w(a,J,L,"containsPoint:p");return this.G<=a.x&&this.G+this.aa>=a.x&&this.H<=a.y&&this.H+this.$>=a.y};t.pf=function(a){E&&w(a,L,L,"containsRect:r");return this.G<=a.x&&a.x+a.width<=this.G+this.aa&&this.H<=a.y&&a.y+a.height<=this.H+this.$};
t.contains=function(a,b,c,d){E?(B(a,L,"contains:x"),B(b,L,"contains:y"),void 0===c?c=0:B(c,L,"contains:w"),void 0===d?d=0:B(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.G<=a&&a+c<=this.G+this.aa&&this.H<=b&&b+d<=this.H+this.$};t.reset=function(){E&&this.ha();this.$=this.aa=this.H=this.G=0};t.offset=function(a,b){E&&(B(a,L,"offset:dx"),B(b,L,"offset:dy"),this.ha());this.G+=a;this.H+=b;return this};
t.Xc=function(a,b){E&&(B(a,L,"inflate:w"),B(b,L,"inflate:h"));return Gc(this,b,a,b,a)};t.Sp=function(a){E&&w(a,Hc,L,"addMargin:m");return Gc(this,a.top,a.right,a.bottom,a.left)};t.Vv=function(a){E&&w(a,Hc,L,"subtractMargin:m");return Gc(this,-a.top,-a.right,-a.bottom,-a.left)};t.vz=function(a,b,c,d){E&&(B(a,L,"grow:t"),B(b,L,"grow:r"),B(c,L,"grow:b"),B(d,L,"grow:l"));return Gc(this,a,b,c,d)};
function Gc(a,b,c,d,e){E&&a.ha();var f=a.aa;c+e<=-f?(a.G+=f/2,a.aa=0):(a.G-=e,a.aa+=c+e);c=a.$;b+d<=-c?(a.H+=c/2,a.$=0):(a.H-=b,a.$+=b+d);return a}t.zz=function(a){E&&w(a,L,L,"intersectRect:r");return Kc(this,a.x,a.y,a.width,a.height)};t.ov=function(a,b,c,d){E&&(B(a,L,"intersect:x"),B(b,L,"intersect:y"),B(c,L,"intersect:w"),B(d,L,"intersect:h"),(0>c||0>d)&&v("Rect.intersect:Width and height cannot be negative"));return Kc(this,a,b,c,d)};
function Kc(a,b,c,d,e){E&&a.ha();var f=Math.max(a.G,b),g=Math.max(a.H,c);b=Math.min(a.G+a.aa,b+d);c=Math.min(a.H+a.$,c+e);a.G=f;a.H=g;a.aa=Math.max(0,b-f);a.$=Math.max(0,c-g);return a}t.Kc=function(a){E&&w(a,L,L,"intersectsRect:r");return this.pv(a.x,a.y,a.width,a.height)};
t.pv=function(a,b,c,d){E&&(B(a,L,"intersects:x"),B(b,L,"intersects:y"),B(a,L,"intersects:w"),B(b,L,"intersects:h"),(0>c||0>d)&&v("Rect.intersects:Width and height cannot be negative"));var e=this.aa,f=this.G;if(Infinity!==e&&Infinity!==c&&(e+=f,c+=a,isNaN(c)||isNaN(e)||f>c||a>e))return!1;a=this.$;c=this.H;return Infinity!==a&&Infinity!==d&&(a+=c,d+=b,isNaN(d)||isNaN(a)||c>d||b>a)?!1:!0};
function Lc(a,b,c){var d=a.aa,e=a.G,f=b.x-c;if(e>b.width+c+c+f||f>d+e)return!1;d=a.$;a=a.H;e=b.y-c;return a>b.height+c+c+e||e>d+a?!1:!0}t.Le=function(a){E&&w(a,J,L,"unionPoint:p");return Mc(this,a.x,a.y,0,0)};t.Lc=function(a){E&&w(a,L,L,"unionRect:r");return Mc(this,a.G,a.H,a.aa,a.$)};
t.bw=function(a,b,c,d){E?(B(a,L,"union:x"),B(b,L,"union:y"),void 0===c?c=0:B(c,L,"union:w"),void 0===d?d=0:B(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 Mc(this,a,b,c,d)};function Mc(a,b,c,d,e){var f=Math.min(a.G,b),g=Math.min(a.H,c);b=Math.max(a.G+a.aa,b+d);c=Math.max(a.H+a.$,c+e);a.G=f;a.H=g;a.aa=b-f;a.$=c-g;return a}
t.vk=function(a,b,c){E&&(B(a,L,"setSpot:x"),B(b,L,"setSpot:y"),w(c,M,L,"setSpot:spot"),this.ha());this.G=a-c.offsetX-c.x*this.aa;this.H=b-c.offsetY-c.y*this.$;return this};
function Qc(a,b,c,d,e,f,g,h){E?(B(a,L,"contains:rx"),B(b,L,"contains:ry"),B(c,L,"contains:rw"),B(d,L,"contains:rh"),B(e,L,"contains:x"),B(f,L,"contains:y"),void 0===g?g=0:B(g,L,"contains:w"),void 0===h?h=0:B(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 Rc(a,b,c,d,e,f,g,h){E&&(B(a,L,"intersects:rx"),B(b,L,"intersects:ry"),B(c,L,"intersects:rw"),B(d,L,"intersects:rh"),B(e,L,"intersects:x"),B(f,L,"intersects:y"),B(g,L,"intersects:w"),B(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.Bz=function(){return 0===this.width&&0===this.height};
L.alloc=function(){var a=Sc.pop();return void 0===a?new L:a};L.allocAt=function(a,b,c,d){var e=Sc.pop();return void 0===e?new L(a,b,c,d):e.h(a,b,c,d)};L.free=function(a){Sc.push(a)};
na.Object.defineProperties(L.prototype,{x:{configurable:!0,get:function(){return this.G},set:function(a){E&&(z(a,"number",L,"x"),this.ha(a));this.G=a}},y:{configurable:!0,get:function(){return this.H},set:function(a){E&&(z(a,"number",L,"y"),this.ha(a));this.H=a}},width:{configurable:!0,get:function(){return this.aa},set:function(a){E&&(z(a,"number",L,"width"),this.ha(a));0>a&&Ca(a,">= 0",L,"width");this.aa=a}},height:{configurable:!0,get:function(){return this.$},
set:function(a){E&&(z(a,"number",L,"height"),this.ha(a));0>a&&Ca(a,">= 0",L,"height");this.$=a}},left:{configurable:!0,get:function(){return this.G},set:function(a){E&&(z(a,"number",L,"left"),this.ha(a));this.G=a}},top:{configurable:!0,get:function(){return this.H},set:function(a){E&&(z(a,"number",L,"top"),this.ha(a));this.H=a}},right:{configurable:!0,get:function(){return this.G+this.aa},set:function(a){E&&(B(a,L,"right"),this.ha(a));this.G+=a-(this.G+this.aa)}},
bottom:{configurable:!0,get:function(){return this.H+this.$},set:function(a){E&&(B(a,L,"top"),this.ha(a));this.H+=a-(this.H+this.$)}},position:{configurable:!0,get:function(){return new J(this.G,this.H)},set:function(a){E&&(w(a,J,L,"position"),this.ha(a));this.G=a.x;this.H=a.y}},size:{configurable:!0,get:function(){return new Zb(this.aa,this.$)},set:function(a){E&&(w(a,Zb,L,"size"),this.ha(a));this.aa=a.width;this.$=a.height}},center:{configurable:!0,
get:function(){return new J(this.G+this.aa/2,this.H+this.$/2)},set:function(a){E&&(w(a,J,L,"center"),this.ha(a));this.G=a.x-this.aa/2;this.H=a.y-this.$/2}},centerX:{configurable:!0,get:function(){return this.G+this.aa/2},set:function(a){E&&(B(a,L,"centerX"),this.ha(a));this.G=a-this.aa/2}},centerY:{configurable:!0,get:function(){return this.H+this.$/2},set:function(a){E&&(B(a,L,"centerY"),this.ha(a));this.H=a-this.$/2}}});L.prototype.isEmpty=L.prototype.Bz;
L.prototype.isReal=L.prototype.o;L.prototype.setSpot=L.prototype.vk;L.prototype.union=L.prototype.bw;L.prototype.unionRect=L.prototype.Lc;L.prototype.unionPoint=L.prototype.Le;L.prototype.intersects=L.prototype.pv;L.prototype.intersectsRect=L.prototype.Kc;L.prototype.intersect=L.prototype.ov;L.prototype.intersectRect=L.prototype.zz;L.prototype.grow=L.prototype.vz;L.prototype.subtractMargin=L.prototype.Vv;L.prototype.addMargin=L.prototype.Sp;L.prototype.inflate=L.prototype.Xc;L.prototype.offset=L.prototype.offset;
L.prototype.contains=L.prototype.contains;L.prototype.containsRect=L.prototype.pf;L.prototype.containsPoint=L.prototype.ea;L.prototype.equalsApprox=L.prototype.Sa;L.prototype.equalTo=L.prototype.Ii;L.prototype.equals=L.prototype.A;L.prototype.setSize=L.prototype.bA;L.prototype.setPoint=L.prototype.ld;L.prototype.set=L.prototype.set;L.prototype.setTo=L.prototype.wg;var Tc=null,Uc=null,Sc=[];L.className="Rect";L.parse=Dc;L.stringify=Ec;L.contains=Qc;L.intersects=Rc;L.ZeroRect=Tc=(new L(0,0,0,0)).ia();
L.NoRect=Uc=(new L(NaN,NaN,NaN,NaN)).ia();L.parse=Dc;L.stringify=Ec;L.contains=Qc;L.intersects=Rc;function Hc(a,b,c,d){void 0===a?this.ne=this.de=this.xe=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}
Hc.prototype.assign=function(a){this.ze=a.ze;this.xe=a.xe;this.de=a.de;this.ne=a.ne;return this};Hc.prototype.wg=function(a,b,c,d){E&&(z(a,"number",Hc,"setTo:t"),z(b,"number",Hc,"setTo:r"),z(c,"number",Hc,"setTo:b"),z(d,"number",Hc,"setTo:l"),this.ha());this.ze=a;this.xe=b;this.de=c;this.ne=d;return this};Hc.prototype.set=function(a){E&&(w(a,Hc,Hc,"assign:m"),this.ha());this.ze=a.ze;this.xe=a.xe;this.de=a.de;this.ne=a.ne;return this};
Hc.prototype.copy=function(){var a=new Hc;a.ze=this.ze;a.xe=this.xe;a.de=this.de;a.ne=this.ne;return a};t=Hc.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 Vc(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 Hc;for(var e=NaN;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));if(isNaN(e))return new Hc(c);for(var f=NaN;""===a[b];)b++;(d=a[b++])&&(f=parseFloat(d));if(isNaN(f))return new Hc(c,e);for(var g=NaN;""===a[b];)b++;(d=a[b++])&&(g=parseFloat(d));return isNaN(g)?new Hc(c,e):new Hc(c,e,f,g)}return new Hc}
function Xc(a){E&&w(a,Hc);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 Hc?this.ze===a.top&&this.xe===a.right&&this.de===a.bottom&&this.ne===a.left:!1};t.Ii=function(a,b,c,d){return this.ze===a&&this.xe===b&&this.de===c&&this.ne===d};
t.Sa=function(a){return K.B(this.ze,a.top)&&K.B(this.xe,a.right)&&K.B(this.de,a.bottom)&&K.B(this.ne,a.left)};t.o=function(){return isFinite(this.top)&&isFinite(this.right)&&isFinite(this.bottom)&&isFinite(this.left)};Hc.alloc=function(){var a=Yc.pop();return void 0===a?new Hc:a};Hc.free=function(a){Yc.push(a)};
na.Object.defineProperties(Hc.prototype,{top:{configurable:!0,get:function(){return this.ze},set:function(a){E&&(B(a,Hc,"top"),this.ha(a));this.ze=a}},right:{configurable:!0,get:function(){return this.xe},set:function(a){E&&(B(a,Hc,"right"),this.ha(a));this.xe=a}},bottom:{configurable:!0,get:function(){return this.de},set:function(a){E&&(B(a,Hc,"bottom"),this.ha(a));this.de=a}},left:{configurable:!0,get:function(){return this.ne},set:function(a){E&&
(B(a,Hc,"left"),this.ha(a));this.ne=a}}});Hc.prototype.isReal=Hc.prototype.o;Hc.prototype.equalsApprox=Hc.prototype.Sa;Hc.prototype.equalTo=Hc.prototype.Ii;Hc.prototype.equals=Hc.prototype.A;Hc.prototype.set=Hc.prototype.set;Hc.prototype.setTo=Hc.prototype.wg;var Zc=null,$c=null,Yc=[];Hc.className="Margin";Hc.parse=Vc;Hc.stringify=Xc;Hc.ZeroMargin=Zc=(new Hc(0,0,0,0)).ia();Hc.TwoMargin=$c=(new Hc(2,2,2,2)).ia();Hc.parse=Vc;Hc.stringify=Xc;
function $b(){this.m11=1;this.m21=this.m12=0;this.m22=1;this.dy=this.dx=0}$b.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};$b.prototype.copy=function(){var a=new $b;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=$b.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 $b?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.it=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.uv=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.gt=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};
$b.prototype.rotate=function(a,b,c){E&&(B(a,$b,"rotate:angle"),B(b,$b,"rotate:rx"),B(c,$b,"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=$b.prototype;
t.translate=function(a,b){E&&(B(a,$b,"translate:x"),B(b,$b,"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&&(B(a,$b,"translate:sx"),B(b,$b,"translate:sy"));this.m11*=a;this.m12*=a;this.m21*=b;this.m22*=b;return this};t.va=function(a){var b=a.x,c=a.y;return a.h(b*this.m11+c*this.m21+this.dx,b*this.m12+c*this.m22+this.dy)};
t.Wd=function(a){var b=1/(this.m11*this.m22-this.m12*this.m21),c=a.x,d=a.y;return a.h(c*this.m22*b+d*-this.m21*b+b*(this.m21*this.dy-this.m22*this.dx),c*-this.m12*b+d*this.m11*b+b*(this.m12*this.dx-this.m11*this.dy))};
t.aw=function(a){var b=a.G,c=a.H,d=b+a.aa,e=c+a.$,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.G=e;a.H=q;a.aa=n-e;a.$=p-q;return a};
$b.alloc=function(){var a=dd.pop();return void 0===a?new $b:a};$b.free=function(a){dd.push(a)};$b.prototype.transformRect=$b.prototype.aw;$b.prototype.invertedTransformPoint=$b.prototype.Wd;$b.prototype.transformPoint=$b.prototype.va;$b.prototype.scale=$b.prototype.scale;$b.prototype.translate=$b.prototype.translate;$b.prototype.rotate=$b.prototype.rotate;$b.prototype.invert=$b.prototype.gt;$b.prototype.multiplyInverted=$b.prototype.uv;$b.prototype.multiply=$b.prototype.multiply;
$b.prototype.reset=$b.prototype.reset;$b.prototype.isIdentity=$b.prototype.it;$b.prototype.equals=$b.prototype.A;$b.prototype.set=$b.prototype.set;var dd=[];$b.className="Transform";$b.xF="54a702f3e53909c447824c6706603faf4c";function M(a,b,c,d){void 0===a?this.Pd=this.Od=this.H=this.G=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 ed,fd,gd,hd,pd,qd,rd,sd,td,ud,vd,wd,Ad,Bd,Cd,Dd,Ed,Fd,Gd,Hd,Id,Md,Nd,Od,Pd,Qd,Rd,Sd,Td,Ud,Vd,Wd,Xd,de,ee,fe;M.prototype.assign=function(a){this.G=a.G;this.H=a.H;this.Od=a.Od;this.Pd=a.Pd;return this};M.prototype.wg=function(a,b,c,d){E&&(ge(a,"setTo:x"),ge(b,"setTo:y"),he(c,"setTo:offx"),he(d,"setTo:offy"),this.ha());this.G=a;this.H=b;this.Od=c;this.Pd=d;return this};M.prototype.set=function(a){E&&(w(a,M,M,"set:s"),this.ha());this.G=a.G;this.H=a.H;this.Od=a.Od;this.Pd=a.Pd;return this};
M.prototype.copy=function(){var a=new M;a.G=this.G;a.H=this.H;a.Od=this.Od;a.Pd=this.Pd;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 ie(a,b){a.G=NaN;a.H=NaN;a.Od=b;return a}function ge(a,b){(isNaN(a)||1<a||0>a)&&Ca(a,"0 <= "+b+" <= 1",M,b)}function he(a,b){(isNaN(a)||Infinity===a||-Infinity===a)&&Ca(a,"real number, not NaN or Infinity",M,b)}
function je(a){if("string"===typeof a){a=a.trim();if("None"===a)return ed;if("TopLeft"===a)return fd;if("Top"===a||"TopCenter"===a||"MiddleTop"===a)return gd;if("TopRight"===a)return hd;if("Left"===a||"LeftCenter"===a||"MiddleLeft"===a)return pd;if("Center"===a)return qd;if("Right"===a||"RightCenter"===a||"MiddleRight"===a)return rd;if("BottomLeft"===a)return sd;if("Bottom"===a||"BottomCenter"===a||"MiddleBottom"===a)return td;if("BottomRight"===a)return ud;if("TopSide"===a)return vd;if("LeftSide"===
a)return wd;if("RightSide"===a)return Ad;if("BottomSide"===a)return Bd;if("TopBottomSides"===a)return Cd;if("LeftRightSides"===a)return Dd;if("TopLeftSides"===a)return Ed;if("TopRightSides"===a)return Fd;if("BottomLeftSides"===a)return Gd;if("BottomRightSides"===a)return Hd;if("NotTopSide"===a)return Id;if("NotLeftSide"===a)return Md;if("NotRightSide"===a)return Nd;if("NotBottomSide"===a)return Od;if("AllSides"===a)return Pd;if("Default"===a)return Qd;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 ke(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.Od&&0===this.Pd?"Spot("+this.x+","+this.y+")":"Spot("+this.x+","+this.y+","+this.offsetX+","+this.offsetY+")":this.A(ed)?"None":this.A(fd)?"TopLeft":this.A(gd)?"Top":this.A(hd)?"TopRight":this.A(pd)?"Left":this.A(qd)?"Center":this.A(rd)?"Right":this.A(sd)?"BottomLeft":this.A(td)?"Bottom":this.A(ud)?"BottomRight":this.A(vd)?"TopSide":this.A(wd)?"LeftSide":this.A(Ad)?"RightSide":this.A(Bd)?"BottomSide":this.A(Cd)?"TopBottomSides":this.A(Dd)?"LeftRightSides":
this.A(Ed)?"TopLeftSides":this.A(Fd)?"TopRightSides":this.A(Gd)?"BottomLeftSides":this.A(Hd)?"BottomRightSides":this.A(Id)?"NotTopSide":this.A(Md)?"NotLeftSide":this.A(Nd)?"NotRightSide":this.A(Od)?"NotBottomSide":this.A(Pd)?"AllSides":this.A(Qd)?"Default":"None"};t.A=function(a){return a instanceof M?(this.G===a.x||isNaN(this.G)&&isNaN(a.x))&&(this.H===a.y||isNaN(this.H)&&isNaN(a.y))&&this.Od===a.offsetX&&this.Pd===a.offsetY:!1};
t.yv=function(){return new M(.5-(this.G-.5),.5-(this.H-.5),-this.Od,-this.Pd)};t.sf=function(a){if(!this.tf())return!1;if(!a.tf())if(a.A(Rd))a=wd;else if(a.A(Sd))a=Ad;else if(a.A(Td))a=vd;else if(a.A(Ud))a=Bd;else return!1;a=a.offsetY;return(this.Pd&a)===a};t.Za=function(){return!isNaN(this.x)&&!isNaN(this.y)};t.Nb=function(){return isNaN(this.x)||isNaN(this.y)};t.tf=function(){return isNaN(this.x)&&isNaN(this.y)&&1===this.offsetX&&0!==this.offsetY};
t.kq=function(){return isNaN(this.x)&&isNaN(this.y)&&0===this.offsetX&&0===this.offsetY};t.Cb=function(){return isNaN(this.x)&&isNaN(this.y)&&-1===this.offsetX&&0===this.offsetY};M.alloc=function(){var a=le.pop();return void 0===a?new M:a};M.free=function(a){le.push(a)};
na.Object.defineProperties(M.prototype,{x:{configurable:!0,get:function(){return this.G},set:function(a){E&&(ge(a,"x"),this.ha(a));this.G=a}},y:{configurable:!0,get:function(){return this.H},set:function(a){E&&(ge(a,"y"),this.ha(a));this.H=a}},offsetX:{configurable:!0,get:function(){return this.Od},set:function(a){E&&(he(a,"offsetX"),this.ha(a));this.Od=a}},offsetY:{configurable:!0,get:function(){return this.Pd},set:function(a){E&&(he(a,"offsetY"),
this.ha(a));this.Pd=a}}});M.prototype.isDefault=M.prototype.Cb;M.prototype.isNone=M.prototype.kq;M.prototype.isSide=M.prototype.tf;M.prototype.isNoSpot=M.prototype.Nb;M.prototype.isSpot=M.prototype.Za;M.prototype.includesSide=M.prototype.sf;M.prototype.opposite=M.prototype.yv;M.prototype.equals=M.prototype.A;M.prototype.set=M.prototype.set;M.prototype.setTo=M.prototype.wg;var le=[];M.className="Spot";M.parse=je;M.stringify=ke;M.None=ed=ie(new M(0,0,0,0),0).ia();M.Default=Qd=ie(new M(0,0,-1,0),-1).ia();
M.TopLeft=fd=(new M(0,0,0,0)).ia();M.TopCenter=gd=(new M(.5,0,0,0)).ia();M.TopRight=hd=(new M(1,0,0,0)).ia();M.LeftCenter=pd=(new M(0,.5,0,0)).ia();M.Center=qd=(new M(.5,.5,0,0)).ia();M.RightCenter=rd=(new M(1,.5,0,0)).ia();M.BottomLeft=sd=(new M(0,1,0,0)).ia();M.BottomCenter=td=(new M(.5,1,0,0)).ia();M.BottomRight=ud=(new M(1,1,0,0)).ia();M.MiddleTop=Vd=gd;M.MiddleLeft=Wd=pd;M.MiddleRight=Xd=rd;M.MiddleBottom=de=td;M.Top=Td=gd;M.Left=Rd=pd;M.Right=Sd=rd;M.Bottom=Ud=td;
M.TopSide=vd=ie(new M(0,0,1,1),1).ia();M.LeftSide=wd=ie(new M(0,0,1,2),1).ia();M.RightSide=Ad=ie(new M(0,0,1,4),1).ia();M.BottomSide=Bd=ie(new M(0,0,1,8),1).ia();M.TopBottomSides=Cd=ie(new M(0,0,1,9),1).ia();M.LeftRightSides=Dd=ie(new M(0,0,1,6),1).ia();M.TopLeftSides=Ed=ie(new M(0,0,1,3),1).ia();M.TopRightSides=Fd=ie(new M(0,0,1,5),1).ia();M.BottomLeftSides=Gd=ie(new M(0,0,1,10),1).ia();M.BottomRightSides=Hd=ie(new M(0,0,1,12),1).ia();M.NotTopSide=Id=ie(new M(0,0,1,14),1).ia();
M.NotLeftSide=Md=ie(new M(0,0,1,13),1).ia();M.NotRightSide=Nd=ie(new M(0,0,1,11),1).ia();M.NotBottomSide=Od=ie(new M(0,0,1,7),1).ia();M.AllSides=Pd=ie(new M(0,0,1,15),1).ia();ee=(new M(.156,.156)).ia();fe=(new M(.844,.844)).ia();M.parse=je;M.stringify=ke;
var K={jA:"7da71ca0ad381e90",Ag:(Math.sqrt(2)-1)/3*4,jw:null,sqrt:function(a){if(0>=a)return 0;var b=K.jw;if(null===b){b=[];for(var c=0;2E3>=c;c++)b[c]=Math.sqrt(c);K.jw=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},da:function(a,b){a-=b;return 5E-8>a&&-5E-8<a},Vb: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},Ps:function(a,b,c,d,e,f,g,h,k,l,m,n){if(K.Vb(a,b,g,h,n,c,d)&&K.Vb(a,b,g,h,n,e,f))return K.Vb(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 x=(d+r)/2,y=(c+u)/2;return K.Ps(a,
b,p,q,d,c,x,y,k,l,m,n)||K.Ps(x,y,r,u,e,f,g,h,k,l,m,n)},wy: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},vy:function(a,b,c,d,e,f,g,h){var k=(c+e)/2,l=(d+f)/2;return ec(((a+c)/2+k)/2,((b+d)/2+l)/2,(k+(e+g)/2)/2,(l+(f+h)/2)/2)},Xl:function(a,b,c,d,e,f,g,h,k,l){if(K.Vb(a,b,g,h,k,c,d)&&K.Vb(a,b,g,h,k,e,f))Mc(l,a,b,0,0),Mc(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.Xl(a,b,m,n,d,c,r,u,k,l);K.Xl(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.Vb(a,b,g,h,k,c,d)&&K.Vb(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},Bv:function(a,b,c,d,e,f,g,h,k,l){if(K.Vb(a,b,e,f,l,c,d))return K.Vb(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.Bv(a,b,m,n,p,q,g,h,k,l)||K.Bv(p,q,c,d,e,f,g,h,k,l)},uA: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},Av:function(a,b,c,d,e,f,g,h){if(K.Vb(a,b,e,f,g,c,d))Mc(h,a,b,0,0),Mc(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.Av(a,b,k,l,m,n,g,h);K.Av(m,n,c,d,e,f,g,h)}return h},tq:function(a,b,c,d,e,f,g,h){if(K.Vb(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.tq(a,b,k,l,m,n,g,h);K.tq(m,n,c,d,e,f,g,h)}return h},Tp:function(a,b,c,d,e,f,g,h,k,l,m,n,p,q){if(K.Vb(a,b,g,h,p,c,d)&&K.Vb(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 x=(r+c)/2,y=(u+d)/2;c=(c+e)/2;d=(d+f)/2;var A=(x+c)/2,C=(y+d)/2,G=(m-k)*(m-k)+(n-l)*(n-l),I=!1;K.Tp(a,b,r,u,x,y,A,C,k,l,m,n,p,q)&&(a=(q.x-k)*(q.x-k)+(q.y-l)*(q.y-l),a<G&&(G=a,I=!0));a=q.x;b=q.y;K.Tp(A,C,c,d,e,f,g,h,k,l,m,n,p,q)&&((q.x-k)*(q.x-k)+(q.y-l)*(q.y-l)<G?I=!0:q.h(a,b));return I},Up:function(a,b,c,d,e,f,g,h,k,l,m,n,p){var q=0;if(K.Vb(a,b,g,h,p,c,d)&&K.Vb(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 x=(c+e)/2,y=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(r+x)/2;c=(u+y)/2;x=(x+e)/2;y=(y+f)/2;var A=(d+x)/2,C=(c+y)/2;q+=K.Up(a,b,r,u,d,c,A,C,k,l,m,n,p);q+=K.Up(A,C,x,y,e,f,g,h,k,l,m,n,p)}return q},Wi:function(a,b,c,d,e,f,g){if(K.da(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.da(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},Ie: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.da(e,g))return K.da(a,c)?(K.Wi(a,b,c,d,e,f,k),!1):K.Wi(a,b,c,d,e,(d-b)/(c-a)*(e-a)+b,k);h=(h-f)/(g-e);if(K.da(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.da(h,g))return K.Wi(a,b,c,d,e,f,k),!1;e=(g*a-h*e+f-b)/(g-h);if(K.da(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.Wi(a,b,c,d,e,g*(e-a)+b,k)},qA:function(a,b,c,d,e){return K.Ie(c.x,c.y,d.x,d.y,a.x,a.y,b.x,b.y,e)},pA: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},
Wc:function(a,b,c,d,e,f,g,h,k){var l=1E21,m=a,n=b;if(K.Ie(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.Ie(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.Ie(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.Ie(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},oA: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},et: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.ea(b)||a.ea(c)||K.dt(h,l,k,l,d,e,f,g)||K.dt(k,l,k,m,d,e,f,g)||K.dt(k,m,h,m,d,e,f,g)||K.dt(h,m,h,l,d,e,f,g)?!0:!1},dt:function(a,b,c,d,e,f,g,h){return 0>=K.Rs(a,b,c,d,e,f)*K.Rs(a,b,c,d,g,h)&&0>=K.Rs(e,
f,g,h,a,b)*K.Rs(e,f,g,h,c,d)},Rs: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},qq: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.Dy(c,l,e,a,b)),d-=Math.abs(e-l),l=e;return f},Dy: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)]},bq: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},Iy: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.Jy(k,0===g?a:b,l,c,0,0)},Jy: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},be:new xb,Gm:new xb};K.za=K.jA;
function me(a){E&&1<arguments.length&&v("Geometry constructor can take at most one optional argument, the Geometry type.");qb(this);this.u=!1;void 0===a?a=ne:E&&tb(a,me,me,"constructor:type");this.wa=a;this.Dc=this.nc=this.dd=this.cd=0;this.lj=new F;this.ur=this.lj.s;this.br=(new L).freeze();this.ta=!0;this.Sm=this.Dk=null;this.Tm=NaN;this.ef=fd;this.ff=ud;this.hl=this.jl=NaN;this.Gf=oe}
me.prototype.copy=function(){var a=new me;a.wa=this.wa;a.cd=this.cd;a.dd=this.dd;a.nc=this.nc;a.Dc=this.Dc;for(var b=this.lj.j,c=b.length,d=a.lj,e=0;e<c;e++){var f=b[e].copy();d.add(f)}a.ur=this.ur;a.br.assign(this.br);a.ta=this.ta;a.Dk=this.Dk;a.Sm=this.Sm;a.Tm=this.Tm;a.ef=this.ef.J();a.ff=this.ff.J();a.jl=this.jl;a.hl=this.hl;a.Gf=this.Gf;return a};t=me.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.Sa=function(a){if(!(a instanceof me))return!1;if(this.type!==a.type)return this.type===pe&&a.type===ne?ue(this,a):a.type===pe&&this.type===ne?ue(a,this):!1;if(this.type===ne){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].Sa(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 ue(a,b){return a.type!==pe||b.type!==ne?!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===ve&&K.B(a.endX,b.endX)&&K.B(a.endY,b.endY)))?!0:!1}function we(a){return a.toString()}t.hb=function(a){a.classType===me?this.type=a:Fa(this,a)};
t.toString=function(a){void 0===a&&(a=-1);switch(this.type){case pe: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 xe:var b=new L(this.startX,this.startY,0,0);b.bw(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 ye:b=new L(this.startX,this.startY,0,0);b.bw(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 ne: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 ze(a,b){function c(){return u>=G-1?!0:null!==k[u+1].match(/[UuBbMmZzLlHhVvCcSsQqTtAaFfXx]/)}function d(){u++;return k[u]}function e(){var a=new J(parseFloat(d()),parseFloat(d()));x===x.toLowerCase()&&(a.x=C.x+a.x,a.y=C.y+a.y);return a}function f(){return C=e()}function g(){return A=e()}function h(){var a=y.toLowerCase();return"c"!==a&&"s"!==a&&"q"!==a&&"t"!==a?C:new J(2*C.x-A.x,2*C.y-A.y)}void 0===b&&(b=!1);"string"!==typeof a&&Ba(a,"string",me,"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=
Qa(),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;Ta(m)}}var u=-1,x="",y="";m=new J(0,0);var A=new J(0,0),C=new J(0,0),G=k.length;a=Ae(null);n=l=!1;p=!0;for(q=null;!(u>=G-1);)if(y=x,x=d(),""!==x)switch(x.toUpperCase()){case "X":p=!0;n=l=!1;break;case "M":q=f();null===a.gc||!0===p?(Be(a,q.x,q.y,l,!n),p=!1):a.moveTo(q.x,q.y);for(m=C;!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();)C=new J((x===x.toLowerCase()?C.x:0)+parseFloat(d()),C.y),a.lineTo(C.x,C.y);break;case "V":for(;!c();)C=new J(C.x,(x===x.toLowerCase()?C.y:0)+parseFloat(d())),a.lineTo(C.x,C.y);break;case "C":for(;!c();){q=e();r=g();var I=f();Ce(a,q.x,q.y,r.x,r.y,I.x,I.y)}break;case "S":for(;!c();)q=h(),r=g(),I=f(),Ce(a,q.x,q.y,r.x,r.y,I.x,I.y);break;case "Q":for(;!c();)q=g(),r=f(),He(a,q.x,q.y,r.x,r.y);break;case "T":for(;!c();)A=q=h(),r=f(),He(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()),R=parseFloat(d()),U=R,ea=!1;c()||(U=parseFloat(d()),c()||(ea=0!==parseFloat(d())));x===x.toLowerCase()&&(I+=C.x,O+=C.y);a.arcTo(q,r,I,O,R,U,ea)}break;case "A":for(;!c();)q=Math.abs(parseFloat(d())),r=Math.abs(parseFloat(d())),I=parseFloat(d()),O=!!parseFloat(d()),R=!!parseFloat(d()),U=f(),Ie(a,q,r,I,O,R,U.x,U.y);break;case "Z":Je(a);C=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.gc.segments.length&&(a.gc.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.Aq(!1)}m=a.Zs;Ke=a;if(b)for(b=m.figures.iterator;b.next();)b.value.isFilled=!0;return m}
function Le(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.sv=function(){if(this.ta||this.ur!==this.figures.s)return!0;for(var a=this.figures.j,b=a.length,c=0;c<b;c++)if(a[c].sv())return!0;return!1};
me.prototype.computeBounds=function(){this.ta=!1;this.Sm=this.Dk=null;this.Tm=NaN;this.ur=this.figures.s;for(var a=this.figures.j,b=a.length,c=0;c<b;c++){var d=a[c];d.ta=!1;var e=d.segments;d.zs=e.s;d=e.j;e=d.length;for(var f=0;f<e;f++){var g=d[f];g.ta=!1;g.Me=null}}a=this.br;a.ja();isNaN(this.jl)||isNaN(this.hl)?a.h(0,0,0,0):a.h(0,0,this.jl,this.hl);Me(this,a,!1);Mc(a,0,0,0,0);a.freeze()};me.prototype.gx=function(){var a=new L;Me(this,a,!0);return a};
function Me(a,b,c){switch(a.type){case pe:case xe:case ye:c?b.h(a.cd,a.dd,0,0):Mc(b,a.cd,a.dd,0,0);Mc(b,a.nc,a.Dc,0,0);break;case ne: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):Mc(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 ve:case Ne:k=n.endX;l=n.endY;Mc(b,k,l,0,0);break;case Oe:K.Xl(k,l,n.point1X,n.point1Y,n.point2X,n.point2Y,n.endX,n.endY,.5,b);k=n.endX;l=n.endY;
break;case Pe:K.Av(k,l,n.point1X,n.point1Y,n.endX,n.endY,.5,b);k=n.endX;l=n.endY;break;case Qe:case Re:var p=n.type===Qe?Se(n,f):Te(n,f,k,l),q=p.length;if(0===q){k=n.centerX;l=n.centerY;Mc(b,k,l,0,0);break}n=null;for(var r=0;r<q;r++)n=p[r],K.Xl(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)}}
me.prototype.normalize=function(){this.u&&za(this);var a=this.gx();this.offset(-a.x,-a.y);return new J(-a.x,-a.y)};me.prototype.offset=function(a,b){this.u&&za(this);E&&(B(a,me,"offset"),B(b,me,"offset"));this.transform(1,0,0,1,a,b);return this};me.prototype.scale=function(a,b){this.u&&za(this);E&&(B(a,me,"scale:x"),B(b,me,"scale:y"),0===a&&Ca(a,"scale must be non-zero",me,"scale:x"),0===b&&Ca(b,"scale must be non-zero",me,"scale:y"));this.transform(a,0,0,b,0,0);return this};
me.prototype.rotate=function(a,b,c){this.u&&za(this);void 0===b&&(b=0);void 0===c&&(c=0);E&&(B(a,me,"rotate:angle"),B(b,me,"rotate:x"),B(c,me,"rotate:y"));var d=$b.alloc();d.reset();d.rotate(a,b,c);this.transform(d.m11,d.m12,d.m21,d.m22,d.dx,d.dy);$b.free(d);return this};t=me.prototype;
t.transform=function(a,b,c,d,e,f){switch(this.type){case pe:case xe:case ye:var g=this.cd;var h=this.dd;this.cd=g*a+h*c+e;this.dd=g*b+h*d+f;g=this.nc;h=this.Dc;this.nc=g*a+h*c+e;this.Dc=g*b+h*d+f;break;case ne: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 ve:case Ne:g=r.endX;h=r.endY;r.endX=g*a+h*c+e;r.endY=g*b+h*d+f;break;case Oe: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 Pe: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 Qe: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 Re: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.ta=!0;return this};
t.ea=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.ea(e,a,b))return!0;var x=u.segments;h=u.startX;k=u.startY;for(var y=h,A=k,C=x.j,G=0;G<=x.length;G++){var I=void 0;if(G!==x.length){I=C[G];var O=I.type;m=I.endX;n=I.endY}else O=ve,m=y,n=A;switch(O){case Ne:y=Ue(e,a,f,a,h,k,y,A);if(isNaN(y))return!0;g+=y;y=m;A=n;break;case ve:h=Ue(e,a,f,a,h,k,m,n);if(isNaN(h))return!0;g+=h;break;case Oe:l=K.Up(h,
k,I.point1X,I.point1Y,I.point2X,I.point2Y,m,n,f,a,e,a,.5);g+=l;break;case Pe:l=K.Up(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 Qe:case Re:O=I.type===Qe?Se(I,u):Te(I,u,h,k);var R=O.length;if(0===R){h=Ue(e,a,f,a,h,k,I.centerX,I.centerY);if(isNaN(h))return!0;g+=h;break}I=null;for(var U=0;U<R;U++){I=O[U];if(0===U){l=Ue(e,a,f,a,h,k,I[0],I[1]);if(isNaN(l))return!0;g+=l}l=K.Up(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.ea(e,a,d?b:b+2))return!0}return 0!==g};function Ue(a,b,c,d,e,f,g,h){if(K.Vb(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 Ve(a,b,c,d){a=a.figures.j;for(var e=a.length,f=0;f<e;f++)if(a[f].ea(b,c,d))return!0;return!1}
t.kv=function(a,b){0>a?a=0:1<a&&(a=1);void 0===b&&(b=new J);if(this.type===pe)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===pe){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===xe){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 x=p[u],y=p[u+1];if(0!==u){K.Wi(l,m,x,y,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=x;m=y}J.free(d);a=g/f;return 0>a?0:1<a?1:a}return 0};
function We(a){if(null===a.Dk){var b=a.Dk=[],c=a.Sm=[],d=[],e=[];if(a.type===pe)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===xe)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===ye){var f=new Xe;f.startX=a.endX;f.startY=(a.startY+a.endY)/2;var g=new Ye(Qe);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=Se(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 Ne: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 ve:d.push(p.endX);d.push(p.endY);g=p.endX;f=p.endY;break;case Oe: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 Pe:K.tq(g,f,p.point1X,p.point1Y,p.endX,p.endY,.5,d);g=p.endX;f=p.endY;break;case Qe:var q=Se(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 x=q[u];K.Ce(g,f,x[2],x[3],x[4],x[5],x[6],x[7],.5,d);g=x[6];f=x[7]}break;case Re:q=Te(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++)x=q[u],K.Ce(g,f,x[2],x[3],x[4],x[5],x[6],x[7],.5,d),g=x[6],
f=x[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(dc(c,d,g,h)),b.push(c));c=g;d=h}return b}t.add=function(a){this.lj.add(a);return this};t.Dm=function(a,b,c,d,e,f,g,h){this.u&&za(this);this.ef=(new M(a,b,e,f)).freeze();this.ff=(new M(c,d,g,h)).freeze();return this};
na.Object.defineProperties(me.prototype,{flattenedSegments:{configurable:!0,get:function(){We(this);return this.Dk}},flattenedLengths:{configurable:!0,get:function(){We(this);return this.Sm}},flattenedTotalLength:{configurable:!0,get:function(){var a=this.Tm;if(isNaN(a)){if(this.type===pe){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===xe)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.Tm=a}return a}},type:{configurable:!0,get:function(){return this.wa},set:function(a){this.wa!==a&&(E&&tb(a,me,me,"type"),this.u&&za(this,a),this.wa=a,this.ta=!0)}},startX:{configurable:!0,get:function(){return this.cd},set:function(a){this.cd!==a&&(E&&B(a,me,"startX"),this.u&&za(this,a),this.cd=a,this.ta=!0)}},startY:{configurable:!0,
get:function(){return this.dd},set:function(a){this.dd!==a&&(E&&B(a,me,"startY"),this.u&&za(this,a),this.dd=a,this.ta=!0)}},endX:{configurable:!0,get:function(){return this.nc},set:function(a){this.nc!==a&&(E&&B(a,me,"endX"),this.u&&za(this,a),this.nc=a,this.ta=!0)}},endY:{configurable:!0,get:function(){return this.Dc},set:function(a){this.Dc!==a&&(E&&B(a,me,"endY"),this.u&&za(this,a),this.Dc=a,this.ta=!0)}},figures:{configurable:!0,get:function(){return this.lj},
set:function(a){this.lj!==a&&(E&&w(a,F,me,"figures"),this.u&&za(this,a),this.lj=a,this.ta=!0)}},spot1:{configurable:!0,get:function(){return this.ef},set:function(a){E&&w(a,M,me,"spot1");this.u&&za(this,a);this.ef=a.J()}},spot2:{configurable:!0,get:function(){return this.ff},set:function(a){E&&w(a,M,me,"spot2");this.u&&za(this,a);this.ff=a.J()}},defaultStretch:{configurable:!0,get:function(){return this.Gf},set:function(a){E&&tb(a,N,me,"stretch");this.u&&
za(this,a);this.Gf=a}},bounds:{configurable:!0,get:function(){this.sv()&&this.computeBounds();return this.br}}});me.prototype.setSpots=me.prototype.Dm;me.prototype.add=me.prototype.add;me.prototype.getFractionForPoint=me.prototype.qx;me.prototype.getPointAlongPath=me.prototype.kv;me.prototype.transform=me.prototype.transform;me.prototype.rotate=me.prototype.rotate;me.prototype.scale=me.prototype.scale;me.prototype.offset=me.prototype.offset;me.prototype.normalize=me.prototype.normalize;
me.prototype.computeBoundsWithoutOrigin=me.prototype.gx;me.prototype.equalsApprox=me.prototype.Sa;var pe=new D(me,"Line",0),xe=new D(me,"Rectangle",1),ye=new D(me,"Ellipse",2),ne=new D(me,"Path",3);me.className="Geometry";me.stringify=we;me.fillPath=function(a){"string"!==typeof a&&Ba(a,"string",me,"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};
me.parse=ze;me.Line=pe;me.Rectangle=xe;me.Ellipse=ye;me.Path=ne;function Xe(a,b,c,d){qb(this);this.u=!1;void 0===c&&(c=!0);this.Ir=c;void 0===d&&(d=!0);this.Mr=d;void 0!==a?(E&&B(a,Xe,"sx"),this.cd=a):this.cd=0;void 0!==b?(E&&B(b,Xe,"sy"),this.dd=b):this.dd=0;this.Gl=new F;this.zs=this.Gl.s;this.ta=!0}
Xe.prototype.copy=function(){var a=new Xe;a.Ir=this.Ir;a.Mr=this.Mr;a.cd=this.cd;a.dd=this.dd;for(var b=this.Gl.j,c=b.length,d=a.Gl,e=0;e<c;e++){var f=b[e].copy();d.add(f)}a.zs=this.zs;a.ta=this.ta;return a};t=Xe.prototype;t.Sa=function(a){if(!(a instanceof Xe&&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].Sa(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.sv=function(){if(this.ta)return!0;var a=this.segments;if(this.zs!==a.s)return!0;a=a.j;for(var b=a.length,c=0;c<b;c++)if(a[c].ta)return!0;return!1};t.add=function(a){this.Gl.add(a);return this};
t.ea=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 Ne:f=m.endX;g=m.endY;d=m.endX;e=m.endY;break;case ve:if(K.Vb(d,e,m.endX,m.endY,c,a,b))return!0;d=m.endX;e=m.endY;break;case Oe:if(K.Ps(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 Pe:if(K.Bv(d,e,m.point1X,m.point1Y,m.endX,m.endY,.5,a,b,c))return!0;d=m.endX;e=m.endY;break;case Qe:case Re:var n=m.type===
Qe?Se(m,this):Te(m,this,d,e),p=n.length;if(0===p){if(K.Vb(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.Vb(d,e,q[0],q[1],c,a,b)||K.Ps(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.Vb(d,e,f,g,c,a,b))return!0}return!1};
na.Object.defineProperties(Xe.prototype,{isFilled:{configurable:!0,get:function(){return this.Ir},set:function(a){E&&z(a,"boolean",Xe,"isFilled");this.u&&za(this,a);this.Ir=a}},isShadowed:{configurable:!0,get:function(){return this.Mr},set:function(a){E&&z(a,"boolean",Xe,"isShadowed");this.u&&za(this,a);this.Mr=a}},startX:{configurable:!0,get:function(){return this.cd},set:function(a){E&&B(a,Xe,"startX");this.u&&za(this,a);this.cd=a;this.ta=!0}},startY:{configurable:!0,
enumerable:!0,get:function(){return this.dd},set:function(a){E&&B(a,Xe,"startY");this.u&&za(this,a);this.dd=a;this.ta=!0}},segments:{configurable:!0,get:function(){return this.Gl},set:function(a){E&&w(a,F,Xe,"segments");this.u&&za(this,a);this.Gl=a;this.ta=!0}}});Xe.prototype.add=Xe.prototype.add;Xe.prototype.equalsApprox=Xe.prototype.Sa;Xe.className="PathFigure";
function Ye(a,b,c,d,e,f,g,h){qb(this);this.u=!1;void 0===a?a=ve:E&&tb(a,Ye,Ye,"constructor:type");this.wa=a;void 0!==b?(E&&B(b,Ye,"ex"),this.nc=b):this.nc=0;void 0!==c?(E&&B(c,Ye,"ey"),this.Dc=c):this.Dc=0;void 0===d&&(d=0);void 0===e&&(e=0);void 0===f&&(f=0);void 0===g&&(g=0);a===Re?(a=f%360,0>a&&(a+=360),this.we=a,this.ri=0,E&&B(d,Ye,"x1"),this.si=Math.max(d,0),E&&B(e,Ye,"y1"),this.ah=Math.max(e,0),this.nl="boolean"===typeof g?!!g:!1,this.Jk=!!h):(E&&B(d,Ye,"x1"),this.we=d,E&&B(e,Ye,"y1"),this.ri=
e,E&&B(f,Ye,"x2"),a===Qe&&(f=Math.max(f,0)),this.si=f,"number"===typeof g?(a===Qe&&(g=Math.max(g,0)),this.ah=g):this.ah=0,this.Jk=this.nl=!1);this.qj=!1;this.ta=!0;this.Me=null}Ye.prototype.copy=function(){var a=new Ye;a.wa=this.wa;a.nc=this.nc;a.Dc=this.Dc;a.we=this.we;a.ri=this.ri;a.si=this.si;a.ah=this.ah;a.nl=this.nl;a.Jk=this.Jk;a.qj=this.qj;a.ta=this.ta;return a};t=Ye.prototype;
t.Sa=function(a){if(!(a instanceof Ye)||this.type!==a.type||this.isClosed!==a.isClosed)return!1;switch(this.type){case Ne:case ve:return K.B(this.endX,a.endX)&&K.B(this.endY,a.endY);case Oe: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 Pe: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 Qe: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 Re: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.hb=function(a){a.classType===Ye?this.type=a:Fa(this,a)};
t.toString=function(a){void 0===a&&(a=-1);switch(this.type){case Ne:a=0>a?"M"+this.endX.toString()+" "+this.endY.toString():"M"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case ve:a=0>a?"L"+this.endX.toString()+" "+this.endY.toString():"L"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case Oe: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 Pe: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 Qe: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 Re: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.qj?"z":"")};t.freeze=function(){this.u=!0;return this};t.ja=function(){this.u=!1;return this};t.close=function(){this.qj=!0;return this};
function Se(a,b){if(null!==a.Me&&!1===b.ta)return a.Me;var c=a.radiusX,d=a.radiusY;void 0===d&&(d=c);if(0===c||0===d)return a.Me=[],a.Me;b=a.we;var e=a.ri,f=K.hx(0,0,c<d?c:d,a.startAngle,a.startAngle+a.sweepAngle,!1);if(c!==d){var g=$b.alloc();g.reset();c<d?g.scale(1,d/c):g.scale(c/d,1);Le(f,g);$b.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.Me=f;return a.Me}
function Te(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.Me&&!1===b.ta)return a.Me;b=a.si;var f=a.ah;0===b&&(b=1E-4);0===f&&(f=1E-4);var g=Math.PI/180*a.we,h=a.nl,k=a.Jk,l=a.nc,m=a.Dc,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=$b.alloc();f.reset();f.translate(c,d);f.rotate(a.we,0,0);f.scale(k,q);Le(b,f);$b.free(f);a.Me=b;return a.Me}
na.Object.defineProperties(Ye.prototype,{isClosed:{configurable:!0,get:function(){return this.qj},set:function(a){this.qj!==a&&(this.qj=a,this.ta=!0)}},type:{configurable:!0,get:function(){return this.wa},set:function(a){E&&tb(a,Ye,Ye,"type");this.u&&za(this,a);this.wa=a;this.ta=!0}},endX:{configurable:!0,get:function(){return this.nc},set:function(a){E&&B(a,Ye,"endX");this.u&&za(this,a);this.nc=a;this.ta=!0}},endY:{configurable:!0,get:function(){return this.Dc},
set:function(a){E&&B(a,Ye,"endY");this.u&&za(this,a);this.Dc=a;this.ta=!0}},point1X:{configurable:!0,get:function(){return this.we},set:function(a){E&&B(a,Ye,"point1X");this.u&&za(this,a);this.we=a;this.ta=!0}},point1Y:{configurable:!0,get:function(){return this.ri},set:function(a){E&&B(a,Ye,"point1Y");this.u&&za(this,a);this.ri=a;this.ta=!0}},point2X:{configurable:!0,get:function(){return this.si},set:function(a){E&&B(a,Ye,"point2X");this.u&&za(this,a);this.si=
a;this.ta=!0}},point2Y:{configurable:!0,get:function(){return this.ah},set:function(a){E&&B(a,Ye,"point2Y");this.u&&za(this,a);this.ah=a;this.ta=!0}},centerX:{configurable:!0,get:function(){return this.we},set:function(a){E&&B(a,Ye,"centerX");this.u&&za(this,a);this.we=a;this.ta=!0}},centerY:{configurable:!0,get:function(){return this.ri},set:function(a){E&&B(a,Ye,"centerY");this.u&&za(this,a);this.ri=a;this.ta=!0}},radiusX:{configurable:!0,
get:function(){return this.si},set:function(a){E&&B(a,Ye,"radiusX");0>a&&Ca(a,">= zero",Ye,"radiusX");this.u&&za(this,a);this.si=a;this.ta=!0}},radiusY:{configurable:!0,get:function(){return this.ah},set:function(a){E&&B(a,Ye,"radiusY");0>a&&Ca(a,">= zero",Ye,"radiusY");this.u&&za(this,a);this.ah=a;this.ta=!0}},startAngle:{configurable:!0,get:function(){return this.nc},set:function(a){this.nc!==a&&(this.u&&za(this,a),E&&B(a,Ye,"startAngle"),a%=360,0>a&&(a+=360),this.nc=
a,this.ta=!0)}},sweepAngle:{configurable:!0,get:function(){return this.Dc},set:function(a){E&&B(a,Ye,"sweepAngle");this.u&&za(this,a);360<a&&(a=360);-360>a&&(a=-360);this.Dc=a;this.ta=!0}},isClockwiseArc:{configurable:!0,get:function(){return this.Jk},set:function(a){this.u&&za(this,a);this.Jk=a;this.ta=!0}},isLargeArc:{configurable:!0,get:function(){return this.nl},set:function(a){this.u&&za(this,a);this.nl=a;this.ta=!0}},xAxisRotation:{configurable:!0,
get:function(){return this.we},set:function(a){E&&B(a,Ye,"xAxisRotation");a%=360;0>a&&(a+=360);this.u&&za(this,a);this.we=a;this.ta=!0}}});Ye.prototype.equalsApprox=Ye.prototype.Sa;var Ne=new D(Ye,"Move",0),ve=new D(Ye,"Line",1),Oe=new D(Ye,"Bezier",2),Pe=new D(Ye,"QuadraticBezier",3),Qe=new D(Ye,"Arc",4),Re=new D(Ye,"SvgArc",4);Ye.className="PathSegment";Ye.Move=Ne;Ye.Line=ve;Ye.Bezier=Oe;Ye.QuadraticBezier=Pe;Ye.Arc=Qe;Ye.SvgArc=Re;
function kf(){this.D=null;this.Hu=(new J(0,0)).freeze();this.Yt=(new J(0,0)).freeze();this.Vq=this.bs=0;this.Wq=1;this.Qr="";this.Ks=this.mr=!1;this.lr=this.Yq=0;this.Eg=this.zr=this.Kr=!1;this.tr=null;this.Is=0;this.Sd=this.Hs=null}kf.prototype.copy=function(){var a=new kf;return this.clone(a)};
kf.prototype.clone=function(a){a.D=this.D;a.Hu.assign(this.viewPoint);a.Yt.assign(this.documentPoint);a.bs=this.bs;a.Vq=this.Vq;a.Wq=this.Wq;a.Qr=this.Qr;a.mr=this.mr;a.Ks=this.Ks;a.Yq=this.Yq;a.lr=this.lr;a.Kr=this.Kr;a.zr=this.zr;a.Eg=this.Eg;a.tr=this.tr;a.Is=this.Is;a.Hs=this.Hs;a.Sd=this.Sd;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.fq=function(a,b){var c=this.diagram;if(null===c)return b;lf(c,this.event,a,b);return b};
kf.prototype.mz=function(a,b){var c=this.diagram;if(null===c)return b;lf(c,this.event,a,b);b.assign(c.Dt(b));return b};
na.Object.defineProperties(kf.prototype,{diagram:{configurable:!0,get:function(){return this.D},set:function(a){this.D=a}},viewPoint:{configurable:!0,get:function(){return this.Hu},set:function(a){w(a,J,kf,"viewPoint");this.Hu.assign(a)}},documentPoint:{configurable:!0,get:function(){return this.Yt},set:function(a){w(a,J,kf,"documentPoint");this.Yt.assign(a)}},modifiers:{configurable:!0,get:function(){return this.bs},set:function(a){this.bs=
a}},button:{configurable:!0,get:function(){return this.Vq},set:function(a){this.Vq=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.Wq},set:function(a){this.Wq=a}},key:{configurable:!0,get:function(){return this.Qr},set:function(a){this.Qr=a}},down:{configurable:!0,get:function(){return this.mr},set:function(a){this.mr=a}},up:{configurable:!0,
enumerable:!0,get:function(){return this.Ks},set:function(a){this.Ks=a}},clickCount:{configurable:!0,get:function(){return this.Yq},set:function(a){this.Yq=a}},delta:{configurable:!0,get:function(){return this.lr},set:function(a){this.lr=a}},isMultiTouch:{configurable:!0,get:function(){return this.Kr},set:function(a){this.Kr=a}},handled:{configurable:!0,get:function(){return this.zr},set:function(a){this.zr=a}},bubbles:{configurable:!0,
get:function(){return this.Eg},set:function(a){this.Eg=a}},event:{configurable:!0,get:function(){return this.tr},set:function(a){this.tr=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.Is},set:function(a){this.Is=a}},targetDiagram:{configurable:!0,
get:function(){return this.Hs},set:function(a){this.Hs=a}},targetObject:{configurable:!0,get:function(){return this.Sd},set:function(a){this.Sd=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.mz;kf.prototype.getMultiTouchViewPoint=kf.prototype.fq;kf.className="InputEvent";function mf(){this.D=null;this.Wa="";this.ms=this.Fs=null}mf.prototype.copy=function(){var a=new mf;a.D=this.D;a.Wa=this.Wa;a.Fs=this.Fs;a.ms=this.ms;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.D},set:function(a){this.D=a}},name:{configurable:!0,get:function(){return this.Wa},set:function(a){this.Wa=a}},subject:{configurable:!0,get:function(){return this.Fs},set:function(a){this.Fs=a}},parameter:{configurable:!0,get:function(){return this.ms},set:function(a){this.ms=a}}});mf.className="DiagramEvent";
function nf(){this.$m=of;this.Ij=this.$r="";this.Go=this.Ho=this.Mo=this.No=this.Lo=this.D=this.ac=null}nf.prototype.clear=function(){this.Go=this.Ho=this.Mo=this.No=this.Lo=this.D=this.ac=null};
nf.prototype.copy=function(){var a=new nf;a.$m=this.$m;a.$r=this.$r;a.Ij=this.Ij;a.ac=this.ac;a.D=this.D;a.Lo=this.Lo;var b=this.No;a.No=Ja(b)&&"function"===typeof b.J?b.J():b;b=this.Mo;a.Mo=Ja(b)&&"function"===typeof b.J?b.J():b;b=this.Ho;a.Ho=Ja(b)&&"function"===typeof b.J?b.J():b;b=this.Go;a.Go=Ja(b)&&"function"===typeof b.J?b.J():b;return a};nf.prototype.hb=function(a){a.classType===nf?this.change=a:Fa(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+=Wa(this.object)),null!==this.oldValue&&(a+=" old: "+Wa(this.oldValue)),null!==
this.oldParam&&(a+=" "+this.oldParam),null!==this.newValue&&(a+=" new: "+Wa(this.newValue)),null!==this.newParam&&(a+=" "+this.newParam));return a};nf.prototype.K=function(a){return a?this.oldValue:this.newValue};nf.prototype.oz=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.Wj(this,!0):null!==this.diagram&&this.diagram.Wj(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.Wj(this,!1):null!==this.diagram&&this.diagram.Wj(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.D},set:function(a){this.D=a}},change:{configurable:!0,get:function(){return this.$m},set:function(a){E&&tb(a,nf,nf,"change");this.$m=a}},modelChange:{configurable:!0,get:function(){return this.$r},set:function(a){E&&z(a,"string",nf,"modelChange");this.$r=a}},propertyName:{configurable:!0,
enumerable:!0,get:function(){return this.Ij},set:function(a){E&&"string"!==typeof a&&z(a,"function",nf,"propertyName");this.Ij=a}},isTransactionFinished:{configurable:!0,get:function(){return this.$m===pf&&("CommittedTransaction"===this.Ij||"FinishedUndo"===this.Ij||"FinishedRedo"===this.Ij)}},object:{configurable:!0,get:function(){return this.Lo},set:function(a){this.Lo=a}},oldValue:{configurable:!0,get:function(){return this.No},set:function(a){this.No=
a}},oldParam:{configurable:!0,get:function(){return this.Mo},set:function(a){this.Mo=a}},newValue:{configurable:!0,get:function(){return this.Ho},set:function(a){this.Ho=a}},newParam:{configurable:!0,get:function(){return this.Go},set:function(a){this.Go=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.oz;
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 sf(){this.w=(new F).freeze();this.Wa="";this.l=!1}
sf.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};sf.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()};sf.prototype.canUndo=function(){return this.isComplete};
sf.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()}};sf.prototype.canRedo=function(){return this.isComplete};sf.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(sf.prototype,{changes:{configurable:!0,get:function(){return this.w}},name:{configurable:!0,get:function(){return this.Wa},set:function(a){this.Wa=a}},isComplete:{configurable:!0,get:function(){return this.l},set:function(a){this.l=a}}});sf.prototype.redo=sf.prototype.redo;sf.prototype.canRedo=sf.prototype.canRedo;sf.prototype.undo=sf.prototype.undo;sf.prototype.canUndo=sf.prototype.canUndo;sf.prototype.clear=sf.prototype.clear;
sf.className="Transaction";function tf(){this.ou=new H;this.Fc=!1;this.L=(new F).freeze();this.ie=-1;this.w=999;this.ke=!1;this.jr=null;this.Ci=0;this.l=!1;E&&(this.l=!0);this.te=(new F).freeze();this.xl=new F;this.eu=!0;this.iu=!1}
tf.prototype.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};
tf.prototype.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.ke=!1;this.jr=null;this.Ci=0;this.te.ja();this.te.clear();this.te.freeze();this.xl.clear()};tf.prototype.copyProperties=function(a){this.isEnabled=a.isEnabled;this.maxHistoryLength=a.maxHistoryLength;this.checksTransactionLevel=a.checksTransactionLevel};t=tf.prototype;t.Xw=function(a){this.ou.add(a)};t.Gx=function(a){this.ou.remove(a)};
t.Ca=function(a){void 0===a&&(a="");null===a&&(a="");if(this.isUndoingRedoing)return!1;!0===this.eu&&(this.eu=!1,this.Ci++,this.zb("StartingFirstTransaction",a,this.currentTransaction),0<this.Ci&&this.Ci--);this.isEnabled&&(this.te.ja(),this.te.add(a),this.te.freeze(),null===this.currentTransaction?this.xl.add(0):this.xl.add(this.currentTransaction.changes.count));this.Ci++;var b=1===this.transactionLevel;b&&this.zb("StartedTransaction",a,this.currentTransaction);return b};
t.ab=function(a){void 0===a&&(a="");return uf(this,!0,a)};t.xf=function(){return uf(this,!1,"")};
function uf(a,b,c){if(a.isUndoingRedoing)return!1;a.checksTransactionLevel&&1>a.transactionLevel&&Ha("Ending transaction without having started a transaction: "+c);var d=1===a.transactionLevel;d&&b&&a.zb("CommittingTransaction",c,a.currentTransaction);var e=0;if(0<a.transactionLevel&&(a.Ci--,a.isEnabled)){var f=a.te.count;0<f&&(""===c&&(c=a.te.O(0)),a.te.ja(),a.te.nb(f-1),a.te.freeze());f=a.xl.count;0<f&&(e=a.xl.O(f-1),a.xl.nb(f-1))}f=a.currentTransaction;if(d){if(b){a.iu=!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.nb(e),a.iu=!0;e=a.maxHistoryLength;0<=e&&(0===e?d.clear():d.count>=e&&(f=d.O(0),null!==f&&f.clear(),d.nb(0),a.ie--));0!==e&&(d.add(b),a.ie++);d.freeze();f=b}a.zb("CommittedTransaction",c,f)}else{a.ke=!0;try{a.isEnabled&&null!==f&&(f.isComplete=!0,f.undo())}finally{a.zb("RolledBackTransaction",c,f),a.ke=!1}null!==f&&f.clear()}a.jr=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.nb(b);c.freeze()}return!1}tf.prototype.canUndo=function(){if(!this.isEnabled||0<this.transactionLevel)return!1;var a=this.transactionToUndo;return null!==a&&a.canUndo()?!0:!1};tf.prototype.undo=function(){if(this.canUndo()){var a=this.transactionToUndo;try{this.ke=!0,this.zb("StartingUndo","Undo",a),this.ie--,a.undo()}catch(b){Ha("undo error: "+b.toString())}finally{this.zb("FinishedUndo","Undo",a),this.ke=!1}}};
tf.prototype.canRedo=function(){if(!this.isEnabled||0<this.transactionLevel)return!1;var a=this.transactionToRedo;return null!==a&&a.canRedo()?!0:!1};tf.prototype.redo=function(){if(this.canRedo()){var a=this.transactionToRedo;try{this.ke=!0,this.zb("StartingRedo","Redo",a),this.ie++,a.redo()}catch(b){Ha("redo error: "+b.toString())}finally{this.zb("FinishedRedo","Redo",a),this.ke=!1}}};
tf.prototype.zb=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.Qs(d)};
tf.prototype.nv=function(a){if(this.isEnabled&&!this.isUndoingRedoing&&!this.skipsEvent(a)){var b=this.currentTransaction;null===b&&(this.jr=b=new sf);var c=a.copy();b=b.changes;b.ja();b.add(c);b.freeze();this.checksTransactionLevel&&0>=this.transactionLevel&&!this.eu&&(a=a.diagram,null!==a&&!1===a.Ui||Ha("Change not within a transaction: "+c.toString()))}};
tf.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(tf.prototype,{models:{configurable:!0,get:function(){return this.ou.iterator}},isEnabled:{configurable:!0,get:function(){return this.Fc},set:function(a){this.Fc=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.ke}},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.jr}},transactionLevel:{configurable:!0,
get:function(){return this.Ci}},isInTransaction:{configurable:!0,get:function(){return 0<this.Ci}},checksTransactionLevel:{configurable:!0,get:function(){return this.l},set:function(a){this.l=a}},nestedTransactionNames:{configurable:!0,get:function(){return this.te}}});tf.prototype.handleChanged=tf.prototype.nv;tf.prototype.redo=tf.prototype.redo;tf.prototype.undo=tf.prototype.undo;tf.prototype.canUndo=tf.prototype.canUndo;
tf.prototype.rollbackTransaction=tf.prototype.xf;tf.prototype.commitTransaction=tf.prototype.ab;tf.prototype.startTransaction=tf.prototype.Ca;tf.prototype.removeModel=tf.prototype.Gx;tf.prototype.addModel=tf.prototype.Xw;tf.prototype.clear=tf.prototype.clear;tf.className="UndoManager";function vf(){0<arguments.length&&Da(vf);qb(this);this.D=yf;this.Wa="";this.Fc=!0;this.Wb=!1;this.Iq=null;this.jy=new kf;this.Ns=-1}vf.prototype.ib=function(a){this.D=a};
vf.prototype.toString=function(){return""!==this.name?this.name+" Tool":Va(this.constructor)};vf.prototype.updateAdornments=function(){};vf.prototype.canStart=function(){return this.isEnabled};vf.prototype.doStart=function(){};vf.prototype.doActivate=function(){this.isActive=!0};vf.prototype.doDeactivate=function(){this.isActive=!1};vf.prototype.doStop=function(){};vf.prototype.doCancel=function(){this.transactionResult=null;this.stopTool()};
vf.prototype.stopTool=function(){var a=this.diagram;a.currentTool===this&&(a.currentTool=null,a.currentCursor="")};vf.prototype.doMouseDown=function(){!this.isActive&&this.canStart()&&this.doActivate()};vf.prototype.doMouseMove=function(){};vf.prototype.doMouseUp=function(){this.stopTool()};vf.prototype.doMouseWheel=function(){};vf.prototype.canStartMultiTouch=function(){return!0};
vf.prototype.standardPinchZoomStart=function(){var a=this.diagram,b=a.lastInput,c=b.fq(0,J.allocAt(NaN,NaN)),d=b.fq(1,J.allocAt(NaN,NaN));if(c.o()&&d.o()&&(this.doCancel(),a.gm("hasGestureZoom"))){a.Oo=a.scale;var e=d.x-c.x,f=d.y-c.y;a.Nw=Math.sqrt(e*e+f*f);b.bubbles=!1}J.free(c);J.free(d)};
vf.prototype.standardPinchZoomMove=function(){var a=this.diagram,b=a.lastInput,c=b.fq(0,J.allocAt(NaN,NaN)),d=b.fq(1,J.allocAt(NaN,NaN));if(c.o()&&d.o()&&(this.doCancel(),a.gm("hasGestureZoom"))){var e=d.x-c.x,f=d.y-c.y;f=Math.sqrt(e*e+f*f)/a.Nw;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.Oo;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)};
vf.prototype.doKeyDown=function(){"Esc"===this.diagram.lastInput.key&&this.doCancel()};vf.prototype.doKeyUp=function(){};vf.prototype.Ca=function(a){void 0===a&&(a=this.name);this.transactionResult=null;return this.diagram.Ca(a)};vf.prototype.yg=function(){var a=this.diagram;return null===this.transactionResult?a.xf():a.ab(this.transactionResult)};
vf.prototype.standardMouseSelect=function(){var a=this.diagram;if(a.allowSelect){var b=a.lastInput,c=a.em(b.documentPoint,!1);if(null!==c)if(kb?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||(kb?b.meta:b.control)||b.shift||a.Vp()}};vf.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;zf(a,d,c);return d.handled};
function zf(a,b,c){b.handled=!1;if(null===a||a.ug()){var d=0;b.left?d=1===b.clickCount?1:2===b.clickCount?2:1:b.right&&1===b.clickCount&&(d=3);var e="ObjectSingleClicked";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)}}}
vf.prototype.standardMouseOver=function(){var a=this.diagram,b=a.lastInput;if(!0!==a.animationManager.sb){var c=a.skipsUndoManager;a.skipsUndoManager=!0;var d=a.viewportBounds.ea(b.documentPoint)?a.Tb(b.documentPoint,null,null):null;b.targetObject=d;var e=!1;if(d!==a.Ok){var f=a.Ok,g=f;a.Ok=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.tg(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.tg(d))break;g(b,d,f);e=!0;if(b.handled)break}d=d.panel}d=a.Ok}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.ec();a.skipsUndoManager=c}};vf.prototype.doCurrentObjectChanged=function(){};
vf.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===Af&&!b.shift||e===Bf&&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===Af&&b.shift||e===Bf&&!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||jb)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)}}};vf.prototype.standardWaitAfter=function(a,b){E&&z(a,"number",vf,"standardWaitAfter:delay");void 0===b&&(b=this.diagram.lastInput);this.cancelWaitAfter();var c=this,d=b.clone(this.jy);this.Ns=wa(function(){c.doWaitAfter(d)},a)};vf.prototype.cancelWaitAfter=function(){-1!==this.Ns&&ra.clearTimeout(this.Ns);this.Ns=-1};
vf.prototype.doWaitAfter=function(){};vf.prototype.findToolHandleAt=function(a,b){a=this.diagram.Tb(a,function(a){for(;null!==a&&!(a.panel instanceof Cf);)a=a.panel;return a});return null===a?null:a.part.category===b?a:null};vf.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(vf.prototype,{diagram:{configurable:!0,get:function(){return this.D},set:function(a){a instanceof P&&(this.D=a)}},name:{configurable:!0,get:function(){return this.Wa},set:function(a){z(a,"string",vf,"name");this.Wa=a}},isEnabled:{configurable:!0,get:function(){return this.Fc},set:function(a){z(a,"boolean",vf,"isEnabled");this.Fc=a}},isActive:{configurable:!0,get:function(){return this.Wb},set:function(a){z(a,"boolean",
vf,"isActive");this.Wb=a}},transactionResult:{configurable:!0,get:function(){return this.Iq},set:function(a){null!==a&&z(a,"string",vf,"transactionResult");this.Iq=a}}});vf.prototype.stopTransaction=vf.prototype.yg;vf.prototype.startTransaction=vf.prototype.Ca;vf.className="Tool";function $a(){vf.call(this);this.name="ToolManager";this.Nc=new F;this.Oc=new F;this.zg=new F;this.ca=this.Ma=850;this.w=(new Zb(2,2)).ia();this.Xb=5E3;this.Na=Bf;this.L=Df;this.ir=this.l=null;this.Pj=-1}
ma($a,vf);$a.prototype.initializeStandardTools=function(){};$a.prototype.updateAdornments=function(a){var b=this.currentToolTip;if(b instanceof Cf&&this.ir===a){var c=b.adornedObject;(null!==a?c.part===a:null===c)?this.showToolTip(b,c):this.hideToolTip()}};
$a.prototype.doMouseDown=function(){var a=this.diagram,b=a.lastInput;b.isTouchEvent&&this.gestureBehavior===Ef&&(b.bubbles=!1);if(b.isMultiTouch){this.cancelWaitAfter();if(this.gestureBehavior===Ff){b.bubbles=!0;return}if(this.gestureBehavior===Ef)return;if(a.currentTool.canStartMultiTouch()){a.currentTool.standardPinchZoomStart();return}}var c=a.undoManager;E&&c.checksTransactionLevel&&0!==c.transactionLevel&&Ha("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.ib(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===Bf?this.mouseWheelBehavior=Af:this.mouseWheelBehavior===Af&&(this.mouseWheelBehavior=Bf));this.doActivate();this.standardWaitAfter(this.holdDelay,b)};
$a.prototype.doMouseMove=function(){var a=this.diagram,b=a.lastInput;if(b.isMultiTouch){if(this.gestureBehavior===Ff){b.bubbles=!0;return}if(this.gestureBehavior===Ef)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.ib(this.diagram);if(e.canStart()){a.doFocus();a.currentTool=e;a.currentTool===e&&(e.isActive||e.doActivate(),e.doMouseMove());return}}Gf(this,
a);a=b.event;null===a||"mousemove"!==a.type&&"pointermove"!==a.type&&a.cancelable||(b.bubbles=!0)};function Gf(a,b){a.standardMouseOver();a.isBeyondDragSize()&&a.standardWaitAfter(a.isActive?a.holdDelay:a.hoverDelay,b.lastInput)}$a.prototype.doCurrentObjectChanged=function(a,b){a=this.currentToolTip;null===a||null!==b&&a instanceof Cf&&(b===a||b.tg(a))||this.hideToolTip()};
$a.prototype.doWaitAfter=function(a){var b=this.diagram;b.Ea&&(this.doMouseHover(),this.isActive||this.doToolTip(),a.isTouchEvent&&!b.lastInput.handled&&(a=a.copy(),a.button=2,a.buttons=2,b.lastInput=a,b.Rl=!0,b.doMouseUp()))};
$a.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)};
$a.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 Cf)||b!==a&&!b.tg(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()};
$a.prototype.showToolTip=function(a,b){!E||a instanceof Cf||a instanceof Hf||v("showToolTip:tooltip must be an Adornment or HTMLInfo.");null!==b&&w(b,N,$a,"showToolTip:obj");var c=this.diagram;a!==this.currentToolTip&&this.hideToolTip();if(a instanceof Cf){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?a.adornedObject=b:a.data=c.model;a.bc();this.positionToolTip(a,
b)}else a instanceof Hf&&a!==this.currentToolTip&&a.show(b,c,this);this.currentToolTip=a;-1!==this.Pj&&(ra.clearTimeout(this.Pj),this.Pj=-1);a=this.toolTipDuration;if(0<a&&Infinity!==a){var e=this;this.Pj=wa(function(){e.hideToolTip()},a)}};
$a.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}};
$a.prototype.hideToolTip=function(){-1!==this.Pj&&(ra.clearTimeout(this.Pj),this.Pj=-1);var a=this.diagram,b=this.currentToolTip;null!==b&&(b instanceof Cf?(a.remove(b),null!==this.ir&&this.ir.wf(b.category),b.data=null,b.adornedObject=null):b instanceof Hf&&null!==b.hide&&b.hide(a,this),this.currentToolTip=null)};
$a.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.ib(this.diagram);if(d.canStart()){a.doFocus();a.currentTool=d;a.currentTool===d&&(d.isActive||d.doActivate(),d.doMouseUp());return}}a.doFocus();this.doDeactivate()};$a.prototype.doMouseWheel=function(){this.standardMouseWheel()};$a.prototype.doKeyDown=function(){var a=this.diagram;null!==a.commandHandler&&a.commandHandler.doKeyDown()};
$a.prototype.doKeyUp=function(){var a=this.diagram;null!==a.commandHandler&&a.commandHandler.doKeyUp()};$a.prototype.findTool=function(a){z(a,"string",$a,"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};
$a.prototype.replaceTool=function(a,b){z(a,"string",$a,"replaceTool:name");null!==b&&(w(b,vf,$a,"replaceTool:newtool"),b.ib(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.jd(d,b):this.mouseDownTools.nb(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.jd(d,b):this.mouseMoveTools.nb(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.jd(d,b):this.mouseUpTools.nb(d),e;return null};function If(a,b,c,d){z(b,"string",$a,"replaceStandardTool:name");w(d,F,$a,"replaceStandardTool:list");null!==c&&(w(c,vf,$a,"replaceStandardTool:newtool"),c.name=b,c.ib(a.diagram));a.findTool(b)?a.replaceTool(b,c):null!==c&&d.add(c)}
na.Object.defineProperties($a.prototype,{mouseWheelBehavior:{configurable:!0,get:function(){return this.Na},set:function(a){tb(a,$a,$a,"mouseWheelBehavior");this.Na=a}},gestureBehavior:{configurable:!0,get:function(){return this.L},set:function(a){tb(a,$a,$a,"gestureBehavior");this.L=a}},currentToolTip:{configurable:!0,get:function(){return this.l},set:function(a){!E||null===a||a instanceof Cf||a instanceof Hf||v("ToolManager.currentToolTip must be an Adornment or HTMLInfo.");
this.l=a;this.ir=null!==a&&a instanceof Cf?a.adornedPart:null}},mouseDownTools:{configurable:!0,get:function(){return this.Nc}},mouseMoveTools:{configurable:!0,get:function(){return this.Oc}},mouseUpTools:{configurable:!0,get:function(){return this.zg}},hoverDelay:{configurable:!0,get:function(){return this.Ma},set:function(a){z(a,"number",$a,"hoverDelay");this.Ma=a}},holdDelay:{configurable:!0,get:function(){return this.ca},set:function(a){z(a,
"number",$a,"holdDelay");this.ca=a}},dragSize:{configurable:!0,get:function(){return this.w},set:function(a){w(a,Zb,$a,"dragSize");this.w=a.J()}},toolTipDuration:{configurable:!0,get:function(){return this.Xb},set:function(a){z(a,"number",$a,"toolTipDuration");this.Xb=a}}});var Bf=new D($a,"WheelScroll",0),Af=new D($a,"WheelZoom",1),Jf=new D($a,"WheelNone",2),Df=new D($a,"GestureZoom",3),Ef=new D($a,"GestureCancel",4),Ff=new D($a,"GestureNone",5);$a.className="ToolManager";
$a.WheelScroll=Bf;$a.WheelZoom=Af;$a.WheelNone=Jf;$a.GestureZoom=Df;$a.GestureCancel=Ef;$a.GestureNone=Ff;function Kf(){vf.call(this);0<arguments.length&&Da(Kf);this.name="Dragging";this.L=this.Nc=!0;this.w=this.Na=this.ca=this.dg=null;this.Cn=this.Oc=!1;this.Ml=new J(NaN,NaN);this.Ds=new J;this.Xb=!0;this.Vk=100;this.Lg=[];this.zg=(new H).freeze();this.Ma=new Lf}ma(Kf,vf);
Kf.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.Vk)?!1:null!==this.findDraggablePart()};
Kf.prototype.findDraggablePart=function(){var a=this.diagram;a=a.em(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};
Kf.prototype.standardMouseSelect=function(){var a=this.diagram;if(a.allowSelect){var b=a.em(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,(kb?b.meta:b.control)||b.shift||Mf(a),this.currentPart.isSelected=!0,a.ba("ChangedSelection",a.selection))}}};
Kf.prototype.doActivate=function(){var a=this.diagram;null===this.currentPart&&this.standardMouseSelect();var b=this.currentPart;null!==b&&(b.canMove()||b.canCopy())&&(Nf=null,this.isActive=!0,this.Ml.set(a.position),Of(this,a.selection),this.Lg.length=0,this.draggedParts=this.computeEffectiveCollection(a.selection,this.dragOptions),a.Zi=!0,!0===a.Ge("temporaryPixelRatio")&&30<a.$w&&Yf(a),Zf(a,this.draggedParts),this.Ca("Drag"),this.startPoint=a.firstInput.documentPoint,a.isMouseCaptured=!0,a.allowDragOut&&
(this.isDragOutStarted=!0,this.Cn=!1,Nf=this,$f=this.diagram,this.doSimulatedDragOut()))};function Of(a,b){if(a.dragsLink){var c=a.diagram;c.allowRelink&&(c.model.ik()&&1===b.count&&b.first()instanceof S?(a.draggedLink=b.first(),a.draggedLink.canRelinkFrom()&&a.draggedLink.canRelinkTo()&&a.draggedLink.Xj(),a.dg=c.toolManager.findTool("Relinking"),null===a.dg&&(a.dg=new ag,a.dg.ib(c))):(a.draggedLink=null,a.dg=null))}}
Kf.prototype.computeEffectiveCollection=function(a,b){return this.diagram.commandHandler.computeEffectiveCollection(a,b)};Kf.prototype.rd=function(a){return void 0===a?new bg(gc):this.isGridSnapEnabled?new bg(new J(Math.round(a.x),Math.round(a.y))):new bg(a.copy())};
Kf.prototype.doDeactivate=function(){this.isActive=!1;var a=this.diagram;a.yf();cg(this);dg(a,this.draggedParts);this.draggedParts=this.currentPart=null;this.Cn=this.isDragOutStarted=!1;if(0<eg.count){for(var b=eg,c=b.length,d=0;d<c;d++){var e=b.O(d);fg(e);gg(e);cg(e);e.diagram.yf()}b.clear()}fg(this);this.Ml.h(NaN,NaN);Nf=$f=null;gg(this);a.isMouseCaptured=!1;a.currentCursor="";a.Zi=!1;this.yg();hg(a,!0)};
function cg(a){var b=a.diagram,c=b.skipsUndoManager;b.skipsUndoManager=!0;ig(a,b.lastInput,null);b.skipsUndoManager=c;a.Lg.length=0}function jg(){var a=Nf;gg(a);kg(a);var b=a.diagram;a.Ml.o()&&(b.position=a.Ml);b.yf()}Kf.prototype.doCancel=function(){gg(this);kg(this);var a=this.diagram;this.Ml.o()&&(a.position=this.Ml);this.stopTool()};Kf.prototype.doKeyDown=function(){this.isActive&&("Esc"===this.diagram.lastInput.key?this.doCancel():this.doMouseMove())};
Kf.prototype.doKeyUp=function(){this.isActive&&this.doMouseMove()};function lg(a,b){var c=Infinity,d=Infinity,e=-Infinity,f=-Infinity;for(a=a.iterator;a.next();){var g=a.value;if(g.dc()&&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 mg(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.xf(),c.Ca("Drag")):kg(a);c.skipsUndoManager=!b;c.partManager.addsToTemporaryLayer=!b;a.startPoint=c.firstInput.documentPoint;b=a.copiesEffectiveCollection?a.draggedParts.$d():c.selection;c=c.bk(b,c,!0);for(b=c.iterator;b.next();)b.value.location=
b.key.location;b=L.alloc();lg(c,b);L.free(b);b=new Ub;for(d=a.draggedParts.iterator;d.next();){var e=d.key;e.dc()&&e.canCopy()&&(e=c.K(e),null!==e&&(e.bc(),b.add(e,a.rd(e.location))))}for(c=c.iterator;c.next();)d=c.value,d instanceof S&&d.canCopy()&&b.add(d,a.rd());a.copiedParts=b;Of(a,b.$d());null!==a.draggedLink&&(c=a.draggedLink,b=c.routeBounds,ng(c,a.startPoint.x-(b.x+b.width/2),a.startPoint.y-(b.y+b.height/2)))}}}
function gg(a){var b=a.diagram;if(null!==a.copiedParts&&(b.wt(a.copiedParts.$d(),!1),a.copiedParts=null,null!==a.draggedParts))for(var c=a.draggedParts.iterator;c.next();)c.key instanceof S&&(c.value.point=new J(0,0));b.skipsUndoManager=!1;b.partManager.addsToTemporaryLayer=!1;a.startPoint=b.firstInput.documentPoint}
function fg(a){if(null!==a.draggedLink){if(a.dragsLink&&null!==a.dg){var b=a.dg;b.diagram.remove(b.temporaryFromNode);b.diagram.remove(b.temporaryToNode)}a.draggedLink=null;a.dg=null}}function og(a,b,c){var d=a.diagram,e=a.startPoint,f=J.alloc();f.assign(d.lastInput.documentPoint);a.moveParts(b,f.Zd(e),c);J.free(f);!0===d.Ge("temporaryPixelRatio")&&null===d.kh&&30<d.$w&&(Yf(d),d.tt())}Kf.prototype.moveParts=function(a,b,c){var d=this.diagram;null!==d&&pg(d,a,b,this.dragOptions,c)};
function kg(a){if(null!==a.draggedParts){for(var b=a.diagram,c=a.draggedParts.iterator;c.next();){var d=c.key;d.dc()&&(d.location=c.value.point)}for(c=a.draggedParts.iterator;c.next();)if(d=c.key,d instanceof S&&d.suspendsRouting){var e=c.value.point;a.draggedParts.add(d,a.rd());ng(d,-e.x,-e.y)}b.hd()}}function qg(a,b){if(null===b)return!0;b=b.part;return null===b||b instanceof Cf||b.layer.isTemporary||a.draggedParts&&a.draggedParts.contains(b)||a.copiedParts&&a.copiedParts.contains(b)?!0:!1}
function tg(a,b){var c=a.diagram;a.dragsLink&&(null!==a.draggedLink&&(a.draggedLink.fromNode=null,a.draggedLink.toNode=null),ug(a,!1));var d=vg(c,b,null,function(b){return!qg(a,b)}),e=c.lastInput;e.targetObject=d;var f=c.skipsUndoManager,g=!1;try{c.skipsUndoManager=!0;g=ig(a,e,d);if(!a.isActive&&null===Nf)return;if(null===d||c.handlesDragDropForTopLevelParts){var h=c.mouseDragOver;null!==h&&(h(e),g=!0)}if(!a.isActive&&null===Nf)return;a.doDragOver(b,d);if(!a.isActive&&null===Nf)return}finally{c.skipsUndoManager=
f,g&&c.hd()}c.isReadOnly||!c.allowMove&&!c.allowCopy||!c.allowHorizontalScroll&&!c.allowVerticalScroll||c.Ts(e.viewPoint)}
function ig(a,b,c){var d=!1,e=a.Lg.length,f=0<e?a.Lg[0]:null;if(c===f)return!1;b.handled=!1;for(var g=0;g<e;g++){var h=a.Lg[g],k=h.mouseDragLeave;if(null!==k&&(k(b,h,c),d=!0,b.handled))break}a.Lg.length=0;if(!a.isActive&&null===Nf||null===c)return d;b.handled=!1;for(e=c;null!==e;)a.Lg.push(e),e=wg(e);e=a.Lg.length;for(c=0;c<e&&(g=a.Lg[c],h=g.mouseDragEnter,null===h||(h(b,g,f),d=!0,!b.handled));c++);return d}
function wg(a){var b=a.panel;return null!==b?b:a instanceof T&&!(a instanceof xg)&&(a=a.containingGroup,null!==a&&a.handlesDragDropForMembers)?a:null}function yg(a,b,c){var d=a.dg;if(null===d)return null;var e=a.diagram.qg(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(qd,a);k=b.Ee(k);k<f&&(g=h,f=k)}}J.free(a);return g}
function ug(a,b){var c=a.draggedLink;if(null!==c&&!(2>c.pointsCount)){var d=a.diagram;if(!d.isReadOnly){var e=a.dg;if(null!==e){var f=null,g=null;null===c.fromNode&&(f=yg(a,c.i(0),!1),null!==f&&(g=f.part));var h=null,k=null;null===c.toNode&&(h=yg(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.Ax&&d.ba("LinkRelinked",c,d.Ax),c.toPort!==d.Bx&&d.ba("LinkRelinked",c,d.Bx)):zg(e,g,f,k,h):zg(e,null,null,null,null)}}}}Kf.prototype.doDragOver=function(){};
function Ag(a,b){var c=a.diagram;a.dragsLink&&ug(a,!0);cg(a);var d=vg(c,b,null,function(b){return!qg(a,b)}),e=c.lastInput;e.targetObject=d;if(null!==d){e.handled=!1;for(var f=d;null!==f;){var g=f.mouseDrop;if(null!==g&&(g(e,f),e.handled))break;Bg(a,e,f);f=wg(f)}}else f=c.mouseDrop,null!==f&&f(e);if(a.isActive||null!==Nf){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!==
Nf){b=L.alloc();for(d=c.selection.iterator;d.next();)e=d.value,e instanceof V&&Cg(a,c,e,b);L.free(b)}}}function Bg(a,b,c){a=a.diagram;c instanceof T&&null===c.containingGroup&&!(c instanceof xg)&&a.handlesDragDropForTopLevelParts&&(c=a.mouseDrop,null!==c&&c(b))}
function Cg(a,b,c,d){var e=!1;c.getAvoidableRect(d);b.viewportBounds.pf(d)&&(e=!0);b=b.links;for(a=a.copiedParts||a.draggedParts;b.next();){var f=b.value;if(!e||Dg(f))a.contains(f)&&a.contains(c)||!f.Xd(c)&&f.isAvoiding&&Lc(f.actualBounds,d,0)&&f.Ta()}}Kf.prototype.doDropOnto=function(){};
Kf.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",mg(this,!1),Zf(a,this.copiedParts),og(this,this.copiedParts,!1),dg(a,this.copiedParts)):this.mayMove()?(gg(this),og(this,this.draggedParts,!0)):this.mayDragOut()?(a.currentCursor="no-drop",mg(this,!1),og(this,this.copiedParts,!1)):gg(this),tg(this,a.lastInput.documentPoint))}};
Kf.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?(gg(this),mg(this,!0),Zf(a,this.copiedParts),og(this,this.copiedParts,!1),dg(a,this.copiedParts),null!==this.copiedParts&&a.Nv(this.copiedParts.$d())):(c=!0,gg(this),this.mayMove()&&(og(this,this.draggedParts,!0),tg(this,a.lastInput.documentPoint)));this.Cn=!0;Ag(this,a.lastInput.documentPoint);
if(this.isActive){var d=b?this.copiedParts.$d():this.draggedParts.$d();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();dg(a,this.draggedParts);this.transactionResult=b?"Copy":"Move";a.ba(b?"SelectionCopied":"SelectionMoved",d)}this.stopTool()}}};
Kf.prototype.simulatedMouseMove=function(a,b,c){if(null===Nf)return!1;var d=Nf.diagram;c instanceof P||(c=null);var e=$f;c!==e&&(null!==e&&e!==d&&(e.yf(),Nf.isDragOutStarted=!1,e=e.toolManager.findTool("Dragging"),null!==e&&e.doSimulatedDragLeave()),$f=c,null!==c&&c!==d&&(jg(),e=c.toolManager.findTool("Dragging"),null!==e&&(eg.contains(e)||eg.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?(void 0!==a.targetTouches&&(0<a.targetTouches.length?a=a.targetTouches[0]:0<a.changedTouches.length&&(a=a.changedTouches[0])),b=c.getMouse(a)):null===b&&(b=new J),c.lastInput.documentPoint=b,c.lastInput.viewPoint=c.Ct(b),c.lastInput.down=!1,c.lastInput.up=!1,d.doSimulatedDragOver());return!0};
Kf.prototype.simulatedMouseUp=function(a,b,c,d){if(null===Nf)return!1;null===d&&(d=b);b=$f;var e=Nf.diagram;if(d!==b){var f=b.toolManager.findTool("Dragging");if(null!==b&&b!==e&&null!==f)return b.yf(),Nf.isDragOutStarted=!1,f.doSimulatedDragLeave(),!1;$f=d;b=d.toolManager.findTool("Dragging");null!==d&&null!==b&&(jg(),eg.contains(b)||eg.add(b),b.doSimulatedDragEnter())}return null===d?(Nf.doCancel(),!0):d!==this.diagram?(null!==a?(void 0!==a.targetTouches&&(0<a.targetTouches.length?a=a.targetTouches[0]:
0<a.changedTouches.length&&(a=a.changedTouches[0])),c=d.getMouse(a)):null===c&&(c=new J),d.lastInput.documentPoint=c,d.lastInput.viewPoint=d.Ct(c),d.lastInput.down=!1,d.lastInput.up=!0,a=d.toolManager.findTool("Dragging"),null!==a&&a.doSimulatedDrop(),a=Nf,null!==a&&(d=a.mayCopy(),a.transactionResult=d?"Copy":"Move",a.stopTool()),!0):!1};
Kf.prototype.mayCopy=function(){if(!this.isCopyEnabled)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowCopy||(kb?!a.lastInput.alt:!a.lastInput.control))return!1;for(a=a.selection.iterator;a.next();){var b=a.value;if(b.dc()&&b.canCopy())return!0}return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canCopy()?!0:!1};
Kf.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.dc()&&b.canCopy())return!0}return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canCopy()?!0:!1};
Kf.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.dc()&&b.canMove())return!0}return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canMove()?!0:!1};Kf.prototype.computeBorder=function(a,b,c){return this.Cn||null===this.draggedParts||this.draggedParts.contains(a)?null:c.assign(b)};Kf.prototype.jz=function(){return Nf};
Kf.prototype.mayDragIn=function(){var a=this.diagram;if(!a.allowDrop||a.isReadOnly||a.isModelReadOnly||!a.allowInsert)return!1;var b=Nf;return null===b||b.diagram.model.dataFormat!==a.model.dataFormat?!1:!0};Kf.prototype.doSimulatedDragEnter=function(){if(this.mayDragIn()){var a=this.diagram;a.animationManager.xd();Eg(a);a.animationManager.xd();a=Nf;null!==a&&(a.diagram.currentCursor="copy",a.diagram.Zi=!1)}};Kf.prototype.doSimulatedDragLeave=function(){var a=Nf;null!==a&&a.doSimulatedDragOut();this.doCancel()};
Kf.prototype.doSimulatedDragOver=function(){var a=this.diagram,b=Nf;null!==b&&null!==b.draggedParts&&this.mayDragIn()&&(a.currentCursor="copy",Fg(this,b.draggedParts.$d(),!1,a.firstInput),og(this,this.copiedParts,!1),tg(this,a.lastInput.documentPoint))};
Kf.prototype.doSimulatedDrop=function(){var a=this.diagram,b=Nf;if(null!==b){var c=b.diagram;b.Cn=!0;gg(this);this.mayDragIn()&&(this.Ca("Drop"),Fg(this,b.draggedParts.$d(),!0,a.lastInput),og(this,this.copiedParts,!1),null!==this.copiedParts&&a.Nv(this.copiedParts.$d()),Ag(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.yg())}};
function Fg(a,b,c,d){if(null===a.copiedParts){var e=a.diagram;if(!e.isReadOnly&&!e.isModelReadOnly){e.skipsUndoManager=!c;e.partManager.addsToTemporaryLayer=!c;a.startPoint=d.documentPoint;c=e.bk(b,e,!0);var f=L.alloc();lg(b,f);d=f.x+f.width/2;e=f.y+f.height/2;L.free(f);f=a.Ds;var g=new Ub,h=J.alloc();for(b=b.iterator;b.next();){var k=b.value,l=c.K(k);k.dc()&&k.canCopy()?(k=k.location,h.h(f.x-(d-k.x),f.y-(e-k.y)),l.location=h,l.bc(),g.add(l,a.rd(h))):l instanceof S&&k.canCopy()&&(ng(l,f.x-d,f.y-e),
g.add(l,a.rd()))}J.free(h);a.copiedParts=g;Of(a,g.$d());null!==a.draggedLink&&(c=a.draggedLink,d=c.routeBounds,ng(c,a.startPoint.x-(d.x+d.width/2),a.startPoint.y-(d.y+d.height/2)))}}}Kf.prototype.doSimulatedDragOut=function(){var a=this.diagram;a.Zi=!1;this.mayCopy()||this.mayMove()?a.currentCursor="":a.currentCursor="no-drop"};Kf.prototype.computeMove=function(a,b,c,d){c=this.diagram;return null!==c?c.computeMove(a,b,this.dragOptions,d):new J};
na.Object.defineProperties(Kf.prototype,{isCopyEnabled:{configurable:!0,get:function(){return this.Nc},set:function(a){z(a,"boolean",Kf,"isCopyEnabled");this.Nc=a}},copiesEffectiveCollection:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"boolean",Kf,"copiesEffectiveCollection");this.L=a}},dragOptions:{configurable:!0,get:function(){return this.Ma},set:function(a){w(a,Lf,Kf,"dragOptions");this.Ma=a}},isGridSnapEnabled:{configurable:!0,
enumerable:!0,get:function(){return this.dragOptions.isGridSnapEnabled},set:function(a){z(a,"boolean",Kf,"isGridSnapEnabled");this.dragOptions.isGridSnapEnabled=a}},isComplexRoutingRealtime:{configurable:!0,get:function(){return this.Xb},set:function(a){z(a,"boolean",Kf,"isComplexRoutingRealtime");this.Xb=a}},isGridSnapRealtime:{configurable:!0,get:function(){return this.dragOptions.isGridSnapRealtime},set:function(a){z(a,"boolean",Kf,"isGridSnapRealtime");this.dragOptions.isGridSnapRealtime=
a}},gridSnapCellSize:{configurable:!0,get:function(){return this.dragOptions.gridSnapCellSize},set:function(a){w(a,Zb,Kf,"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,Kf,"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,Kf,"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",Kf,"dragsLink");this.dragOptions.dragsLink=a}},dragsTree:{configurable:!0,get:function(){return this.dragOptions.dragsTree},set:function(a){z(a,
"boolean",Kf,"dragsTree");this.dragOptions.dragsTree=a}},currentPart:{configurable:!0,get:function(){return this.ca},set:function(a){null!==a&&w(a,T,Kf,"currentPart");this.ca=a}},copiedParts:{configurable:!0,get:function(){return this.w},set:function(a){this.w=a}},draggedParts:{configurable:!0,get:function(){return this.Na},set:function(a){this.Na=a}},draggingParts:{configurable:!0,get:function(){return null!==this.copiedParts?this.copiedParts.$d():
null!==this.draggedParts?this.draggedParts.$d():this.zg}},draggedLink:{configurable:!0,get:function(){return this.diagram.draggedLink},set:function(a){null!==a&&w(a,S,Kf,"draggedLink");this.diagram.draggedLink=a}},isDragOutStarted:{configurable:!0,get:function(){return this.Oc},set:function(a){this.Oc=a}},startPoint:{configurable:!0,get:function(){return this.Ds},set:function(a){w(a,J,Kf,"startPoint");this.Ds.A(a)||this.Ds.assign(a)}},delay:{configurable:!0,
enumerable:!0,get:function(){return this.Vk},set:function(a){z(a,"number",Kf,"delay");this.Vk=a}}});Kf.prototype.getDraggingSource=Kf.prototype.jz;var eg=null,Nf=null,$f=null;Kf.className="DraggingTool";eg=new F;Za("draggingTool",function(){return this.findTool("Dragging")},function(a){If(this,"Dragging",a,this.mouseMoveTools)});$a.prototype.doCancel=function(){null!==Nf&&Nf.doCancel();vf.prototype.doCancel.call(this)};
function Gg(){0<arguments.length&&Da(Gg);vf.call(this);this.zg=100;this.ca=!1;var a=new S,b=new Hg;b.isPanelMain=!0;b.stroke="blue";a.add(b);b=new Hg;b.toArrow="Standard";b.fill="blue";b.stroke="blue";a.add(b);a.layerName="Tool";this.Lm=a;a=new V;b=new Hg;b.portId="";b.figure="Rectangle";b.fill=null;b.stroke="magenta";b.strokeWidth=2;b.desiredSize=sc;a.add(b);a.selectable=!1;a.layerName="Tool";this.Jm=a;this.Km=b;a=new V;b=new Hg;b.portId="";b.figure="Rectangle";b.fill=null;b.stroke="magenta";b.strokeWidth=
2;b.desiredSize=sc;a.add(b);a.selectable=!1;a.layerName="Tool";this.Gq=a;this.Hq=b;this.Oc=this.Nc=this.Na=this.Ma=this.Xb=null;this.L=!0;this.Wx=new Ub;this.Hm=this.li=this.Im=null}ma(Gg,vf);Gg.prototype.doStop=function(){this.diagram.yf();this.originalToPort=this.originalToNode=this.originalFromPort=this.originalFromNode=this.originalLink=null;this.validPortsCache.clear();this.targetPort=null};
Gg.prototype.copyPortProperties=function(a,b,c,d,e){if(null!==a&&null!==b&&null!==c&&null!==d){var f=b.Fe(),g=Zb.alloc();g.width=b.naturalBounds.width*f;g.height=b.naturalBounds.height*f;d.desiredSize=g;Zb.free(g);e?(d.toSpot=b.toSpot,d.toEndSegmentLength=b.toEndSegmentLength):(d.fromSpot=b.fromSpot,d.fromEndSegmentLength=b.fromEndSegmentLength);c.locationSpot=qd;f=J.alloc();c.location=b.oa(qd,f);J.free(f);d.angle=b.Oi();null!==this.portTargeted&&this.portTargeted(a,b,c,d,e)}};
Gg.prototype.setNoTargetPortProperties=function(a,b,c){null!==b&&(b.desiredSize=sc,b.fromSpot=ed,b.toSpot=ed);null!==a&&(a.location=this.diagram.lastInput.documentPoint);null!==this.portTargeted&&this.portTargeted(null,null,a,b,c)};Gg.prototype.doMouseDown=function(){this.isActive&&this.doMouseMove()};
Gg.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.Ts(a.lastInput.viewPoint)}};Gg.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};
Gg.prototype.findTargetPort=function(a){var b=this.diagram,c=b.lastInput.documentPoint,d=this.portGravity;0>=d&&(d=.1);var e=this,f=b.qg(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(qd,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};
Gg.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.aq(b).count>=c)return!1}return!0};
Gg.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.ud(b).count>=c)return!1}return!0};
Gg.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};Gg.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.ud(b);b.next();)if(d=b.value,d.fromNode===c&&d.fromPortId===a)return!0;return!1};
Gg.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};Gg.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 Ig(this,c,b,d)};
function Ig(a,b,c,d){if(b===c)return!0;var e=b.fromNode;if(null!==e&&e.isLinkLabel&&(d.add(e),Ig(a,e.labeledLink,c,d)))return!0;b=b.toNode;return null!==b&&b.isLinkLabel&&(d.add(b),Ig(a,b.labeledLink,c,d))?!0:!1}
Gg.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!==Jg){if(d===Kg){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!Lg(this,a,b,c,!0)}if(d===Mg){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!Lg(this,a,b,c,!0)}if(d===Ng)return a===b?a=!0:(d=new H,d.add(b),a=Og(this,d,a,b,c)),!a;if(d===Pg)return!Lg(this,a,b,c,!1);if(d===Qg)return a===b?a=!0:(d=new H,d.add(b),a=Rg(this,d,a,b,c)),!a}return!0};function Lg(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&&Lg(a,g,c,d,e)))return!0}return!1}
function Og(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&&Og(a,b,g,d,e)))return!0}return!1}function Rg(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&&Rg(a,b,h,d,e))return!0}}return!1}
na.Object.defineProperties(Gg.prototype,{portGravity:{configurable:!0,get:function(){return this.zg},set:function(a){z(a,"number",Gg,"portGravity");0<=a&&(this.zg=a)}},isUnconnectedLinkValid:{configurable:!0,get:function(){return this.ca},set:function(a){z(a,"boolean",Gg,"isUnconnectedLinkValid");this.ca=a}},temporaryLink:{configurable:!0,get:function(){return this.Lm},set:function(a){w(a,S,Gg,"temporaryLink");this.Lm=a}},temporaryFromNode:{configurable:!0,
enumerable:!0,get:function(){return this.Jm},set:function(a){w(a,V,Gg,"temporaryFromNode");this.Jm=a}},temporaryFromPort:{configurable:!0,get:function(){return this.Km},set:function(a){w(a,N,Gg,"temporaryFromPort");this.Km=a}},temporaryToNode:{configurable:!0,get:function(){return this.Gq},set:function(a){w(a,V,Gg,"temporaryToNode");this.Gq=a}},temporaryToPort:{configurable:!0,get:function(){return this.Hq},set:function(a){w(a,N,Gg,"temporaryToPort");this.Hq=
a}},originalLink:{configurable:!0,get:function(){return this.Xb},set:function(a){null!==a&&w(a,S,Gg,"originalLink");this.Xb=a}},originalFromNode:{configurable:!0,get:function(){return this.Ma},set:function(a){null!==a&&w(a,V,Gg,"originalFromNode");this.Ma=a}},originalFromPort:{configurable:!0,get:function(){return this.Na},set:function(a){null!==a&&w(a,N,Gg,"originalFromPort");this.Na=a}},originalToNode:{configurable:!0,get:function(){return this.Nc},
set:function(a){null!==a&&w(a,V,Gg,"originalToNode");this.Nc=a}},originalToPort:{configurable:!0,get:function(){return this.Oc},set:function(a){null!==a&&w(a,N,Gg,"originalToPort");this.Oc=a}},isForwards:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"boolean",Gg,"isForwards");this.L=a}},validPortsCache:{configurable:!0,get:function(){return this.Wx}},targetPort:{configurable:!0,get:function(){return this.Im},set:function(a){null!==
a&&w(a,N,Gg,"targetPort");this.Im=a}},linkValidation:{configurable:!0,get:function(){return this.li},set:function(a){null!==a&&z(a,"function",Gg,"linkValidation");this.li=a}},portTargeted:{configurable:!0,get:function(){return this.Hm},set:function(a){null!==a&&z(a,"function",Gg,"portTargeted");this.Hm=a}}});Gg.className="LinkingBaseTool";function Sg(){0<arguments.length&&Da(Sg);Gg.call(this);this.name="Linking";this.w={};this.l=null;this.M=Tg;this.Fh=null}ma(Sg,Gg);
Sg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowLink||!a.model.jt()||!a.lastInput.left||a.currentTool!==this&&!this.isBeyondDragSize()?!1:null!==this.findLinkablePort()};
Sg.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===Tg||a===Ug){var c=this.findValidLinkablePort(b,!1);if(null!==c)return this.isForwards=!0,c}if(a===Tg||a===$g)if(b=this.findValidLinkablePort(b,!0),null!==b)return this.isForwards=!1,b;return null};
Sg.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.Ta(),a.add(this.temporaryLink)),this.isActive=!0)};Sg.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.yg()};Sg.prototype.doStop=function(){Gg.prototype.doStop.call(this);this.startObject=null};
Sg.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.Ru(),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()};Sg.prototype.isNewTreeLink=function(){var a=this.archetypeLinkData;if(null===a)return!0;if(a instanceof S)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};Sg.prototype.insertLink=function(a,b,c,d){return this.diagram.partManager.insertLink(a,b,c,d)};Sg.prototype.doNoLink=function(){};
na.Object.defineProperties(Sg.prototype,{archetypeLinkData:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&z(a,"object",Sg,"archetypeLinkData");a instanceof N&&w(a,S,Sg,"archetypeLinkData");this.w=a}},archetypeLabelNodeData:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&z(a,"object",Sg,"archetypeLabelNodeData");a instanceof N&&w(a,V,Sg,"archetypeLabelNodeData");this.l=a}},direction:{configurable:!0,get:function(){return this.M},
set:function(a){tb(a,Sg,Sg,"direction");this.M=a}},startObject:{configurable:!0,get:function(){return this.Fh},set:function(a){null!==a&&w(a,N,Sg,"startObject");this.Fh=a}}});var Tg=new D(Sg,"Either",0),Ug=new D(Sg,"ForwardsOnly",0),$g=new D(Sg,"BackwardsOnly",0);Sg.className="LinkingTool";Sg.Either=Tg;Sg.ForwardsOnly=Ug;Sg.BackwardsOnly=$g;
function ag(){0<arguments.length&&Da(ag);Gg.call(this);this.name="Relinking";var a=new Hg;a.figure="Diamond";a.desiredSize=uc;a.fill="lightblue";a.stroke="dodgerblue";a.cursor="pointer";a.segmentIndex=0;this.w=a;a=new Hg;a.figure="Diamond";a.desiredSize=uc;a.fill="lightblue";a.stroke="dodgerblue";a.cursor="pointer";a.segmentIndex=-1;this.Fh=a;this.l=null;this.Mw=new L}ma(ag,Gg);
ag.prototype.updateAdornments=function(a){if(null!==a&&a instanceof S){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.uf()&&(c=a.ek(b),null===c&&(c=this.makeAdornment(d,!1),a.rh(b,c)))}null===c&&a.wf(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.uf()&&
(c=a.ek(b),null===c?(c=this.makeAdornment(d,!0),a.rh(b,c)):c.v()));null===c&&a.wf(b)}};ag.prototype.makeAdornment=function(a,b){var c=new Cf;c.type=W.Link;b=b?this.toHandleArchetype:this.fromHandleArchetype;null!==b&&c.add(b.copy());c.adornedObject=a;return c};
ag.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowRelink||!a.model.jt()||!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};
ag.prototype.doActivate=function(){var a=this.diagram;if(null===this.originalLink){var b=this.handle;null===b&&(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 Cf&&c.adornedPart instanceof S))return;this.handle=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.Mw.set(this.originalLink.actualBounds);null!==this.originalLink&&0<this.originalLink.pointsCount&&(null===this.originalLink.fromNode&&(null!==this.temporaryFromPort&&(this.temporaryFromPort.desiredSize=rc),null!==this.temporaryFromNode&&(this.temporaryFromNode.location=this.originalLink.i(0))),null===this.originalLink.toNode&&
(null!==this.temporaryToPort&&(this.temporaryToPort.desiredSize=rc),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.Ta(),a.add(this.temporaryLink));this.isActive=!0};
ag.prototype.copyLinkProperties=function(a,b){if(null!==a&&null!==b){b.adjusting=a.adjusting;b.corner=a.corner;var c=a.curve;if(c===ah||c===bh)c=ch;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}};
ag.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.yg()};ag.prototype.doStop=function(){Gg.prototype.doStop.call(this);this.handle=null};
ag.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.Ta()),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.jq(this.Mw)}this.stopTool()};
ag.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};ag.prototype.doNoRelink=function(){};
function zg(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(ag.prototype,{fromHandleArchetype:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,ag,"fromHandleArchetype");this.w=a}},toHandleArchetype:{configurable:!0,get:function(){return this.Fh},set:function(a){null!==a&&w(a,N,ag,"toHandleArchetype");this.Fh=a}},handle:{configurable:!0,get:function(){return this.l},set:function(a){if(null!==a&&(w(a,N,ag,"handle"),!(a.part instanceof Cf)))throw Error("new handle is not in an Adornment: "+
a);this.l=a}}});ag.className="RelinkingTool";Za("linkingTool",function(){return this.findTool("Linking")},function(a){If(this,"Linking",a,this.mouseMoveTools)});Za("relinkingTool",function(){return this.findTool("Relinking")},function(a){If(this,"Relinking",a,this.mouseDownTools)});
function dh(){0<arguments.length&&Da(dh);vf.call(this);this.name="LinkReshaping";var a=new Hg;a.figure="Rectangle";a.desiredSize=tc;a.fill="lightblue";a.stroke="dodgerblue";this.w=a;a=new Hg;a.figure="Diamond";a.desiredSize=uc;a.fill="lightblue";a.stroke="dodgerblue";a.cursor="move";this.L=a;this.ca=3;this.Mt=this.l=null;this.zl=new J;this.ls=new F}ma(dh,vf);dh.prototype.lv=function(a){return a&&a.qs&&0!==a.qs.value?a.qs:eh};
dh.prototype.Cm=function(a,b){w(a,N,dh,"setReshapingBehavior:obj");tb(b,dh,dh,"setReshapingBehavior:behavior");a.qs=b};
dh.prototype.updateAdornments=function(a){if(null!==a&&a instanceof S){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.uf()&&(b=a.ek(this.name),null===b||b.Jw!==a.pointsCount||b.Uw!==a.resegmentable)&&(b=this.makeAdornment(c),null!==b&&(b.Jw=a.pointsCount,b.Uw=a.resegmentable,a.rh(this.name,b)))}null===b&&a.wf(this.name)}};
dh.prototype.makeAdornment=function(a){var b=a.part,c=b.pointsCount,d=b.isOrthogonal,e=null;if(null!==b.points&&1<c){e=new Cf;e.type=W.Link;c=b.firstPickIndex;var f=b.lastPickIndex,g=d?1:0;if(b.resegmentable&&b.computeCurve()!==fh)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.Cm(h,gh),h.cursor="n-resize"):K.B(k.y,l.y)&&(this.Cm(h,hh),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.Cm(h,gh),h.cursor="n-resize"):K.B(k.y,l.y)&&(this.Cm(h,hh),h.cursor="w-resize")):g!==f&&(this.Cm(h,ih),h.cursor="move");e.add(h)}e.adornedObject=a}return e};dh.prototype.makeHandle=function(){var a=this.handleArchetype;return null===a?null:a.copy()};
dh.prototype.makeResegmentHandle=function(){var a=this.midHandleArchetype;return null===a?null:a.copy()};dh.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};
dh.prototype.doActivate=function(){var a=this.diagram;null===this.handle&&(this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name));if(null!==this.handle){var b=this.handle.part.adornedPart;if(b instanceof S){this.Mt=b;a.isMouseCaptured=!0;this.Ca(this.name);if(b.resegmentable&&999===this.handle.fromMaxLinks){var c=b.points.copy(),d=this.getResegmentingPoint();c.Lb(this.handle.segmentIndex+1,d);b.isOrthogonal&&c.Lb(this.handle.segmentIndex+1,d);b.points=c;b.Mb();b.updateAdornments();
this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name);if(null===this.handle){this.doDeactivate();return}}this.zl=b.i(this.handle.segmentIndex);this.ls=b.points.copy();this.isActive=!0}}};dh.prototype.doDeactivate=function(){this.yg();this.Mt=this.handle=null;this.isActive=this.diagram.isMouseCaptured=!1};dh.prototype.doCancel=function(){var a=this.adornedLink;null!==a&&(a.points=this.ls);this.stopTool()};dh.prototype.getResegmentingPoint=function(){return this.handle.oa(qd)};
dh.prototype.doMouseMove=function(){var a=this.diagram;this.isActive&&(a=this.computeReshape(a.lastInput.documentPoint),this.reshape(a))};
dh.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&&(jh(this,g,d,e,f,!0)||jh(this,g,d,e,f,!1))){var h=b.points.copy();jh(this,g,d,
e,f,!0)?(h.jd(c-2,new J(g.x,(f.y+g.y)/2)),h.jd(c+1,new J(f.x,(f.y+g.y)/2))):(h.jd(c-2,new J((f.x+g.x)/2,g.y)),h.jd(c+1,new J((f.x+g.x)/2,f.y)));h.nb(c);h.nb(c-1);b.points=h;b.Mb()}else g=b.i(c+2),Math.abs(e.x-f.x)<this.resegmentingDistance&&Math.abs(e.y-f.y)<this.resegmentingDistance&&(jh(this,d,e,f,g,!0)||jh(this,d,e,f,g,!1))&&(h=b.points.copy(),jh(this,d,e,f,g,!0)?(h.jd(c-1,new J(d.x,(d.y+g.y)/2)),h.jd(c+2,new J(g.x,(d.y+g.y)/2))):(h.jd(c-1,new J((d.x+g.x)/2,d.y)),h.jd(c+2,new J((d.x+g.x)/2,g.y))),
h.nb(c+1),h.nb(c),b.points=h,b.Mb())}}else g=J.alloc(),K.Wi(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.nb(c),b.points=d,b.Mb()),J.free(g)}a.Ya();this.transactionResult=this.name;a.ba("LinkReshaped",this.adornedLink,this.ls)}this.stopTool()};
function jh(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}
dh.prototype.reshape=function(a){var b=this.adornedLink;b.Eh();var c=this.handle.segmentIndex,d=this.lv(this.handle);if(b.isOrthogonal)if(c===b.firstPickIndex+1)c=b.firstPickIndex+1,d===gh?(b.N(c,b.i(c-1).x,a.y),b.N(c+1,b.i(c+2).x,a.y)):d===hh&&(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===gh?(b.N(c-1,b.i(c-2).x,a.y),b.N(c,b.i(c+1).x,a.y)):d===hh&&(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).Nb()&&(f=e.oa(qd,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).Nb()&&(c=e.oa(qd,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.nf()};dh.prototype.computeReshape=function(a){var b=this.adornedLink,c=this.handle.segmentIndex;switch(this.lv(this.handle)){case ih:return a;case gh:return new J(b.i(c).x,a.y);case hh:return new J(a.x,b.i(c).y);default:case eh:return b.i(c)}};
na.Object.defineProperties(dh.prototype,{handleArchetype:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,dh,"handleArchetype");this.w=a}},midHandleArchetype:{configurable:!0,get:function(){return this.L},set:function(a){null!==a&&w(a,N,dh,"midHandleArchetype");this.L=a}},handle:{configurable:!0,get:function(){return this.l},set:function(a){if(null!==a&&(w(a,N,dh,"handle"),!(a.part instanceof Cf)))throw Error("new handle is not in an Adornment: "+
a);this.l=a}},adornedLink:{configurable:!0,get:function(){return this.Mt}},resegmentingDistance:{configurable:!0,get:function(){return this.ca},set:function(a){z(a,"number",dh,"resegmentingDistance");this.ca=a}},originalPoint:{configurable:!0,get:function(){return this.zl}},originalPoints:{configurable:!0,get:function(){return this.ls}}});dh.prototype.setReshapingBehavior=dh.prototype.Cm;dh.prototype.getReshapingBehavior=dh.prototype.lv;
var eh=new D(dh,"None",0),hh=new D(dh,"Horizontal",1),gh=new D(dh,"Vertical",2),ih=new D(dh,"All",3);dh.className="LinkReshapingTool";dh.None=eh;dh.Horizontal=hh;dh.Vertical=gh;dh.All=ih;Za("linkReshapingTool",function(){return this.findTool("LinkReshaping")},function(a){If(this,"LinkReshaping",a,this.mouseDownTools)});
function kh(){0<arguments.length&&Da(kh);vf.call(this);this.name="Resizing";this.Sf=(new Zb(1,1)).freeze();this.Rf=(new Zb(9999,9999)).freeze();this.Fg=(new Zb(NaN,NaN)).freeze();this.L=!1;this.ce=null;var a=new Hg;a.alignmentFocus=qd;a.figure="Rectangle";a.desiredSize=tc;a.fill="lightblue";a.stroke="dodgerblue";a.strokeWidth=1;a.cursor="pointer";this.w=a;this.l=null;this.zl=new J;this.Lw=new Zb;this.Po=new J;this.cu=new Zb(0,0);this.bu=new Zb(Infinity,Infinity);this.au=new Zb(1,1);this.Iw=!0}
ma(kh,vf);kh.prototype.updateAdornments=function(a){if(!(null===a||a instanceof S)){if(a.isSelected&&!this.diagram.isReadOnly){var b=a.resizeObject,c=a.ek(this.name);if(null!==b&&a.canResize()&&a.actualBounds.o()&&a.isVisible()&&b.actualBounds.o()&&b.uf()){if(null===c||c.adornedObject!==b)c=this.makeAdornment(b);if(null!==c){b=b.Oi();Dg(a)&&this.updateResizeHandles(c,b);a.rh(this.name,c);return}}}a.wf(this.name)}};
kh.prototype.makeAdornment=function(a){var b=a.part.resizeAdornmentTemplate;if(null===b){b=new Cf;b.type=W.Spot;b.locationSpot=qd;var c=new lh;c.isPanelMain=!0;b.add(c);b.add(this.makeHandle(a,fd));b.add(this.makeHandle(a,hd));b.add(this.makeHandle(a,ud));b.add(this.makeHandle(a,sd));b.add(this.makeHandle(a,Vd));b.add(this.makeHandle(a,Xd));b.add(this.makeHandle(a,de));b.add(this.makeHandle(a,Wd))}else if(mh(b),b=b.copy(),null===b)return null;b.adornedObject=a;return b};
kh.prototype.makeHandle=function(a,b){a=this.handleArchetype;if(null===a)return null;a=a.copy();a.alignment=b;return a};
kh.prototype.updateResizeHandles=function(a,b){if(null!==a)if(!a.alignment.Cb()&&("pointer"===a.cursor||0<a.cursor.indexOf("resize")))a:{var c=a.alignment;c.Nb()&&(c=qd);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)};kh.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};
kh.prototype.doActivate=function(){var a=this.diagram;null===this.handle&&(this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name));null!==this.handle&&(this.adornedObject=this.handle.part.adornedObject,null!==this.adornedObject&&(this.zl.set(this.adornedObject.oa(this.handle.alignment.yv())),this.Po.set(this.adornedObject.part.location),this.Lw.set(this.adornedObject.desiredSize),this.au=this.computeCellSize(),this.cu=this.computeMinSize(),this.bu=this.computeMaxSize(),a.isMouseCaptured=
!0,this.Iw=a.animationManager.isEnabled,a.animationManager.isEnabled=!1,this.Ca(this.name),this.isActive=!0))};kh.prototype.doDeactivate=function(){var a=this.diagram;this.yg();this.ce=this.handle=null;this.isActive=a.isMouseCaptured=!1;a.animationManager.isEnabled=this.Iw};kh.prototype.doCancel=function(){null!==this.adornedObject&&(this.adornedObject.desiredSize=this.originalDesiredSize,this.adornedObject.part.location=this.originalLocation);this.stopTool()};
kh.prototype.doMouseMove=function(){var a=this.diagram;if(this.isActive){var b=this.cu,c=this.bu,d=this.au,e=this.adornedObject.at(a.lastInput.documentPoint,J.alloc()),f=this.computeReshape();b=this.computeResize(e,this.handle.alignment,b,c,d,f);this.resize(b);a.hd();J.free(e)}};
kh.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){var b=this.cu,c=this.bu,d=this.au,e=this.adornedObject.at(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()};
kh.prototype.resize=function(a){var b=this.diagram,c=this.adornedObject,d=c.part;c.desiredSize=a.size;d.bc();a=this.adornedObject.oa(this.handle.alignment.yv());d instanceof xg?(c=new F,c.add(d),b.moveParts(c,this.zl.copy().Zd(a),!0)):d.location=d.location.copy().Zd(a).add(this.zl)};
kh.prototype.computeResize=function(a,b,c,d,e,f){b.Nb()&&(b=qd);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.bq(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};kh.prototype.computeReshape=function(){var a=nh;this.adornedObject instanceof Hg&&(a=oh(this.adornedObject));return!(a===ph||this.diagram.lastInput.shift)};
kh.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};kh.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};
kh.prototype.computeCellSize=function(){var a=new Zb(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(kh.prototype,{handleArchetype:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,kh,"handleArchetype");this.w=a}},handle:{configurable:!0,get:function(){return this.l},set:function(a){if(null!==a&&(w(a,N,kh,"handle"),!(a.part instanceof Cf)))throw Error("new handle is not in an Adornment: "+a);this.l=a}},adornedObject:{configurable:!0,get:function(){return this.ce},set:function(a){if(null!==a&&(w(a,N,
kh,"handle"),a.part instanceof Cf))throw Error("new handle must not be in an Adornment: "+a);this.ce=a}},minSize:{configurable:!0,get:function(){return this.Sf},set:function(a){w(a,Zb,kh,"minSize");if(!this.Sf.A(a)){var b=a.width;isNaN(b)&&(b=0);a=a.height;isNaN(a)&&(a=0);this.Sf.h(b,a)}}},maxSize:{configurable:!0,get:function(){return this.Rf},set:function(a){w(a,Zb,kh,"maxSize");if(!this.Rf.A(a)){var b=a.width;isNaN(b)&&(b=Infinity);a=a.height;isNaN(a)&&(a=Infinity);
this.Rf.h(b,a)}}},cellSize:{configurable:!0,get:function(){return this.Fg},set:function(a){w(a,Zb,kh,"cellSize");this.Fg.A(a)||this.Fg.assign(a)}},isGridSnapEnabled:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"boolean",kh,"isGridSnapEnabled");this.L=a}},originalDesiredSize:{configurable:!0,get:function(){return this.Lw}},originalLocation:{configurable:!0,get:function(){return this.Po}}});kh.className="ResizingTool";
Za("resizingTool",function(){return this.findTool("Resizing")},function(a){If(this,"Resizing",a,this.mouseDownTools)});function qh(){0<arguments.length&&Da(qh);vf.call(this);this.name="Rotating";this.Na=45;this.Ma=2;this.Po=new J;this.ce=null;var a=new Hg;a.figure="Ellipse";a.desiredSize=uc;a.fill="lightblue";a.stroke="dodgerblue";a.strokeWidth=1;a.cursor="pointer";this.w=a;this.l=null;this.Kw=0;this.vu=new J(NaN,NaN);this.L=0;this.ca=50}ma(qh,vf);
qh.prototype.updateAdornments=function(a){if(null!==a){if(a.Bh()){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.uf())){var c=a.ek(this.name);if(null===c||c.adornedObject!==b)c=this.makeAdornment(b);if(null!==c){c.angle=b.Oi();null===c.placeholder&&(c.location=this.computeAdornmentLocation(b));a.rh(this.name,c);return}}a.wf(this.name)}};
qh.prototype.makeAdornment=function(a){var b=a.part.rotateAdornmentTemplate;if(null===b){b=new Cf;b.type=W.Position;b.locationSpot=qd;var c=this.handleArchetype;null!==c&&b.add(c.copy())}else if(mh(b),b=b.copy(),null===b)return null;b.adornedObject=a;return b};qh.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};
qh.prototype.doActivate=function(){var a=this.diagram;if(null===this.adornedObject){null===this.handle&&(this.handle=this.findToolHandleAt(a.firstInput.documentPoint,this.name));if(null===this.handle)return;this.adornedObject=this.handle.part.adornedObject}null!==this.adornedObject&&(this.Kw=this.adornedObject.angle,this.vu=this.computeRotationPoint(this.adornedObject),this.Po=this.adornedObject.part.location.copy(),a.isMouseCaptured=!0,a.delaysLayout=!0,this.Ca(this.name),this.isActive=!0)};
qh.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(qd)};
qh.prototype.computeAdornmentLocation=function(a){var b=this.rotationPoint;b.o()||(b=this.computeRotationPoint(a));b=a.at(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)};qh.prototype.doDeactivate=function(){var a=this.diagram;this.yg();this.ce=this.handle=null;this.vu=new J(NaN,NaN);this.isActive=a.isMouseCaptured=!1};qh.prototype.doCancel=function(){this.diagram.delaysLayout=!1;this.rotate(this.originalAngle);this.stopTool()};qh.prototype.doMouseMove=function(){var a=this.diagram;this.isActive&&(a=this.computeRotate(a.lastInput.documentPoint),this.rotate(a))};
qh.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.adornedObject,this.originalAngle)}this.stopTool()};
qh.prototype.rotate=function(a){E&&B(a,qh,"rotate:newangle");var b=this.adornedObject;if(null!==b){b.angle=a;b=b.part;b.bc();var c=b.locationObject,d=b.rotateObject;if(c===d||c.tg(d))c=this.Po.copy(),b.location=c.Zd(this.rotationPoint).rotate(a-this.originalAngle).add(this.rotationPoint)}};
qh.prototype.computeRotate=function(a){a=this.rotationPoint.Xa(a)-this.handleAngle;var b=this.adornedObject.panel;null!==b&&(a-=b.Oi());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(qh.prototype,{handleArchetype:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,qh,"handleArchetype");this.w=a}},handle:{configurable:!0,get:function(){return this.l},set:function(a){if(null!==a&&(w(a,N,qh,"handle"),!(a.part instanceof Cf)))throw Error("new handle is not in an Adornment: "+a);this.l=a}},adornedObject:{configurable:!0,get:function(){return this.ce},set:function(a){if(null!==a&&(w(a,N,
qh,"handle"),a.part instanceof Cf))throw Error("new handle must not be in an Adornment: "+a);this.ce=a}},snapAngleMultiple:{configurable:!0,get:function(){return this.Na},set:function(a){z(a,"number",qh,"snapAngleMultiple");this.Na=a}},snapAngleEpsilon:{configurable:!0,get:function(){return this.Ma},set:function(a){z(a,"number",qh,"snapAngleEpsilon");this.Ma=a}},originalAngle:{configurable:!0,get:function(){return this.Kw}},rotationPoint:{configurable:!0,
enumerable:!0,get:function(){return this.vu}},handleAngle:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"number",qh,"handleAngle");this.L=a}},handleDistance:{configurable:!0,get:function(){return this.ca},set:function(a){z(a,"number",qh,"handleDistance");this.ca=a}}});qh.className="RotatingTool";Za("rotatingTool",function(){return this.findTool("Rotating")},function(a){If(this,"Rotating",a,this.mouseDownTools)});
function rh(){vf.call(this);0<arguments.length&&Da(rh);this.name="ClickSelecting"}ma(rh,vf);rh.prototype.canStart=function(){return!this.isEnabled||this.isBeyondDragSize()?!1:!0};rh.prototype.doMouseUp=function(){this.isActive&&(this.standardMouseSelect(),!this.standardMouseClick()&&this.diagram.lastInput.isTouchEvent&&this.diagram.toolManager.doToolTip());this.stopTool()};rh.className="ClickSelectingTool";function sh(){vf.call(this);0<arguments.length&&Da(sh);this.name="Action";this.Ak=null}
ma(sh,vf);sh.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.Ak=c;a.Ok=a.Tb(b.documentPoint,null,null);return!0}return!1};sh.prototype.doMouseDown=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.Ak;null!==b&&(a.targetObject=b,null!==b.actionDown&&b.actionDown(a,b))}else this.canStart()&&this.doActivate()};
sh.prototype.doMouseMove=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.Ak;null!==b&&(a.targetObject=b,null!==b.actionMove&&b.actionMove(a,b))}};sh.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.Ak;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()};
sh.prototype.doCancel=function(){var a=this.diagram.lastInput,b=this.Ak;null!==b&&(a.targetObject=b,null!==b.actionCancel&&b.actionCancel(a,b),this.stopTool())};sh.prototype.doStop=function(){this.Ak=null};sh.className="ActionTool";function th(){vf.call(this);0<arguments.length&&Da(th);this.name="ClickCreating";this.ej=null;this.w=!0;this.l=!1;this.Cw=new J(0,0)}ma(th,vf);
th.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.Cw=a.lastInput.viewPoint.copy()),2!==a.lastInput.clickCount||this.isBeyondDragSize(this.Cw))return!1}else if(1!==a.lastInput.clickCount)return!1;return a.currentTool!==this&&null!==a.em(a.lastInput.documentPoint,!0)?!1:!0};
th.prototype.doMouseUp=function(){var a=this.diagram;this.isActive&&this.insertPart(a.lastInput.documentPoint);this.stopTool()};
th.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 T?c.dc()&&(mh(c),d=c.copy(),null!==d&&b.add(d)):null!==c&&(c=b.model.copyNodeData(c),Ja(c)&&(b.model.lf(c),d=b.xc(c)));null!==d&&(c=J.allocAt(a.x,a.y),this.isGridSnapEnabled&&uh(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.yg();return d};
na.Object.defineProperties(th.prototype,{archetypeNodeData:{configurable:!0,get:function(){return this.ej},set:function(a){null!==a&&z(a,"object",th,"archetypeNodeData");this.ej=a}},isDoubleClick:{configurable:!0,get:function(){return this.w},set:function(a){z(a,"boolean",th,"isDoubleClick");this.w=a}},isGridSnapEnabled:{configurable:!0,get:function(){return this.l},set:function(a){z(a,"boolean",th,"isGridSnapEnabled");this.l=a}}});th.className="ClickCreatingTool";
function vh(){vf.call(this);0<arguments.length&&Da(vh);this.name="DragSelecting";this.Vk=175;this.w=!1;var a=new T;a.layerName="Tool";a.selectable=!1;var b=new Hg;b.name="SHAPE";b.figure="Rectangle";b.fill=null;b.stroke="magenta";a.add(b);this.l=a}ma(vh,vf);
vh.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.em(b.documentPoint,!0))?!1:!0};vh.prototype.doActivate=function(){var a=this.diagram;this.isActive=!0;a.isMouseCaptured=!0;a.skipsUndoManager=!0;a.add(this.box);this.doMouseMove()};
vh.prototype.doDeactivate=function(){var a=this.diagram;a.yf();a.remove(this.box);a.skipsUndoManager=!1;this.isActive=a.isMouseCaptured=!1};vh.prototype.doMouseMove=function(){var a=this.diagram;if(this.isActive&&null!==this.box){var b=this.computeBoxBounds(),c=this.box.bb("SHAPE");null===c&&(c=this.box.Bb());var d=Zb.alloc().h(b.width,b.height);b=J.alloc().h(b.x,b.y);c.desiredSize=d;this.box.position=b;Zb.free(d);J.free(b);(a.allowHorizontalScroll||a.allowVerticalScroll)&&a.Ts(a.lastInput.viewPoint)}};
vh.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram;a.remove(this.box);try{a.currentCursor="wait",a.ba("ChangingSelection",a.selection),this.selectInRect(this.computeBoxBounds()),a.ba("ChangedSelection",a.selection)}finally{a.currentCursor=""}}this.stopTool()};vh.prototype.computeBoxBounds=function(){var a=this.diagram;return new L(a.firstInput.documentPoint,a.lastInput.documentPoint)};
vh.prototype.selectInRect=function(a){var b=this.diagram,c=b.lastInput;a=b.ox(a,this.isPartialInclusion);if(kb?c.meta:c.control)if(c.shift)for(a=a.iterator;a.next();)b=a.value,b.isSelected&&(b.isSelected=!1);else for(a=a.iterator;a.next();)b=a.value,b.isSelected=!b.isSelected;else if(c.shift)for(a=a.iterator;a.next();)b=a.value,b.isSelected||(b.isSelected=!0);else{c=new F;for(b=b.selection.iterator;b.next();){var d=b.value;a.contains(d)||c.add(d)}for(b=c.iterator;b.next();)b.value.isSelected=!1;for(a=
a.iterator;a.next();)b=a.value,b.isSelected||(b.isSelected=!0)}};na.Object.defineProperties(vh.prototype,{delay:{configurable:!0,get:function(){return this.Vk},set:function(a){z(a,"number",vh,"delay");this.Vk=a}},isPartialInclusion:{configurable:!0,get:function(){return this.w},set:function(a){z(a,"boolean",vh,"isPartialInclusion");this.w=a}},box:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,T,vh,"box");this.l=a}}});
vh.className="DragSelectingTool";function wh(){vf.call(this);0<arguments.length&&Da(wh);this.name="Panning";this.qu=new J;this.iy=new J;this.Eg=!1;var a=this;this.Ow=function(){ra.document.removeEventListener("scroll",a.Ow,!1);a.stopTool()}}ma(wh,vf);wh.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};
wh.prototype.doActivate=function(){var a=this.diagram;this.Eg?(a.lastInput.bubbles=!0,ra.document.addEventListener("scroll",this.Ow,!1)):(a.currentCursor="move",a.isMouseCaptured=!0,this.qu.assign(a.position));this.isActive=!0};wh.prototype.doDeactivate=function(){var a=this.diagram;a.currentCursor="";this.isActive=a.isMouseCaptured=!1};wh.prototype.doCancel=function(){var a=this.diagram;a.position=this.qu;a.isMouseCaptured=!1;this.stopTool()};wh.prototype.doMouseMove=function(){this.move()};
wh.prototype.doMouseUp=function(){this.move();this.stopTool()};wh.prototype.move=function(){var a=this.diagram;if(this.isActive&&a)if(this.Eg)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(wh.prototype,{bubbles:{configurable:!0,get:function(){return this.Eg},set:function(a){z(a,"boolean",wh,"bubbles");this.Eg=a}},originalPosition:{configurable:!0,get:function(){return this.qu}}});wh.className="PanningTool";Za("clickCreatingTool",function(){return this.findTool("ClickCreating")},function(a){If(this,"ClickCreating",a,this.mouseUpTools)});
Za("clickSelectingTool",function(){return this.findTool("ClickSelecting")},function(a){If(this,"ClickSelecting",a,this.mouseUpTools)});Za("panningTool",function(){return this.findTool("Panning")},function(a){If(this,"Panning",a,this.mouseMoveTools)});Za("dragSelectingTool",function(){return this.findTool("DragSelecting")},function(a){If(this,"DragSelecting",a,this.mouseMoveTools)});Za("actionTool",function(){return this.findTool("Action")},function(a){If(this,"Action",a,this.mouseDownTools)});
function Hf(){this.ca=this.L=this.l=this.w=null}
na.Object.defineProperties(Hf.prototype,{mainElement:{configurable:!0,get:function(){return this.L},set:function(a){null!==a&&w(a,HTMLElement,Hf,"mainElement");this.L=a}},show:{configurable:!0,get:function(){return this.w},set:function(a){this.w!==a&&(null!==a&&z(a,"function",Hf,"show"),this.w=a)}},hide:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(null!==a&&z(a,"function",Hf,"hide"),this.l=a)}},valueFunction:{configurable:!0,
enumerable:!0,get:function(){return this.ca},set:function(a){this.ca=a}}});Hf.className="HTMLInfo";function xh(a,b,c){this.text=a;this.ex=b;this.visible=c}xh.className="ContextMenuButtonInfo";function yh(){vf.call(this);0<arguments.length&&Da(yh);this.name="ContextMenu";this.w=this.St=this.l=null;this.Hw=new J;this.Tt=null;var a=this;this.Fu=function(){a.stopTool()}}ma(yh,vf);
function zh(a){var b=new Hf;b.show=function(a,b,c){c.showDefaultContextMenu()};b.hide=function(a,b){b.hideDefaultContextMenu()};Ah=b;a.Fu=function(){a.stopTool()};b=ya("div");var c=ya("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=ya("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",Bh,!1);b.addEventListener("selectstart",Bh,!1);c.addEventListener("contextmenu",
Bh,!1);b.className="goCXforeground";c.className="goCXbackground";ra.document.body&&(ra.document.body.appendChild(b),ra.document.body.appendChild(c));Ch=b;Dh=c;Eh=!0}function Bh(a){a.preventDefault();return!1}yh.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return this.isBeyondDragSize()||!a.lastInput.right?!1:a.lastInput.isTouchEvent&&null!==this.defaultTouchContextMenu||null!==this.findObjectWithContextMenu()?!0:!1};yh.prototype.doStart=function(){this.Hw.set(this.diagram.firstInput.documentPoint)};
yh.prototype.doStop=function(){this.hideContextMenu();this.currentObject=null};yh.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(b.lastInput.isTouchEvent&&this.defaultTouchContextMenu)return d.part}else if(null!==b.contextMenu)return b;return null};
yh.prototype.doActivate=function(){};yh.prototype.doMouseDown=function(){vf.prototype.doMouseDown.call(this);if(this.isActive&&this.currentContextMenu instanceof Cf){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.canStart()&&(a.doActivate(),a.doMouseDown(),a.doDeactivate())}this.diagram.toolManager.mouseDownTools.contains(this)&&Fh(this)};
yh.prototype.doMouseUp=function(){if(this.isActive&&this.currentContextMenu instanceof Cf){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.canStart()&&(a.doActivate(),a.doCancel(),a.doDeactivate())}Fh(this)};
function Fh(a){var b=a.diagram;if(a.isActive){var c=a.currentContextMenu;if(null!==c){if(!(c instanceof Hf)){var d=b.Tb(b.lastInput.documentPoint,null,null);null!==d&&d.tg(c)&&a.standardMouseClick(null,null)}a.stopTool();a.canStart()&&(b.currentTool=a,a.doMouseUp())}}else a.canStart()&&(Gh(a,!0),a.isActive||a.stopTool())}
function Gh(a,b,c){void 0===c&&(c=null);b&&a.standardMouseSelect();if(!a.standardMouseClick())if(a.isActive=!0,b=Ah,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)}yh.prototype.doMouseMove=function(){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.doMouseMove();this.isActive&&this.diagram.toolManager.doMouseMove()};
yh.prototype.showContextMenu=function(a,b){!E||a instanceof Cf||a instanceof Hf||v("showContextMenu:contextMenu must be an Adornment or HTMLInfo.");null!==b&&w(b,N,yh,"showContextMenu:obj");var c=this.diagram;a!==this.currentContextMenu&&this.hideContextMenu();if(a instanceof Cf){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?a.adornedObject=b:a.data=c.model;
a.bc();this.positionContextMenu(a,b)}else a instanceof Hf&&a.show(b,c,this);this.currentContextMenu=a};yh.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}};
yh.prototype.hideContextMenu=function(){var a=this.diagram,b=this.currentContextMenu;null!==b&&(b instanceof Cf?(a.remove(b),null!==this.St&&this.St.wf(b.category),b.data=null,b.adornedObject=null):b instanceof Hf&&(null!==b.hide?b.hide(a,this):null!==b.mainElement&&(b.mainElement.style.display="none")),this.currentContextMenu=null,this.standardMouseOver())};
function Hh(){var a=new F;a.add(new xh("Copy",function(a){a.commandHandler.copySelection()},function(a){return a.commandHandler.canCopySelection()}));a.add(new xh("Cut",function(a){a.commandHandler.cutSelection()},function(a){return a.commandHandler.canCutSelection()}));a.add(new xh("Delete",function(a){a.commandHandler.deleteSelection()},function(a){return a.commandHandler.canDeleteSelection()}));a.add(new xh("Paste",function(a){a.commandHandler.pasteSelection(a.lastInput.documentPoint)},function(a){return a.commandHandler.canPasteSelection()}));
a.add(new xh("Select All",function(a){a.commandHandler.selectAll()},function(a){return a.commandHandler.canSelectAll()}));a.add(new xh("Undo",function(a){a.commandHandler.undo()},function(a){return a.commandHandler.canUndo()}));a.add(new xh("Redo",function(a){a.commandHandler.redo()},function(a){return a.commandHandler.canRedo()}));a.add(new xh("Scroll To Part",function(a){a.commandHandler.scrollToPart()},function(a){return a.commandHandler.canScrollToPart()}));a.add(new xh("Zoom To Fit",function(a){a.commandHandler.zoomToFit()},
function(a){return a.commandHandler.canZoomToFit()}));a.add(new xh("Reset Zoom",function(a){a.commandHandler.resetZoom()},function(a){return a.commandHandler.canResetZoom()}));a.add(new xh("Group Selection",function(a){a.commandHandler.groupSelection()},function(a){return a.commandHandler.canGroupSelection()}));a.add(new xh("Ungroup Selection",function(a){a.commandHandler.ungroupSelection()},function(a){return a.commandHandler.canUngroupSelection()}));a.add(new xh("Edit Text",function(a){a.commandHandler.editTextBlock()},
function(a){return a.commandHandler.canEditTextBlock()}));return a}
yh.prototype.showDefaultContextMenu=function(){var a=this.diagram;null===this.Tt&&(this.Tt=Hh());Ch.innerHTML="";Dh.addEventListener("click",this.Fu,!1);var b=this,c=ya("ul");c.className="goCXul";Ch.appendChild(c);c.innerHTML="";for(var d=this.Tt.iterator;d.next();){var e=d.value,f=e.visible;if("function"===typeof e.ex&&("function"!==typeof f||f(a))){f=ya("li");f.className="goCXli";var g=ya("a");g.className="goCXa";g.href="#";g.Yx=e.ex;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)}}Ch.style.display="block";Dh.style.display="block"};yh.prototype.hideDefaultContextMenu=function(){null!==this.currentContextMenu&&this.currentContextMenu===Ah&&(Ch.style.display="none",Dh.style.display="none",Dh.removeEventListener("click",this.Fu,!1),this.currentContextMenu=null)};
na.Object.defineProperties(yh.prototype,{currentContextMenu:{configurable:!0,get:function(){return this.l},set:function(a){!E||null===a||a instanceof Cf||a instanceof Hf||v("ContextMenuTool.currentContextMenu must be an Adornment or HTMLInfo.");this.l=a;this.St=a instanceof Cf?a.adornedPart:null}},defaultTouchContextMenu:{configurable:!0,get:function(){!1===Eh&&null===Ah&&Ih&&zh(this);return Ah},set:function(a){!E||null===a||a instanceof Cf||a instanceof Hf||v("ContextMenuTool.defaultTouchContextMenu must be an Adornment or HTMLInfo.");
null===a&&(Eh=!0);Ah=a}},currentObject:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,yh,"currentObject");this.w=a}},mouseDownPoint:{configurable:!0,get:function(){return this.Hw}}});var Ah=null,Eh=!1,Dh=null,Ch=null;yh.className="ContextMenuTool";Za("contextMenuTool",function(){return this.findTool("ContextMenu")},function(a){If(this,"ContextMenu",a,this.mouseUpTools)});
function Jh(){0<arguments.length&&Da(Jh);vf.call(this);this.name="TextEditing";this.lh=new Kh;this.Na=null;this.Ma=Lh;this.zi=null;this.na=Mh;this.L=1;this.ca=!0;this.w=null;this.l=new Hf;this.Ut=null;Nh(this,this.l)}ma(Jh,vf);
function Nh(a,b){if(Ih){var c=ya("textarea");a.Ut=c;c.addEventListener("input",function(){if(null!==a.textBlock){var b=a.zx(this.value);this.style.width=20+b.measuredBounds.width*this.fA+"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(Oh)):9===c?(a.acceptText(Ph),b.preventDefault()):27===c&&(a.doCancel(),null!==a.diagram&&a.diagram.doFocus())}},!1);c.addEventListener("focus",
function(){if(null!==a.currentTextEditor&&a.state!==Mh){var b=a.Ut;a.na===Qh&&(a.na=Rh);"function"===typeof b.select&&a.selectsTextOnActivate&&(b.select(),b.setSelectionRange(0,9999))}},!1);c.addEventListener("blur",function(){if(null!==a.currentTextEditor&&a.state!==Mh){var b=a.Ut;"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 Kh&&f instanceof Jh)if(f.state===Sh)c.style.border="3px solid red",c.focus();else{var d=a.oa(qd),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.lineCount;c.fA=l;c.className="goTXarea";b.div.appendChild(c);c.focus();f.selectsTextOnActivate&&(c.select(),c.setSelectionRange(0,9999))}};b.hide=function(a){a.div.removeChild(c)}}}
Jh.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 Kh&&b.editable&&b.part.canEdit()))return!1;b=b.part;return null===b||this.starting===Lh&&!b.isSelected||this.starting===Th&&2>a.lastInput.clickCount?!1:!0};Jh.prototype.doStart=function(){this.isActive||null===this.textBlock||this.doActivate()};
Jh.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 Kh&&(this.textBlock=b,null!==b.part)){this.isActive=!0;this.na=Qh;var c=this.defaultTextEditor;null!==b.textEditor&&(c=b.textEditor);this.lh=this.textBlock.copy();var d=new L(this.textBlock.oa(fd),this.textBlock.oa(ud));a.Mv(d);c.show(b,a,this);this.currentTextEditor=c}}}};Jh.prototype.doCancel=function(){this.stopTool()};
Jh.prototype.doMouseUp=function(){!this.isActive&&this.canStart()&&this.doActivate()};Jh.prototype.doMouseDown=function(){this.isActive&&this.acceptText(Uh)};
Jh.prototype.acceptText=function(a){switch(a){case Uh:if(this.na===Vh)this.currentTextEditor instanceof HTMLElement&&this.currentTextEditor.focus();else if(this.na===Qh||this.na===Sh||this.na===Rh)this.na=Wh,Xh(this);break;case Yh:case Oh:case Ph:if(Oh!==a||!0!==this.textBlock.isMultiline)if(this.na===Qh||this.na===Sh||this.na===Rh)this.na=Wh,Xh(this)}};
function Xh(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=Vh,a.transactionResult=a.name,b.text=f,null!==b.textEdited&&b.textEdited(b,e,f),null!==c&&c.ba("TextEdited",b,e),a.yg(),a.stopTool(),null!==c&&c.doFocus()):(a.na=Sh,null!==b.errorFunction&&b.errorFunction(a,e,f),d.show(b,c,a))}}
Jh.prototype.doDeactivate=function(){var a=this.diagram;null!==a&&(this.na=Mh,this.textBlock=null,null!==this.currentTextEditor&&this.currentTextEditor.hide(a,this),this.isActive=!1)};Jh.prototype.isValidText=function(a,b,c){w(a,Kh,Jh,"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};Jh.prototype.zx=function(a){var b=this.lh;b.text=a;b.measure(this.textBlock.ol,Infinity);return b};
na.Object.defineProperties(Jh.prototype,{textBlock:{configurable:!0,get:function(){return this.Na},set:function(a){null!==a&&w(a,Kh,Jh,"textBlock");this.Na=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 Hf||v("TextEditingTool.defaultTextEditor must be an HTMLInfo.");this.l=a}},starting:{configurable:!0,
get:function(){return this.Ma},set:function(a){tb(a,Jh,Jh,"starting");this.Ma=a}},textValidation:{configurable:!0,get:function(){return this.zi},set:function(a){null!==a&&z(a,"function",Jh,"textValidation");this.zi=a}},minimumEditorScale:{configurable:!0,get:function(){return this.L},set:function(a){null!==a&&z(a,"number",Jh,"minimumEditorScale");this.L=a}},selectsTextOnActivate:{configurable:!0,get:function(){return this.ca},set:function(a){null!==a&&z(a,
"boolean",Jh,"selectsTextOnActivate");this.ca=a}},state:{configurable:!0,get:function(){return this.na},set:function(a){this.na!==a&&(tb(a,Jh,Jh,"starting"),this.na=a)}}});Jh.prototype.measureTemporaryTextBlock=Jh.prototype.zx;
var Yh=new D(Jh,"LostFocus",0),Uh=new D(Jh,"MouseDown",1),Ph=new D(Jh,"Tab",2),Oh=new D(Jh,"Enter",3),ai=new D(Jh,"SingleClick",0),Lh=new D(Jh,"SingleClickSelected",1),Th=new D(Jh,"DoubleClick",2),Mh=new D(Jh,"StateNone",0),Qh=new D(Jh,"StateActive",1),Rh=new D(Jh,"StateEditing",2),Wh=new D(Jh,"StateValidating",3),Sh=new D(Jh,"StateInvalid",4),Vh=new D(Jh,"StateValidated",5);Jh.className="TextEditingTool";Jh.LostFocus=Yh;Jh.MouseDown=Uh;Jh.Tab=Ph;Jh.Enter=Oh;Jh.SingleClick=ai;
Jh.SingleClickSelected=Lh;Jh.DoubleClick=Th;Jh.StateNone=Mh;Jh.StateActive=Qh;Jh.StateEditing=Rh;Jh.StateValidating=Wh;Jh.StateInvalid=Sh;Jh.StateValidated=Vh;Za("textEditingTool",function(){return this.findTool("TextEditing")},function(a){If(this,"TextEditing",a,this.mouseUpTools)});
function bi(){ci||(di(),ci=!0);this.uw=ei;this.D=yf;this.vn=this.wn=null;this.dj=this.xn=this.yn=0;this.Fk=this.pi=this.sb=this.Nr=this.Nf=!1;this.Tg=this.Fc=!0;this.fr=this.er=this.tw=null;this.sw=0;this.hr=new Ub;this.$t=600;this.$x=new J(0,0);this.qw=this.pw=this.Rw=!1;this.Cg=new H;this.Cj=new Ub;this.hs=new H;this.gr=null}bi.prototype.ib=function(a){this.D=a};function ei(a,b,c,d){a/=d/2;return 1>a?c/2*a*a+b:-c/2*(--a*(a-2)-1)+b}
function fi(a,b,c,d){return a===d?b+c:c*(-Math.pow(2,-10*a/d)+1)+b}bi.prototype.canStart=function(){return!0};t=bi.prototype;t.Dh=function(a,b){this.Fc&&(void 0!==b&&(this.gr=b),this.Tg||this.D.Ui)&&(this.Cg.add(a),this.canStart(a)&&(this.Nf&&this.xd(),this.pi=this.sb=!0))};t.Rz=function(a,b){this.Fc&&(void 0!==b&&(this.gr=b),this.Tg||this.D.Ui)&&(this.Cg.add(a),this.canStart(a)&&(this.Nf&&this.xd(),this.sb=!0))};
function gi(a){if(a.Fc&&(a.Cg.clear(),a.sb))if(!a.Fk)a.sb=!1,a.pi=!1;else if(0===a.dj){var b=+new Date;a.dj=b;ra.requestAnimationFrame(function(){if(!1!==a.sb&&!a.Nf&&a.dj===b){var c=a.D;c.Ge("temporaryPixelRatio")&&Yf(c);hi(c);a.sb=!1;a.pi=!1;c.ba("AnimationStarting");ii(a,b)}})}}
t.th=function(a,b,c,d,e,f){if(!(!this.sb||(E&&w(a,N,bi,"addToAnimation:obj"),"position"===b&&c.A(d))||a instanceof T&&!a.isAnimated)){var g=this.Cj;if(g.contains(a)){var h=g.K(a);g=h.start;var k=h.end;void 0===g[b]&&(g[b]=ji(c));k[b]=ji(d)}else h={},k={},h[b]=ji(c),k[b]=ji(d),d=h.position,d instanceof J&&!d.o()&&this.Cg.contains("Expand SubGraph")&&d.assign(k.position),h=new ki(h,k,e),g.add(a,h);e&&0===b.indexOf("position:")&&a instanceof T?h.bv.location=ji(a.location):e&&(h.bv[b]=ji(c));f&&(h.ut=
!0);this.Fk=!0}};function ji(a){return a instanceof J?a.copy():a instanceof Zb?a.copy():a}function li(a,b){if(!a.Nf)return!1;a=a.Cj.K(b);return null!==a&&a.ut}
function ii(a,b){function c(){if(!1!==e.Nf&&e.dj===b){var a=+new Date,f=a>r?l:a-q;mi(e);ni(e,d,p,g,f,l);e.er&&e.er();Eg(d);oi(e);a>r?pi(e):ra.requestAnimationFrame(c)}}var d=a.D;if(null!==d){var e=a,f=a.gr||{},g=f.Py||a.uw,h=f.sA||null,k=f.tA||null,l=f.duration||a.$t,m=a.$x;for(f=a.Cj.iterator;f.next();){var n=f.value.start.position;n instanceof J&&(n.o()||n.assign(m))}a.tw=g;a.er=h;a.fr=k;a.sw=l;a.hr=a.Cj;var p=a.hr;for(f=p.iterator;f.next();)h=f.value.end,h["position:placeholder"]&&(k=f.key.findVisibleNode(),
k instanceof xg&&null!==k.placeholder&&(m=k.placeholder,k=m.oa(fd),m=m.padding,k.x+=m.left,k.y+=m.top,h["position:placeholder"]=k));a.Nf=!0;mi(a);ni(a,d,p,g,0,l);Eg(a.D,!0);oi(a);var q=+new Date,r=q+l;e.dj===b&&ra.requestAnimationFrame(function(){c()})}}function mi(a){if(!a.Nr){var b=a.D;a.Rw=b.skipsUndoManager;a.pw=b.skipsModelSourceBindings;a.qw=b.Zi;b.skipsUndoManager=!0;b.skipsModelSourceBindings=!0;b.Zi=!0;a.Nr=!0}}
function oi(a){var b=a.D;b.skipsUndoManager=a.Rw;b.skipsModelSourceBindings=a.pw;b.Zi=a.qw;a.Nr=!1}function ni(a,b,c,d,e,f){for(c=c.iterator;c.next();){var g=c.key,h=c.value,k=h.start,l=h.end,m=qi;for(n in l)"position"===n&&(l["position:placeholder"]||l["position:node"])||null===m.get(n)||m.get(n)(g,k[n],l[n],d,e,f,h)}d=b.rv;b.rv=!0;var n=a.uw;0!==a.yn&&0!==a.xn&&(c=a.yn,b.Da=n(e,c,a.xn-c,f));null!==a.wn&&null!==a.vn&&(c=a.wn,a=a.vn,b.ua=new J(n(e,c.x,a.x-c.x,f),n(e,c.y,a.y-c.y,f)));b.rv=d}
t.xd=function(){!0===this.sb&&(this.pi=this.sb=!1,this.dj=0,this.Fk&&this.D.ec());this.Nf&&this.Fc&&pi(this)};
function pi(a){a.Nf=!1;a.Fk=!1;mi(a);for(var b=a.D,c=a.tw,d=a.sw,e=a.hr,f=a.hs.iterator;f.next();)f.value.v();e=e.iterator;for(f=qi;e.next();){var g=e.key,h=e.value,k=h.start,l=h.end,m=h.bv,n;for(n in l)if(null!==f.get(n)){var p=n;!h.Vu||"position:node"!==p&&"position:placeholder"!==p||(p="position");f.get(p)(g,k[n],void 0!==m[n]?m[n]:h.Vu?k[n]:l[n],c,d,d)}h.Vu&&void 0!==m.location&&g instanceof T&&(g.location=m.location);h.ut&&g instanceof T&&g.Ob(!1)}for(c=a.D.links;c.next();)d=c.value,null!==d.dh&&
(d.points=d.dh,d.dh=null);b.lt.clear();hg(b,!1);b.Ya();b.S();b.hd();ri(b);oi(a);a.fr&&a.fr();a.dj=0;a.hr.clear();a.fr=null;a.er=null;a.wn=null;a.vn=null;a.yn=0;a.xn=0;a.Cj.clear();0<a.hs.count&&a.hs.clear();a.gr=null;b.ba("AnimationFinished");b.ec()}
t.Rp=function(a,b){if(this.pi&&(this.Cg.contains("Expand Tree")||this.Cg.contains("Expand SubGraph"))){var c=b.actualBounds,d=null;b instanceof xg&&(d=b.placeholder);null!==d?(c=d.oa(fd),d=d.padding,c.x+=d.left,c.y+=d.top,this.th(a,"position",c,a.position,!1)):this.th(a,"position",new J(c.x+c.width/2,c.y+c.height/2),a.position,!1);this.th(a,"scale",.01,a.scale,!1);if(a instanceof xg)for(a=a.memberParts;a.next();)d=a.value,d instanceof V&&this.Rp(d,b)}};
t.Qp=function(a,b){if(a.isVisible()&&this.pi&&(this.Cg.contains("Collapse Tree")||this.Cg.contains("Collapse SubGraph"))){var c=null;b instanceof xg&&(c=b.placeholder);null!==c?this.th(a,"position:placeholder",a.position,c,!0):this.th(a,"position:node",a.position,b,!0);this.th(a,"scale",a.scale,.01,!0);this.sb&&(c=this.Cj,c.contains(a)&&(c.K(a).ut=!0));if(a instanceof xg)for(a=a.memberParts;a.next();)c=a.value,c instanceof V&&this.Qp(c,b)}};
function si(a,b,c){a.sb&&!b.A(c)&&(null===a.wn&&b.o()&&null===a.vn&&(a.wn=b.copy()),a.vn=c.copy(),a.Fk=!0)}function ti(a,b,c){a.sb&&a.D.Ui&&(0===a.yn&&0===a.xn&&(a.yn=b),a.xn=c,a.Fk=!0)}
function di(){var a=new Ub;a.add("position",function(a,c,d,e,f,g){f!==g?a.Bt(e(f,c.x,d.x-c.x,g),e(f,c.y,d.y-c.y,g)):a.position=new J(e(f,c.x,d.x-c.x,g),e(f,c.y,d.y-c.y,g))});a.add("position:placeholder",function(a,c,d,e,f,g){f!==g?a.Bt(e(f,c.x,d.x-c.x,g),e(f,c.y,d.y-c.y,g)):a.position=new J(e(f,c.x,d.x-c.x,g),e(f,c.y,d.y-c.y,g))});a.add("position:node",function(a,c,d,e,f,g){var b=a.actualBounds,k=d.actualBounds;d=k.x+k.width/2-b.width/2;b=k.y+k.height/2-b.height/2;f!==g?a.Bt(e(f,c.x,d-c.x,g),e(f,
c.y,b-c.y,g)):a.position=new J(e(f,c.x,d-c.x,g),e(f,c.y,b-c.y,g))});a.add("opacity",function(a,c,d,e,f,g){a.opacity=e(f,c,d-c,g)});a.add("scale",function(a,c,d,e,f,g){a.scale=e(f,c,d-c,g)});a.add("angle",function(a,c,d,e,f,g){a.angle=e(f,c,d-c,g)});a.add("visible",function(a,c,d,e,f,g){a.visible=f!==g?c:d});qi=a}
na.Object.defineProperties(bi.prototype,{animationReasons:{configurable:!0,get:function(){return this.Cg}},isEnabled:{configurable:!0,get:function(){return this.Fc},set:function(a){z(a,"boolean",bi,"isEnabled");this.Fc=a}},duration:{configurable:!0,get:function(){return this.$t},set:function(a){z(a,"number",bi,"duration");1>a&&Ca(a,">= 1",bi,"duration");this.$t=a}},isAnimating:{configurable:!0,get:function(){return this.Nf}},isTicking:{configurable:!0,
enumerable:!0,get:function(){return this.Nr}},isInitial:{configurable:!0,get:function(){return this.Tg},set:function(a){z(a,"boolean",bi,"isInitial");this.Tg=a}}});bi.prototype.stopAnimation=bi.prototype.xd;bi.prototype.addToAnimation=bi.prototype.th;bi.prototype.prepareAnimation=bi.prototype.Rz;bi.prototype.prepareAutomaticAnimation=bi.prototype.Dh;var qi=null,ci=!1;bi.className="AnimationManager";function ki(a,b,c){this.start=a;this.end=b;this.bv={};this.Vu=c;this.ut=!1}
ki.className="AnimationStates";function ui(){0<arguments.length&&Da(ui);qb(this);this.D=null;this.Ga=new F;this.Wa="";this.mb=1;this.w=!1;this.Gj=this.L=this.Qh=this.Ph=this.Oh=this.Nh=this.Lh=this.Mh=this.Kh=this.Sh=this.Jh=this.Rh=this.Ih=this.Hh=!0;this.l=!1;this.Qo=[]}t=ui.prototype;t.ib=function(a){this.D=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 xg?e++:k instanceof V?d++:k instanceof S?f++:k instanceof Cf?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&&Jb(d)&&(h+=" #"+Jb(d)),c instanceof V?h+=" "+
Wa(d):c instanceof S&&(h+=" "+Wa(c.fromNode)+" "+Wa(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.Gj)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.ea(a)&&(d=!0);for(var e=J.alloc(),f=this.Ga.j,g=f.length;g--;){var h=f[g];if((!0!==d||!1!==Dg(h))&&h.isVisible()&&(e.assign(a),ac(e,h.td),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.Ki=function(a,b,c,d){void 0===b&&(b=null);void 0===c&&(c=null);d instanceof F||d instanceof H||(d=new H);if(!1===this.Gj)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.ea(a)&&(e=!0);for(var f=J.alloc(),g=this.Ga.j,h=g.length;h--;){var k=g[h];if((!0!==e||!1!==Dg(k))&&k.isVisible()){f.assign(a);ac(f,k.td);var l=k;k.Ki(f,b,c,d)&&(null!==b&&(l=b(l)),null===l||null!==c&&!c(l)||d.add(l))}}J.free(f);return d};
t.pg=function(a,b,c,d,e){void 0===b&&(b=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof F||e instanceof H||(e=new H);if(!1===this.Gj)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.pf(a)&&(f=!0);for(var g=this.Ga.j,h=g.length;h--;){var k=g[h];if((!0!==f||!1!==Dg(k))&&k.isVisible()){var l=k;k.pg(a,b,c,d,e)&&(null!==b&&(l=b(l)),null===l||null!==c&&!c(l)||e.add(l))}}return e};
t.qg=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 F||e instanceof H)f=e;e=!0}f instanceof F||f instanceof H||(f=new H);if(!1===this.Gj)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.ea(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!==Dg(n))&&n.isVisible()){h.assign(a);ac(h,n.td);
k.h(a.x+b,a.y);ac(k,n.td);var p=n;n.qg(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.kd=function(a,b){if(this.visible){var c=void 0===b?a.viewportBounds:b;var d=this.Ga.j,e=d.length;a=Qa();b=Qa();for(var f=0;f<e;f++){var g=d[f];g.Gw=f;g instanceof S&&!1===g.Mc||g instanceof Cf&&null!==g.adornedPart||(Lc(g.actualBounds,c,10)?(g.kd(!0),a.push(g)):(g.kd(!1),null!==g.adornments&&0<g.adornments.count&&b.push(g)))}for(c=0;c<a.length;c++)for(d=a[c],vi(d),d=d.adornments;d.next();)e=d.value,e.measure(Infinity,Infinity),e.arrange(),e.kd(!0);for(c=0;c<b.length;c++)d=b[c],d.updateAdornments(),
wi(d,!0);Ta(a);Ta(b)}};t.jc=function(a,b,c){if(this.visible&&0!==this.mb&&(void 0===c&&(c=!0),c||!this.isTemporary)){c=this.Ga.j;var d=c.length;if(0!==d){1!==this.mb&&(a.globalAlpha=this.mb);var e=this.Qo;e.length=0;for(var f=b.scale,g=0;g<d;g++){var h=c[g];if(Dg(h)){if(h instanceof S&&(h.isOrthogonal&&e.push(h),!1===h.Mc))continue;var k=h.actualBounds;k.width*f>b.qe||k.height*f>b.qe?h.jc(a,b):xi(a,h)}}a.globalAlpha=1}}};
function xi(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&&(yi(b,a,b.areaBackground,!0,!0,d,c),a.fillRect(c.x,c.y,c.width,c.height));null===b.areaBackground&&null===b.background&&(yi(b,a,"rgba(0,0,0,0.3)",!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),yi(b,a,b.background,!0,!1,d,c),a.fillRect(0,0,d.width/2,d.height/2),
e.it()||(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.cb(of,a,this,b,c,d,e)};t.Si=function(a,b,c){var d=this.Ga;b.ii=this;if(a>=d.count)a=d.count;else if(d.O(a)===b)return-1;d.Lb(a,b);b.hq(c);d=this.diagram;null!==d&&(c?d.S():d.Si(b));zi(this,a,b);return a};
t.zc=function(a,b,c){if(!c&&b.layer!==this&&null!==b.layer)return b.layer.zc(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.iq(c);d.nb(a);d=this.diagram;null!==d&&(c?d.S():d.zc(b));b.ii=null;return a};
function zi(a,b,c){b=Ai(a,b,c);if(c instanceof xg&&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.nb(b),e.Lb(d,c))}c=c.containingGroup;null!==c&&zi(a,-1,c)}}
function Ai(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.nb(b);a.Lb(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.nb(b);a.Lb(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.Oa(),b=a.length,c=0;c<b;c++)a[c].kd(!1),this.zc(-1,a[c],!1);this.Qo.length=0};
na.Object.defineProperties(ui.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.D}},name:{configurable:!0,get:function(){return this.Wa},set:function(a){z(a,"string",ui,"name");var b=this.Wa;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.Wa=a;this.g("name",b,a);for(a=this.Ga.iterator;a.next();)a.value.layerName=this.Wa}}},opacity:{configurable:!0,get:function(){return this.mb},set:function(a){var b=this.mb;b!==a&&(z(a,"number",ui,"opacity"),(0>a||1<a)&&Ca(a,"0 <= value <= 1",ui,"opacity"),this.mb=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",ui,"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",ui,"visible");this.L=a;this.g("visible",b,a);for(b=this.Ga.iterator;b.next();)b.value.Ob(a);a=this.diagram;null!==a&&a.S()}}},pickable:{configurable:!0,get:function(){return this.Gj},set:function(a){var b=this.Gj;b!==a&&(z(a,"boolean",ui,"pickable"),this.Gj=
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.Hh},set:function(a){var b=this.Hh;b!==a&&(z(a,"boolean",ui,"allowCopy"),this.Hh=a,this.g("allowCopy",b,a))}},allowDelete:{configurable:!0,get:function(){return this.Ih},set:function(a){var b=this.Ih;b!==a&&(z(a,"boolean",ui,"allowDelete"),
this.Ih=a,this.g("allowDelete",b,a))}},allowTextEdit:{configurable:!0,get:function(){return this.Rh},set:function(a){var b=this.Rh;b!==a&&(z(a,"boolean",ui,"allowTextEdit"),this.Rh=a,this.g("allowTextEdit",b,a))}},allowGroup:{configurable:!0,get:function(){return this.Jh},set:function(a){var b=this.Jh;b!==a&&(z(a,"boolean",ui,"allowGroup"),this.Jh=a,this.g("allowGroup",b,a))}},allowUngroup:{configurable:!0,get:function(){return this.Sh},set:function(a){var b=
this.Sh;b!==a&&(z(a,"boolean",ui,"allowUngroup"),this.Sh=a,this.g("allowUngroup",b,a))}},allowLink:{configurable:!0,get:function(){return this.Kh},set:function(a){var b=this.Kh;b!==a&&(z(a,"boolean",ui,"allowLink"),this.Kh=a,this.g("allowLink",b,a))}},allowRelink:{configurable:!0,get:function(){return this.Mh},set:function(a){var b=this.Mh;b!==a&&(z(a,"boolean",ui,"allowRelink"),this.Mh=a,this.g("allowRelink",b,a))}},allowMove:{configurable:!0,get:function(){return this.Lh},
set:function(a){var b=this.Lh;b!==a&&(z(a,"boolean",ui,"allowMove"),this.Lh=a,this.g("allowMove",b,a))}},allowReshape:{configurable:!0,get:function(){return this.Nh},set:function(a){var b=this.Nh;b!==a&&(z(a,"boolean",ui,"allowReshape"),this.Nh=a,this.g("allowReshape",b,a))}},allowResize:{configurable:!0,get:function(){return this.Oh},set:function(a){var b=this.Oh;b!==a&&(z(a,"boolean",ui,"allowResize"),this.Oh=a,this.g("allowResize",b,a))}},allowRotate:{configurable:!0,
enumerable:!0,get:function(){return this.Ph},set:function(a){var b=this.Ph;b!==a&&(z(a,"boolean",ui,"allowRotate"),this.Ph=a,this.g("allowRotate",b,a))}},allowSelect:{configurable:!0,get:function(){return this.Qh},set:function(a){var b=this.Qh;b!==a&&(z(a,"boolean",ui,"allowSelect"),this.Qh=a,this.g("allowSelect",b,a))}}});ui.prototype.findObjectsNear=ui.prototype.qg;ui.prototype.findObjectsIn=ui.prototype.pg;ui.prototype.findObjectsAt=ui.prototype.Ki;ui.prototype.findObjectAt=ui.prototype.Tb;
ui.className="Layer";
function P(a){function b(){c.removeEventListener(ra.document,"DOMContentLoaded",b,!1);c.setRTL()}1<arguments.length&&v("Diagram constructor can only take one optional argument, the DIV HTML element or its id.");Bi||(Ci(),Bi=!0);qb(this);yf=this;bb=[];this.pb=!0;this.Ek=new bi;this.Ek.ib(this);this.Jb=17;this.Xn=!1;this.wu="default";this.Ja=null;var c=this;Ih&&(null!==ra.document.body?this.setRTL():c.addEventListener(ra.document,"DOMContentLoaded",b,!1));this.Ra=new F;this.ya=this.Aa=0;this.Ea=null;
this.uu=new Ub;this.eg=this.$c=null;this.Kv();this.il=null;this.Jv();this.ua=(new J(NaN,NaN)).freeze();this.kr=this.Da=1;this.Er=(new J(NaN,NaN)).freeze();this.Fr=NaN;this.Zr=1E-4;this.Xr=100;this.ub=new $b;this.Os=(new J(NaN,NaN)).freeze();this.vr=(new L(NaN,NaN,NaN,NaN)).freeze();this.vi=(new Hc(0,0,0,0)).freeze();this.Lj=Di;this.ys=!1;this.ts=this.ps=null;this.fj=Ei;this.hj=Qd;this.di=Ei;this.Sn=Qd;this.Gr=this.Dr=fd;this.oc=!0;this.Tn=!1;this.Fd=new H;this.Zh=new Ub;this.Bn=!0;this.Xm=250;this.Gk=
-1;this.Ym=(new Hc(16,16,16,16)).freeze();this.Wk=this.sd=!1;this.bl=!0;this.$h=new kf;this.$h.diagram=this;this.$e=new kf;this.$e.diagram=this;this.vj=new kf;this.vj.diagram=this;this.re=this.Cf=null;this.Rl=!1;this.Wt=this.Xt=null;this.Sq=ra.PointerEvent&&(gb||ib||jb)&&ra.navigator&&!1!==ra.navigator.msPointerEnabled;Fi(this);this.Bi=new H;this.Or=!0;this.Js=Gi;this.Xb=!1;this.Ls=Jg;this.Na=null;Hi.add("Model",Ii);this.ca=this.Ma=this.Wb=null;this.dr="";this.un="auto";this.Tf=this.cs=this.Vf=this.Wf=
this.Yf=this.Ef=this.If=this.Df=null;this.Ar=!1;this.Ff=this.jg=this.Xf=this.Uf=null;this.pu=!1;this.su={};this.Al=[null,null];this.L=null;this.Vt=this.Bu=this.Fh=this.fh=!1;this.Oc=!0;this.rj=this.$b=!1;this.ac=null;var d=this;this.zg=function(a){var b=d.partManager;if(a.model===b.diagram.model&&b.diagram.fa){b.diagram.fa=!1;try{var c=a.change;""===a.modelChange&&c===of&&b.updateDataBindings(a.object,a.propertyName)}finally{b.diagram.fa=!0}}};this.Hm=function(a){d.partManager.doModelChanged(a)};
this.Tw=!0;this.ie=-2;this.Hj=new Ub;this.ru=new F;this.Of=!1;this.Ih=this.Hh=this.Kq=this.Fc=!0;this.Lq=!1;this.Rq=this.Pq=this.Qh=this.Ph=this.Oh=this.Nh=this.Lh=this.Mh=this.Kh=this.Oq=this.Sh=this.Jh=this.Rh=this.Mq=!0;this.Se=this.Nc=!1;this.Qq=this.Nq=this.Cr=this.Br=!0;this.xs=this.vs=16;this.yu=this.us=!1;this.mp=this.ws=null;this.zu=this.Au=0;this.gb=(new Hc(5)).freeze();this.Iq=(new H).freeze();this.Yr=999999999;this.Gq=(new H).freeze();this.ei=this.pj=this.Sg=!0;this.bi=this.Rg=!1;this.ic=
null;this.Dg=!0;this.je=!1;this.Hq=new H;this.Ew=new H;this.Qb=null;this.Oo=1;this.Nw=0;this.Ae={scale:1,position:new J,bounds:new L,wx:!1};this.Sw=(new L(NaN,NaN,NaN,NaN)).freeze();this.Lp=(new Zb(NaN,NaN)).freeze();this.zn=(new L(NaN,NaN,NaN,NaN)).freeze();this.Pr=!1;this.pr=null;Ji(this);this.Ur=this.yr=this.fs=this.ww=this.vw=this.xw=this.Wg=this.ai=this.Zf=null;Ki(this);this.Hb=null;this.xr=!1;this.Ok=null;this.partManager=new Ii;this.toolManager=new $a;this.toolManager.initializeStandardTools();
this.currentTool=this.defaultTool=this.toolManager;this.nr=null;this.Qk=new Lf;this.ks=this.js=null;this.Cp=!1;this.commandHandler=Li();this.model=Mi();this.fh=!0;this.layout=new Ni;this.fh=!1;this.zw=this.Zt=null;this.Pb=1;this.kh=null;this.qe=1;this.Ao=0;this.Bo=[0,0,0,0,0];this.Co=0;this.Hd=1;this.pl=0;this.Rr=new J;this.Gu=500;this.Tq=new J;this.Te=!1;this.preventDefault=this.tt=this.pm=this.qm=this.om=this.nm=this.pk=this.rk=this.qk=this.mk=this.nk=this.fw=this.Yv=this.Zv=this.$v=this.ui=this.hp=
this.ti=this.gp=null;this.w=!1;this.ci=new Oi;this.Gs=!1;void 0!==a&&Pi(this,a);this.pb=!1}P.prototype.clear=function(){this.model.clear();Qi=null;Ri="";Si(this,!1);this.zn=(new L(NaN,NaN,NaN,NaN)).freeze();this.S()};
function Si(a,b){var c=null;null!==a.Hb&&(c=a.Hb.part);a.animationManager.xd();for(var d=[],e=a.Ra.length,f=0;f<e;f++){var g=a.Ra.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.Fd.clear();a.Zh.clear();a.Bi.clear();a.Vp();a.Qu();a.Ok=null;Ra=[];null!==c&&(a.add(c),a.partManager.parts.remove(c));if(b)for(b=0;b<d.length;b++)a.add(d[b])}function Li(){return null}
P.prototype.reset=function(){this.pb=!0;this.clear();this.Ek=new bi;this.Ek.ib(this);this.Ra=new F;this.Kv();this.Jv();this.ua=(new J(NaN,NaN)).freeze();this.Da=1;this.Er=(new J(NaN,NaN)).freeze();this.Fr=NaN;this.Zr=1E-4;this.Xr=100;this.Os=(new J(NaN,NaN)).freeze();this.vr=(new L(NaN,NaN,NaN,NaN)).freeze();this.vi=(new Hc(0,0,0,0)).freeze();this.Lj=Di;this.ys=!1;this.ts=this.ps=null;this.fj=Ei;this.hj=Qd;this.di=Ei;this.Sn=Qd;this.Gr=this.Dr=fd;this.Xm=250;this.Ym=(new Hc(16,16,16,16)).freeze();
this.Or=!0;this.Js=Gi;this.Ls=Jg;this.un="auto";this.Tf=this.cs=this.Vf=this.Wf=this.Yf=this.Ef=this.If=this.Df=null;this.Ar=!1;this.Ff=this.jg=this.Xf=this.Uf=null;this.Of=!1;this.Ih=this.Hh=this.Kq=this.Fc=!0;this.Lq=!1;this.Qq=this.Nq=this.Cr=this.Br=this.Rq=this.Pq=this.Qh=this.Ph=this.Oh=this.Nh=this.Lh=this.Mh=this.Kh=this.Oq=this.Sh=this.Jh=this.Rh=this.Mq=!0;this.xs=this.vs=16;this.gb=(new Hc(5)).freeze();this.Yr=999999999;this.ic=null;this.Pr=!1;this.Pb=1;this.kh=null;this.Ao=0;this.Bo=[0,
0,0,0,0];this.Co=0;Ki(this);this.Hb=null;this.partManager=new Ii;this.toolManager=new $a;this.toolManager.initializeStandardTools();this.ks=this.js=this.nr=null;this.Cp=!1;this.Qk.reset();this.uu=new Ub;this.uu.clear();this.currentTool=this.defaultTool=this.toolManager;this.commandHandler=Li();this.fh=!0;Ji(this);this.layout=new Ni;this.fh=!1;this.model=Mi();this.model.undoManager=new tf;this.je=!1;this.bl=!0;this.pb=this.sd=!1;this.S();this.re=this.Cf=null;Fi(this);this.dr=""};
function Ki(a){a.Zf=new Ub;var b=new V,c=new Kh;c.bind(new Ti("text","",Wa));b.add(c);a.xw=b;a.Zf.add("",b);b=new V;c=new Kh;c.stroke="brown";c.bind(new Ti("text","",Wa));b.add(c);a.Zf.add("Comment",b);b=new V;b.selectable=!1;b.avoidable=!1;c=new Hg;c.figure="Ellipse";c.fill="black";c.stroke=null;c.desiredSize=(new Zb(3,3)).ia();b.add(c);a.Zf.add("LinkLabel",b);a.ai=new Ub;b=new xg;b.selectionObjectName="GROUPPANEL";b.type=W.Vertical;c=new Kh;c.font="bold 12pt sans-serif";c.bind(new Ti("text","",
Wa));b.add(c);c=new W(W.Auto);c.name="GROUPPANEL";var d=new Hg;d.figure="Rectangle";d.fill="rgba(128,128,128,0.2)";d.stroke="black";c.add(d);d=new lh;d.padding=(new Hc(5,5,5,5)).ia();c.add(d);b.add(c);a.vw=b;a.ai.add("",b);a.Wg=new Ub;b=new S;c=new Hg;c.isPanelMain=!0;b.add(c);c=new Hg;c.toArrow="Standard";c.fill="black";c.stroke=null;c.strokeWidth=0;b.add(c);a.ww=b;a.Wg.add("",b);b=new S;c=new Hg;c.isPanelMain=!0;c.stroke="brown";b.add(c);a.Wg.add("Comment",b);b=new Cf;b.type=W.Auto;c=new Hg;c.fill=
null;c.stroke="dodgerblue";c.strokeWidth=3;b.add(c);c=new lh;c.margin=(new Hc(1.5,1.5,1.5,1.5)).ia();b.add(c);a.fs=b;a.yr=b;b=new Cf;b.type=W.Link;c=new Hg;c.isPanelMain=!0;c.fill=null;c.stroke="dodgerblue";c.strokeWidth=3;b.add(c);a.Ur=b}
P.prototype.setRTL=function(a){a=void 0===a?this.div:a;null===a&&(a=ra.document.body);var b=ya("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.wu=c};
P.prototype.setScrollWidth=function(a){a=void 0===a?this.div:a;null===a&&(a=ra.document.body);var b=0;if(Ih){var c=Ui;b=Vi;null===c&&(c=Ui=ya("p"),c.style.width="100%",c.style.height="200px",c.style.boxSizing="content-box",b=Vi=ya("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||lb||(b=11)}this.Jb=b};P.prototype.hb=function(a){a.classType===P?this.autoScale=a:Fa(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.Ra.iterator;c.next();)b+="\n "+c.value.toString(a-1);return b};P.prototype.addEventListener=function(a,b,c,d){a.addEventListener(b,c,d)};
P.prototype.removeEventListener=function(a,b,c,d){a.removeEventListener(b,c,d)};
function Wi(a){var b=a.Ea.Ha;b instanceof HTMLCanvasElement&&(a.Sq?(a.addEventListener(b,"pointerdown",a.nm,!1),a.addEventListener(b,"pointermove",a.om,!1),a.addEventListener(b,"pointerup",a.qm,!1),a.addEventListener(b,"pointerout",a.pm,!1)):(a.addEventListener(b,"touchstart",a.$v,!1),a.addEventListener(b,"touchmove",a.Zv,!1),a.addEventListener(b,"touchend",a.Yv,!1),a.addEventListener(b,"mousemove",a.nk,!1),a.addEventListener(b,"mousedown",a.mk,!1),a.addEventListener(b,"mouseup",a.qk,!1),a.addEventListener(b,
"mouseout",a.pk,!1)),a.addEventListener(b,"mouseenter",a.Ky,!1),a.addEventListener(b,"mouseleave",a.Ly,!1),a.addEventListener(b,"wheel",a.rk,!1),a.addEventListener(b,"keydown",a.Ez,!1),a.addEventListener(b,"keyup",a.Fz,!1),a.addEventListener(b,"blur",a.xy,!1),a.addEventListener(b,"focus",a.yy,!1),a.addEventListener(b,"selectstart",function(a){a.preventDefault();return!1},!1),a.addEventListener(b,"contextmenu",function(a){a.preventDefault();return!1},!1),a.addEventListener(b,"gesturestart",function(b){a.toolManager.gestureBehavior!==
Ff&&(a.toolManager.gestureBehavior===Ef?b.preventDefault():a.Te&&a.lastInput.handled||(b.preventDefault(),a.Oo=a.scale,a.currentTool.doCancel()))},!1),a.addEventListener(b,"gesturechange",function(b){if(a.toolManager.gestureBehavior!==Ff)if(a.toolManager.gestureBehavior===Ef)b.preventDefault();else if(!a.Te||!a.lastInput.handled){b.preventDefault();var c=b.scale;if(null!==a.Oo){var e=a.Ea.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.Oo*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),a.addEventListener(ra,"resize",a.fw,!1))}function Yf(a){30<a.Ao&&(a.kh=1)}function hg(a,b){null!==a.kh&&(a.kh=null,b&&a.tt(),a.Ao=0,a.Bo=[0,0,0,0,0],a.Co=0)}P.prototype.computePixelRatio=function(){return null!==this.kh?this.kh: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.Ea)if(this.scrollsPageOnFocus)this.Ea.focus();else{var a=ra.scrollX||ra.pageXOffset,b=ra.scrollY||ra.pageYOffset;this.Ea.focus();ra.scrollTo(a,b)}};P.prototype.yy=function(){this.D.ba("GainedFocus")};
P.prototype.xy=function(){this.D.ba("LostFocus")};function hi(a){if(null!==a.Ea){var b=a.Ja;if(0!==b.clientWidth&&0!==b.clientHeight){a.setScrollWidth();var c=a.bi?a.Jb:0,d=a.Rg?a.Jb:0,e=a.Pb;a.Pb=a.computePixelRatio();a.Pb!==e&&(a.Tn=!0,a.ec());if(b.clientWidth!==a.Aa+c||b.clientHeight!==a.ya+d)a.pj=!0,a.oc=!0,b=a.layout,null!==b&&b.isViewportSized&&a.autoScale===Ei&&(a.Wk=!0,b.C()),a.$b||a.ec()}}}
function Ji(a){var b=new ui;b.name="Background";a.Vl(b);b=new ui;b.name="";a.Vl(b);b=new ui;b.name="Foreground";a.Vl(b);b=new ui;b.name="Adornment";b.isTemporary=!0;a.Vl(b);b=new ui;b.name="Tool";b.isTemporary=!0;b.isBoundsIncluded=!0;a.Vl(b);b=new ui;b.name="Grid";b.allowSelect=!1;b.pickable=!1;b.isTemporary=!0;a.Ww(b,a.dm("Background"))}
function Xi(a){a.Hb=new W(W.Grid);a.Hb.name="GRID";var b=new Hg;b.figure="LineH";b.stroke="lightgray";b.strokeWidth=.5;b.interval=1;a.Hb.add(b);b=new Hg;b.figure="LineH";b.stroke="gray";b.strokeWidth=.5;b.interval=5;a.Hb.add(b);b=new Hg;b.figure="LineH";b.stroke="gray";b.strokeWidth=1;b.interval=10;a.Hb.add(b);b=new Hg;b.figure="LineV";b.stroke="lightgray";b.strokeWidth=.5;b.interval=1;a.Hb.add(b);b=new Hg;b.figure="LineV";b.stroke="gray";b.strokeWidth=.5;b.interval=5;a.Hb.add(b);b=new Hg;b.figure=
"LineV";b.stroke="gray";b.strokeWidth=1;b.interval=10;a.Hb.add(b);b=new T;b.add(a.Hb);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.Hb.visible=!1}function Yi(){this.D.yu?this.D.yu=!1:this.D.isEnabled?this.D.ix(this):Zi(this.D)}function cj(a){this.D.isEnabled?(this.D.Au=a.target.scrollTop,this.D.zu=a.target.scrollLeft):Zi(this.D)}
P.prototype.ix=function(a){if(null!==this.Ea){this.us=!0;var b=this.documentBounds,c=this.viewportBounds,d=this.vi,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.Xn)switch(this.wu){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.zu!==u&&(r.x=u/c+e,this.zu=u),this.allowVerticalScroll&&this.Au!==a.scrollTop&&(r.y=a.scrollTop/c+f,this.Au=a.scrollTop),this.position=r,J.free(r),this.pj=this.us=!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.ws.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.ws.scrollHeight-this.ya)+a.scrollTop-this.ya/c+d))),J.free(r),dj(this),this.pj=this.us=!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.mp.style.width="1px"),n>=h&&f>=b&&d<=q&&(this.mp.style.height="1px"))}};P.prototype.computeBounds=function(){0<this.Fd.count&&ej(this);return fj(this)};
function fj(a){if(a.fixedBounds.o()){var b=a.fixedBounds.copy();b.Sp(a.gb);return b}for(var c=!0,d=a.Ra.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.Lc(l)))}}}c&&(b=new L(0,0,0,0));b.Sp(a.gb);return b}
P.prototype.computePartsBounds=function(a,b){void 0===b&&(b=!1);var c=null;if(Ka(a))for(var d=0;d<a.length;d++){var e=a[d];!b&&e instanceof S||(e.bc(),null===c?c=e.actualBounds.copy():c.Lc(e.actualBounds))}else for(a=a.iterator;a.next();)d=a.value,!b&&d instanceof S||(d.bc(),null===c?c=d.actualBounds.copy():c.Lc(d.actualBounds));return null===c?new L(NaN,NaN,0,0):c};
function gj(a,b){if((b||a.je)&&!a.pb&&null!==a.Ea&&!a.animationManager.isAnimating&&a.documentBounds.o()){a.pb=!0;var c=a.fj;b&&a.di!==Ei&&(c=a.di);var d=c!==Ei?hj(a,c):a.scale;c=a.viewportBounds.copy();var e=a.Aa/d,f=a.ya/d,g=null,h=a.animationManager;h.sb&&(g=a.ua.copy());var k=a.hj,l=a.Sn;b&&!k.Za()&&(l.Za()||l.Cb())&&(k=l.Cb()?qd:l);ij(a,a.documentBounds,e,f,k,b);null!==g&&si(h,g,a.ua);b=a.scale;a.scale=d;a.pb=!1;d=a.viewportBounds;d.Sa(c)||a.sq(c,d,b,!1)}}
function hj(a,b){var c=a.kr;if(null===a.Ea)return c;a.Sg&&jj(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===kj?(b=Math.min(k,h),b>c&&(b=c),b<a.minScale&&(b=a.minScale),b>a.maxScale&&(b=a.maxScale),b):b===lj?(b=k>h?(g-a.Jb)/d:(f-a.Jb)/e,b>c&&(b=c),b<a.minScale&&(b=a.minScale),b>a.maxScale&&(b=a.maxScale),b):a.scale}
P.prototype.zoomToFit=function(){var a=this.Lj;this.Lj=Di;this.scale=hj(this,kj);a!==Di&&(gj(this,!1),ij(this,this.documentBounds,this.Aa/this.Da,this.ya/this.Da,this.hj,!1));this.Lj=a};t=P.prototype;
t.kA=function(a,b){void 0===b&&(b=kj);var c=a.width,d=a.height;if(!(0===c||0===d||isNaN(c)&&isNaN(d))){var e=1;if(b===kj||b===lj)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===lj?f/d>e/c?(f-(this.Rg?this.Jb:0))/d:(e-(this.bi?this.Jb:0))/c:Math.min(f/d,e/c)}this.scale=e;this.position=new J(a.x,a.y)}};
t.qy=function(a,b){this.Sg&&jj(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 ij(a,b,c,d,e,f){a.ua.ja();var g=a.ua,h=g.x,k=g.y;if(f||a.scrollMode===Di)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.vi,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.gb.left;g.y=isFinite(k)?k:-a.gb.top;null!==a.positionComputation&&(b=a.positionComputation(a,g),g.x=b.x,g.y=b.y);a.ua.freeze()}t.em=function(a,b){void 0===b&&(b=!0);if(b){if(a=vg(this,a,function(a){return a.part},function(a){return a.canSelect()}),a instanceof T)return a}else if(a=vg(this,a,function(a){return a.part}),a instanceof T)return a;return null};
t.Tb=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);ej(this);for(var d=this.Ra.iteratorBackwards;d.next();){var e=d.value;if(e.visible&&(e=e.Tb(a,b,c),null!==e))return e}return null};function vg(a,b,c,d){void 0===c&&(c=null);void 0===d&&(d=null);ej(a);for(a=a.Ra.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.Yy=function(a,b,c){void 0===b&&(b=!0);return mj(this,a,function(a){return a.part},b?function(a){return a instanceof T&&a.canSelect()}:null,c)};function mj(a,b,c,d,e){void 0===c&&(c=null);void 0===d&&(d=null);e instanceof F||e instanceof H||(e=new H);ej(a);for(a=a.Ra.iteratorBackwards;a.next();){var f=a.value;f.visible&&!f.isTemporary&&f.Ki(b,c,d,e)}return e}
t.Ki=function(a,b,c,d){void 0===b&&(b=null);void 0===c&&(c=null);d instanceof F||d instanceof H||(d=new H);ej(this);for(var e=this.Ra.iteratorBackwards;e.next();){var f=e.value;f.visible&&f.Ki(a,b,c,d)}return d};t.ox=function(a,b,c,d){void 0===b&&(b=!1);void 0===c&&(c=!0);return nj(this,a,function(a){return a instanceof T&&(!c||a.canSelect())},b,d)};
t.pg=function(a,b,c,d,e){void 0===b&&(b=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof F||e instanceof H||(e=new H);ej(this);for(var f=this.Ra.iteratorBackwards;f.next();){var g=f.value;g.visible&&g.pg(a,b,c,d,e)}return e};function nj(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 F||e instanceof H||(e=new H);ej(a);for(a=a.Ra.iteratorBackwards;a.next();){var g=a.value;g.visible&&!g.isTemporary&&g.pg(b,f,c,d,e)}return e}
t.Zy=function(a,b,c,d,e){void 0===c&&(c=!0);void 0===d&&(d=!0);return oj(this,a,b,function(a){return a instanceof T&&(!d||a.canSelect())},c,e)};t.qg=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 F||e instanceof H)f=e;e=!0}f instanceof F||f instanceof H||(f=new H);ej(this);for(var g=this.Ra.iteratorBackwards;g.next();){var h=g.value;h.visible&&h.qg(a,b,c,d,e,f)}return f};
function oj(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 F||e instanceof H)f=e;e=!0}f instanceof F||f instanceof H||(f=new H);ej(a);for(a=a.Ra.iteratorBackwards;a.next();){var h=a.value;h.visible&&!h.isTemporary&&h.qg(b,c,g,d,e,f)}return f}P.prototype.acceptEvent=function(a){return pj(this,a,a instanceof MouseEvent)};
function pj(a,b,c){var d=a.$e;a.$e=a.vj;a.vj=d;d.diagram=a;d.event=b;c?qj(a,b,d):(d.viewPoint=a.$e.viewPoint,d.documentPoint=a.$e.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);kb&&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=rj(b);d.targetObject=null;return d}
function rj(a){var b=a.target.D;if(!b){var c=a.path;c||"function"!==typeof a.composedPath||(c=a.composedPath());c&&c[0]&&(b=c[0].D)}return b?b:null}function sj(a,b,c,d){var e=tj(a,b,!0,!1,!0,d);qj(a,c,e);e.targetDiagram=rj(b);e.targetObject=null;d||e.clone(a.$h);return e}
function uj(a,b,c,d){var e;d=tj(a,b,!1,!1,!1,d);null!==c?((e=ra.document.elementFromPoint(c.clientX,c.clientY))&&e.D?(b=c,c=e.D):(b=void 0!==b.targetTouches?b.targetTouches[0]:b,c=a),d.targetDiagram=c,qj(a,b,d)):null!==a.$e?(d.documentPoint=a.$e.documentPoint,d.viewPoint=a.$e.viewPoint,d.targetDiagram=a.$e.targetDiagram):null!==a.$h&&(d.documentPoint=a.$h.documentPoint,d.viewPoint=a.$h.viewPoint,d.targetDiagram=a.$h.targetDiagram);d.targetObject=null;return d}
function tj(a,b,c,d,e,f){var g=a.$e;a.$e=a.vj;a.vj=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.Sq&&b instanceof ra.PointerEvent&&"touch"!==b.pointerType&&(g.button=b.button,void 0===b.buttons||fb||(g.buttons=b.buttons),kb&&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 vj(a,b,c){if(b.bubbles)return E&&E.tx&&Ha("NOT handled "+c.type+" "+b.toString()),!0;E&&E.tx&&Ha("handled "+c.type+" "+a.currentTool.name+" "+b.toString());void 0!==c.stopPropagation&&c.stopPropagation();!1!==c.cancelable&&c.preventDefault();c.cancelBubble=!0;return!1}
P.prototype.Ez=function(a){var b=this.D;if(!this.D.isEnabled)return!1;var c=pj(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 vj(b,c,a)};
P.prototype.Fz=function(a){var b=this.D;if(!b.isEnabled)return!1;var c=pj(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 vj(b,c,a)};
P.prototype.Ky=function(a){var b=this.D;if(!b.isEnabled)return!1;var c=pj(b,a,!0);null!==b.mouseEnter&&b.mouseEnter(c);return vj(b,c,a)};P.prototype.Ly=function(a){var b=this.D;if(!b.isEnabled)return!1;var c=pj(b,a,!0);null!==b.mouseLeave&&b.mouseLeave(c);return vj(b,c,a)};
P.prototype.getMouse=function(a){var b=this.Ea;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.ub?ac(new J(b,a),this.ub):new J(b,a)};
function qj(a,b,c){var d=a.Ea,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.ub?(b=J.allocAt(g,h),a.ub.Wd(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.Al[0])b=a.Al[c];else return;c=a.Ea;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.Sg||(this.Sg=!0,this.ec(!0))};function ri(a){a.$b||ej(a);a.Sg&&jj(a,a.computeBounds())}t.vf=function(){this.pb||this.$b||(this.S(),wj(this),dj(this),this.Ya(),this.hd())};t.Dz=function(){return this.sd};
t.Fy=function(a){void 0===a&&(a=null);var b=this.animationManager,c=b.isEnabled;b.xd();b.isEnabled=!1;Eg(this);this.je=!1;b.isEnabled=c;null!==a&&wa(a,1)};t.ec=function(a){void 0===a&&(a=!1);if(!0!==this.sd&&!(this.pb||!1===a&&this.$b)){this.sd=!0;var b=this;ra.requestAnimationFrame(function(){b.sd&&b.hd()})}};t.hd=function(){if(!this.bl||this.sd)this.bl&&(this.bl=!1),Eg(this)};function xj(a,b){a.animationManager.isAnimating||a.pb||!a.pj||Zi(a)||(b&&ej(a),gj(a,!1))}
function Eg(a,b){if(!a.$b&&(a.sd=!1,null!==a.Ja||a.Lp.o())){a.$b=!0;var c=a.animationManager,d=a.ru;if(!c.isTicking&&0!==d.length){for(var e=d.j,f=e.length,g=0;g<f;g++){var h=e[g];yj(h,!1);h.v()}d.clear()}d=a.Ew;0<d.count&&(d.each(function(a){a.ew()}),d.clear());e=d=!1;c.isAnimating&&(e=!0,d=a.skipsUndoManager,a.skipsUndoManager=!0);c.sb||hi(a);xj(a,!1);null!==a.Hb&&(a.Hb.visible&&!a.xr&&(zj(a),a.xr=!0),!a.Hb.visible&&a.xr&&(a.xr=!1));ej(a);f=!1;if(!a.je||a.Dg)a.je?Aj(a,!a.Wk):(a.Ca("Initial Layout"),
!1===c.isEnabled&&c.xd(),Aj(a,!1)),f=!0;a.Wk=!1;ej(a);a.Bu||c.isAnimating||ri(a);xj(a,!0);f&&(a.je||Bj(a),a.ba("LayoutCompleted"));ej(a);f&&!a.je&&(a.je=!0,a.ab("Initial Layout"),a.skipsUndoManager||a.undoManager.clear(),wa(function(){a.isModified=!1},1));a.Pu();gi(c);b||a.jc(a.$c);e&&(a.skipsUndoManager=d);a.$b=!1}}
function Bj(a){var b=a.Ra.j;a.kd(b,b.length,a);a.di!==Ei?a.scale=hj(a,a.di):a.fj!==Ei?a.scale=hj(a,a.fj):(b=a.initialScale,isFinite(b)&&0<b&&(a.scale=b));b=a.initialPosition;if(b.o())a.position=b;else{b=J.alloc();b.Yi(a.documentBounds,a.initialDocumentSpot);var c=a.viewportBounds;c=L.allocAt(0,0,c.width,c.height);var d=J.alloc();d.Yi(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);wj(a);xj(a,!0);gj(a,!0)}a.ba("InitialLayoutCompleted");zj(a)}
function ej(a){if((a.$b||!a.animationManager.isAnimating)&&0!==a.Fd.count){for(var b=0;23>b;b++){var c=a.Fd.iterator;if(null===c||0===a.Fd.count)break;a.Fd=new H;a.ew(c,a.Fd);E&&22===b&&Ha("failure to validate parts")}a.nodes.each(function(a){a instanceof xg&&0!==(a.T&65536)!==!1&&(a.T=a.T^65536)})}}
t.ew=function(a,b){for(a.reset();a.next();){var c=a.value;!c.dc()||c instanceof xg||(c.Vi()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c))}for(a.reset();a.next();)c=a.value,c instanceof xg&&c.isVisible()&&Cj(this,c);for(a.reset();a.next();)c=a.value,c instanceof S&&c.isVisible()&&(c.Vi()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c));for(a.reset();a.next();)c=a.value,c instanceof Cf&&c.isVisible()&&(c.Vi()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c))};
function Cj(a,b){for(var c=Qa(),d=Qa(),e=b.memberParts;e.next();){var f=e.value;f.isVisible()&&(f instanceof xg?(Dj(f)||Ej(f)||Fj(f))&&Cj(a,f):f instanceof S?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();Ta(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();Ta(d)}
t.kd=function(a,b,c,d){if(this.ei||this.animationManager.isAnimating)for(var e=0;e<b;e++)a[e].kd(c,d)};
t.jc=function(a,b){void 0===b&&(b=null);if(null!==this.Ja){null===this.Ea&&v("No canvas specified");var c=this.animationManager;if(!c.sb){var d=new Date;Gj(this);if("0"!==this.Ja.style.opacity){var e=a!==this.$c,f=this.Ra.j,g=f.length,h=this;this.kd(f,g,h);if(e)a.Uc(!0),dj(this);else if(!this.oc&&null===b&&!c.isAnimating)return;g=this.ua;var k=this.Da,l=Math.round(g.x*k)/k,m=Math.round(g.y*k)/k;c=this.ub;c.reset();1!==k&&c.scale(k);0===g.x&&0===g.y||c.translate(-l,-m);k=this.Pb;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.Gi&&E.Zu&&E.Zu(this,a);l=null!==b?function(c){var d=b;if(c.visible&&0!==c.mb){var e=c.Ga.j,f=e.length;if(0!==f){1!==c.mb&&(a.globalAlpha=c.mb);c=c.Qo;c.length=0;for(var g=h.scale,k=0;k<f;k++){var l=e[k];if(Dg(l)&&!d.contains(l)){if(l instanceof S&&(l.isOrthogonal&&c.push(l),!1===l.Mc))continue;var m=l.actualBounds;m.width*g>h.qe||m.height*g>h.qe?l.jc(a,
h):xi(a,l)}}a.globalAlpha=1}}}:function(b){b.jc(a,h)};Hj(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.ci&&Ij(this.ci,this)&&this.pr();E&&(E.$u||E.Gi)&&E.Yp&&E.Yp(a,this,c);e?(this.$c.Uc(!0),dj(this)):this.oc=this.ei=!1;e=+new Date-+d;if(null===this.kh){d=this.Bo;d[this.Co]=e;this.Co=(this.Co+1)%d.length;for(f=e=0;f<this.Bo.length;f++)e+=this.Bo[f];this.Ao=e/d.length}}}}};
function Jj(a,b,c,d,e,f,g,h,k,l){if(null!==a.Ja){null===a.Ea&&v("No canvas specified");void 0===g&&(g=null);void 0===h&&(h=null);void 0===k&&(k=!1);void 0===l&&(l=!1);Gj(a);a.$c.Uc(!0);dj(a);a.rj=!0;var m=a.Da;a.Da=e;var n=a.Ra.j,p=n.length;try{var q=new L(f.x,f.y,d.width/e,d.height/e),r=q.copy();r.Sp(c);zj(a,r);ej(a);a.kd(n,p,a,q);var u=a.Pb;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 x=$b.alloc();
x.reset();x.translate(c.left,c.top);x.scale(e);0===f.x&&0===f.y||x.translate(-f.x,-f.y);b.setTransform(x.m11,x.m12,x.m21,x.m22,x.dx,x.dy);$b.free(x);Hj(a,b);if(null!==g){var y=new H,A=g.iterator;for(A.reset();A.next();){var C=A.value;!1===l&&"Grid"===C.layer.name||null===C||y.add(C)}var G=function(c){var d=k;if(c.visible&&0!==c.mb&&(void 0===d&&(d=!0),d||!c.isTemporary)){d=c.Ga.j;var e=d.length;if(0!==e){1!==c.mb&&(b.globalAlpha=c.mb);c=c.Qo;c.length=0;for(var f=a.scale,g=0;g<e;g++){var h=d[g];if(Dg(h)&&
y.contains(h)){if(h instanceof S&&(h.isOrthogonal&&c.push(h),!1===h.Mc))continue;var l=h.actualBounds;l.width*f>a.qe||l.height*f>a.qe?h.jc(b,a):xi(b,h)}}b.globalAlpha=1}}}}else if(!k&&l){var I=a.grid.part,O=I.layer;G=function(c){c===O?I.jc(b,a):c.jc(b,a,k)}}else G=function(c){c.jc(b,a,k)};for(c=0;c<p;c++)G(n[c]);a.rj=!1;a.ci&&Ij(a.ci,a)&&a.pr()}finally{a.Da=m,a.$c.Uc(!0),dj(a),a.kd(n,p,a),zj(a)}}}t.Ge=function(a){return this.eg[a]};
t.Nx=function(a,b){"minDrawingLength"===a&&(this.qe=b);this.eg[a]=b;this.vf()};t.Kv=function(){this.eg=new xb;this.eg.drawShadows=!0;this.eg.textGreeking=!0;this.eg.viewportOptimizations=lb||gb||ib?!1:!0;this.eg.temporaryPixelRatio=!0;this.eg.pictureRatioOptimization=!0;this.qe=this.eg.minDrawingLength=1};function Hj(a,b){a=a.eg;null!==a&&(void 0!==a.imageSmoothingEnabled&&b.Mx(!!a.imageSmoothingEnabled),a=a.defaultFont,void 0!==a&&null!==a&&(b.font=a))}t.gm=function(a){return this.il[a]};
t.aA=function(a,b){this.il[a]=b};t.Jv=function(){this.il=new xb;this.il.extraTouchArea=10;this.il.extraTouchThreshold=10;this.il.hasGestureZoom=!0};t.Tv=function(a){Kj(this,a)};
function Kj(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.bb(k);else if(f=a[k],void 0===f||null===f)f=a.toolManager[k];Ja(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.Yw(b[g]);continue}else if(d&&"Changed"===g){a.sh(b[g]);continue}else if(d&&
Ya(a.toolManager,g))f=a.toolManager;else if(d&&Lj(a,g)){a.Sj(g,b[g]);continue}else if(a instanceof X&&"Changed"===g){a.sh(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.Vw(g)}}t.Pu=function(){if(0===this.undoManager.transactionLevel&&0!==this.Zh.count){for(;0<this.Zh.count;){var a=this.Zh;this.Zh=new Ub;for(a=a.iterator;a.next();){var b=a.key;b.jq(a.value);b.cc()}}this.S()}};
t.S=function(a){void 0===a&&(a=null);if(null===a)this.oc=!0,this.ec();else{var b=this.viewportBounds;null!==a&&a.o()&&b.Kc(a)&&(this.oc=!0,this.ec())}this.ba("InvalidateDraw")};
t.ux=function(a,b){if(!0!==this.oc){this.oc=!0;var c=!0===this.Ge("temporaryPixelRatio");if(!0===this.Ge("viewportOptimizations")&&this.scrollMode!==Mj&&this.vi.Ii(0,0,0,0)&&b.width===a.width&&b.height===a.height){var d=this.scale,e=Math.max(a.x,b.x),f=Math.max(a.y,b.y);d=L.allocAt(e,f,Math.max(0,Math.min(a.x+a.width,b.x+b.width)-e)*d,Math.max(0,Math.min(a.y+a.height,b.y+b.height)-f)*d);if(!this.Gs&&0<d.width&&0<d.height){if(!(this.$b||(this.sd=!1,null===this.Ja||(this.$b=!0,this.Pu(),this.documentBounds.o()||
jj(this,this.computeBounds()),e=this.Ea,null===e||e instanceof Nj)))){var g=this.Pb;f=this.Aa*g;var h=this.ya*g,k=this.scale*g,l=Math.round(Math.round(b.x*k)-Math.round(a.x*k));b=Math.round(Math.round(b.y*k)-Math.round(a.y*k));k=this.Zt;a=this.zw;k.width!==f&&(k.width=f);k.height!==h&&(k.height=h);a.clearRect(0,0,f,h);k=190*g;var m=70*g,n=Math.max(l,0),p=Math.max(b,0),q=Math.floor(f-n),r=Math.floor(h-p);a.drawImage(e.Ha,n,p,q,r,0,0,q,r);Ij(this.ci,this)&&a.clearRect(0,0,k,m);e=Qa();a=Qa();r=Math.abs(l);
q=Math.abs(b);var u=0===n?0:f-r;n=J.allocAt(u,0);r=J.allocAt(r+u,h);a.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 x=this.ub;x.reset();x.scale(g,g);1!==this.Da&&x.scale(this.Da);g=this.ua;(0!==g.x||0!==g.y)&&isFinite(g.x)&&isFinite(g.y)&&x.translate(-g.x,-g.y);ac(n,x);ac(r,x);e.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:h-q;n.h(0,u);r.h(f,q+u);a.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)));ac(n,x);ac(r,x);e.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)));Ij(this.ci,this)&&(f=0<l?0:-l,h=0<b?0:-b,n.h(f,h),r.h(k+f,m+h),a.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))),ac(n,x),ac(r,x),e.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);xj(this,!1);null===this.Ja&&v("No div specified");null===this.Ea&&v("No canvas specified");if(!this.animationManager.sb&&
(f=this.$c,this.oc)){Gj(this);h=this.Pb;f.setTransform(1,0,0,1,0,0);f.clearRect(0,0,this.Aa*h,this.ya*h);f.drawImage(this.Zt.Ha,0<l?0:Math.round(-l),0<b?0:Math.round(-b));b=this.ua;g=this.Da;k=Math.round(b.x*g)/g;m=Math.round(b.y*g)/g;l=this.ub;l.reset();1!==g&&l.scale(g);0===b.x&&0===b.y||l.translate(-k,-m);f.save();f.beginPath();b=a.length;for(g=0;g<b;g++)k=a[g],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.clip();f.setTransform(1,0,
0,1,0,0);f.scale(h,h);f.transform(l.m11,l.m12,l.m21,l.m22,l.dx,l.dy);E&&E.Gi&&E.Zu&&E.Zu(this,f);h=this.Ra.j;b=h.length;this.kd(h,b,this);Hj(this,f);for(g=0;g<b;g++)if(n=h[g],k=e,n.visible&&0!==n.mb){1!==n.mb&&(f.globalAlpha=n.mb);m=n.Qo;m.length=0;p=this.scale;n=n.Ga.j;q=n.length;r=k.length;for(x=0;x<q;x++)if(u=n[x],Dg(u)){if(u instanceof S&&(u.isOrthogonal&&m.push(u),!1===u.Mc))continue;var y=Oj(u,u.actualBounds);a:{var A=y;for(var C=k,G=r,I=2/p,O=4/p,R=0;R<G;R++){var U=C[R];if(0!==U.width&&0!==
U.height&&A.pv(U.x-I,U.y-I,U.width+O,U.height+O)){A=!0;break a}}A=!1}A&&(y.width*p>this.qe||y.height*p>this.qe?u.jc(f,this):xi(f,u))}f.globalAlpha=1}f.restore();f.Uc(!0);E&&(E.$u||E.Gi)&&E.Yp&&E.Yp(f,this,l);this.ci&&Ij(this.ci,this)&&this.pr();this.oc=this.ei=!1;this.tt()}Ta(e);Ta(a);this.$b=!1}}else this.hd();L.free(d);c&&(Yf(this),this.hd(),hg(this,!0))}else c?(Yf(this),this.hd(),hg(this,!0)):this.hd()}};function wj(a){!1===a.pj&&(a.pj=!0)}function dj(a){!1===a.ei&&(a.ei=!0)}
function Gj(a){!1!==a.Tn&&(a.Tn=!1,Pj(a,a.Aa,a.ya))}function Pj(a,b,c){var d=a.Pb;a.Ea.resize(b*d,c*d,b,c)&&(a.oc=!0,a.$c.Uc(!0))}
function Zi(a){var b=a.Ea;if(null===b)return!0;var c=a.Ja,d=a.Aa,e=a.ya,f=a.Sw.copy();if(!f.o())return!0;var g=!1,h=a.bi?a.Jb:0,k=a.Rg?a.Jb:0,l=c.clientWidth||d+h;c=c.clientHeight||e+k;if(l!==d+h||c!==e+k)a.bi=!1,a.Rg=!1,k=h=0,a.Aa=l,a.ya=c,g=a.Tn=!0;a.pj=!1;var m=a.documentBounds,n=0,p=0,q=0,r=0;l=f.width;c=f.height;var u=a.vi;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 x=m.height+q+r;n=m.x-n;
var y=f.x;p=m.right+p;var A=f.right+h;q=m.y-q;var C=f.y;r=m.bottom+r;var G=f.bottom+k,I="1px",O="1px";m=a.scale;var R=!(u<l+h),U=!(x<c+k);a.scrollMode===Di&&(R||U)&&(R&&a.hasHorizontalScrollbar&&a.allowHorizontalScroll&&(I=1,n+1<y&&(I=Math.max((y-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"),U&&a.hasVerticalScrollbar&&a.allowVerticalScroll&&(O=1,q+1<C&&(O=Math.max((C-q)*m+a.ya,O)),r>G+1&&(O=Math.max((r-G)*m+a.ya,O)),c+k+1<x&&(O=Math.max((x-
c+k)*m+a.ya,O)),O=O.toString()+"px"));U="1px"!==I;R="1px"!==O;U&&R||!U&&!R||(R&&(A-=a.Jb),U&&(G-=a.Jb),u<l+h||!a.hasHorizontalScrollbar||!a.allowHorizontalScroll||(h=1,n+1<y&&(h=Math.max((y-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"),U="1px"!==I,h=a.ya,U!==a.Rg&&(h=U?a.ya-a.Jb:a.ya+a.Jb),x<c+k||!a.hasVerticalScrollbar||!a.allowVerticalScroll||(k=1,q+1<C&&(k=Math.max((C-q)*m+h,k)),r>G+1&&(k=Math.max((r-G)*m+h,k)),c+1<x&&(k=Math.max((x-
c)*m+h,k)),O=k.toString()+"px"),R="1px"!==O);if(a.us&&U===a.Rg&&R===a.bi)return d===a.Aa&&e===a.ya||a.hd(),!1;U!==a.Rg&&("1px"===I?a.ya=a.ya+a.Jb:a.ya=Math.max(a.ya-a.Jb,1),g=!0);a.Rg=U;a.mp.style.width=I;R!==a.bi&&("1px"===O?a.Aa=a.Aa+a.Jb:a.Aa=Math.max(a.Aa-a.Jb,1),g=!0,a.Xn&&(k=J.alloc(),R?(b.style.left=a.Jb+"px",a.position=k.h(a.ua.x+a.Jb/a.scale,a.ua.y)):(b.style.left="0px",a.position=k.h(a.ua.x-a.Jb/a.scale,a.ua.y)),J.free(k)));a.bi=R;a.mp.style.height=O;a.yu=!0;g&&(a.Tn=!0);b=a.ws;k=b.scrollLeft;
a.hasHorizontalScrollbar&&a.allowHorizontalScroll&&(l+1<u?k=(a.position.x-n)*m:n+1<y?k=b.scrollWidth-b.clientWidth:p>A+1&&(k=a.position.x*m));if(a.Xn)switch(a.wu){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<x?b.scrollTop=(a.position.y-q)*m:q+1<C?b.scrollTop=b.scrollHeight-b.clientHeight:r>G+1&&(b.scrollTop=a.position.y*m));l=a.Aa;c=a.ya;b.style.width=l+(a.bi?a.Jb:0)+"px";
b.style.height=c+(a.Rg?a.Jb:0)+"px";return d!==l||e!==c||a.animationManager.sb?(a.sq(f,a.viewportBounds,m,g),!1):!0}
t.add=function(a){w(a,T,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.dm(a.layerName),null===b&&(b=this.dm("")),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.Si(99999999,a,a.diagram===this);0<=c&&this.cb(qf,"parts",b,null,a,null,c);b.isTemporary||this.Ya();a.C(1);c=a.layerChanged;null!==c&&c(a,null,
b)}};t.Si=function(a){this.partManager.Si(a);var b=this;Qj(a,function(a){Rj(b,a)});(a instanceof Cf||a instanceof xg&&null!==a.placeholder)&&a.v();null!==a.data&&Qj(a,function(a){Sj(b.partManager,a)});!0!==Ej(a)&&!0!==Fj(a)||this.Fd.add(a);Tj(a,!0,this);Uj(a)?(a.actualBounds.o()&&this.S(Oj(a,a.actualBounds)),this.Ya()):a.isVisible()&&a.actualBounds.o()&&this.S(Oj(a,a.actualBounds));this.ec()};
t.zc=function(a){a.Xj();this.partManager.zc(a);var b=this;null!==a.data&&Qj(a,function(a){Vj(b.partManager,a,b)});this.Fd.remove(a);Uj(a)?(a.actualBounds.o()&&this.S(Oj(a,a.actualBounds)),this.Ya()):a.isVisible()&&a.actualBounds.o()&&this.S(Oj(a,a.actualBounds));this.ec()};t.remove=function(a){w(a,T,P,"remove:part");Wj(this,a,!0)};
function Wj(a,b,c){var d=b.layer;null!==d&&d.diagram===a&&(b.isSelected=!1,b.isHighlighted=!1,b.C(2),c&&b.ck(),c=d.zc(-1,b,!1),0<=c&&a.cb(rf,"parts",d,b,null,c,null),a=b.layerChanged,null!==a&&a(b,d,null))}t.wt=function(a,b){if(Ka(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.bk=function(a,b,c){return this.partManager.bk(a,b,c)};
P.prototype.moveParts=function(a,b,c,d){void 0===d&&(d=Xj(this));w(b,J,P,"moveParts:offset");if(null!==this.toolManager){var e=new Ub;if(null!==a)if(Ka(a))for(var f=0;f<a.length;f++)Yj(this,e,a[f],c,d);else for(a=a.iterator;a.next();)Yj(this,e,a.value,c,d);else{for(a=this.parts;a.next();)Yj(this,e,a.value,c,d);for(a=this.nodes;a.next();)Yj(this,e,a.value,c,d);for(a=this.links;a.next();)Yj(this,e,a.value,c,d)}pg(this,e,b,d,c)}};
function Yj(a,b,c,d,e){void 0===e&&(e=Xj(a));if(!b.contains(c)&&(!d||c.canMove()||c.canCopy()))if(c instanceof V){b.add(c,a.rd(e,c,c.location));if(c instanceof xg)for(var f=c.memberParts;f.next();)Yj(a,b,f.value,d,e);for(f=c.linksConnected;f.next();){var g=f.value;if(!b.contains(g)){var h=g.fromNode,k=g.toNode;null!==h&&b.contains(h)&&null!==k&&b.contains(k)&&Yj(a,b,g,d,e)}}if(e.dragsTree)for(c=c.hv();c.next();)Yj(a,b,c.value,d,e)}else if(c instanceof S)for(b.add(c,a.rd(e,c)),c=c.labelNodes;c.next();)Yj(a,
b,c.value,d,e);else c instanceof Cf||b.add(c,a.rd(e,c,c.location))}
function pg(a,b,c,d,e){if(null!==b&&(w(b,Ub,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.Cp)||Zf(a,b);for(var h=Qa(),k=Qa(),l=b.iterator,m=J.alloc();l.next();){var n=l.key,p=l.value;if(n.dc()){var q=Zj(a,n,b);if(null!==q)h.push(new ak(n,p,q));else if(!e||n.canMove())q=p.point,f.assign(q),a.computeMove(n,f.add(g),d,m),n.location=m,void 0===p.shifted&&(p.shifted=new J),p.shifted.assign(m.Zd(q))}else l.key instanceof S&&k.push(l.pa)}J.free(m);
e=h.length;for(l=0;l<e;l++)n=h[l],f.assign(n.info.point),void 0===n.mv.shifted&&(n.mv.shifted=new J),n.node.location=f.add(n.mv.shifted);e=J.alloc();l=J.alloc();n=k.length;for(p=0;p<n;p++){var r=k[p];q=r.key;if(q instanceof S)if(q.suspendsRouting){q.dh=null;m=q.fromNode;var u=q.toNode;if(null!==a.draggedLink&&d.dragsLink)if(u=r.value.point,null===q.dragComputation)b.add(q,a.rd(d,q,g)),ng(q,g.x-u.x,g.y-u.y);else{r=J.allocAt(0,0);(m=q.i(0))&&m.o()&&r.assign(m);var x=m=J.alloc().assign(r).add(g);d.isGridSnapEnabled&&
(d.isGridSnapRealtime||a.lastInput.up)&&(x=J.alloc(),uh(a,q,m,x,d));m.assign(q.dragComputation(q,m,x)).Zd(r);b.add(q,a.rd(d,q,m));ng(q,m.x-u.x,m.y-u.y);J.free(r);J.free(m);x!==m&&J.free(x)}else null!==m&&(e.assign(m.location),x=b.K(m),null!==x&&e.Zd(x.point)),null!==u&&(l.assign(u.location),x=b.K(u),null!==x&&l.Zd(x.point)),null!==m&&null!==u?e.Sa(l)?(m=r.value.point,u=f,u.assign(e),u.Zd(m),b.add(q,a.rd(d,q,e)),ng(q,u.x,u.y)):(q.suspendsRouting=!1,q.Ta()):(r=r.value.point,m=null!==m?e:null!==u?l:
g,b.add(q,a.rd(d,q,m)),ng(q,m.x-r.x,m.y-r.y))}else if(null===q.fromNode||null===q.toNode)m=r.value.point,b.add(q,a.rd(d,q,g)),ng(q,g.x-m.x,g.y-m.y)}J.free(f);J.free(g);J.free(e);J.free(l);Ta(h);Ta(k);c||(ej(a),dg(a,b))}}
P.prototype.computeMove=function(a,b,c,d){void 0===d&&(d=new J);d.assign(b);if(null===a)return d;var e=b,f=c.isGridSnapEnabled;f&&(c.isGridSnapRealtime||this.lastInput.up)&&(e=J.alloc(),uh(this,a,b,e,c));c=null!==a.dragComputation?a.dragComputation(a,b,e):e;var g=a.minLocation,h=g.x;isNaN(h)&&(h=f?Math.round(a.location.x):a.location.x);g=g.y;isNaN(g)&&(g=f?Math.round(a.location.y):a.location.y);var k=a.maxLocation,l=k.x;isNaN(l)&&(l=f?Math.round(a.location.x):a.location.x);k=k.y;isNaN(k)&&(k=f?Math.round(a.location.y):
a.location.y);d.h(Math.max(h,Math.min(c.x,l)),Math.max(g,Math.min(c.y,k)));e!==b&&J.free(e);return d};function Xj(a){var b=a.toolManager.findTool("Dragging");return null!==b?b.dragOptions:a.Qk}
function uh(a,b,c,d,e){void 0===e&&(e=Xj(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.vk(0,0,a,b,e);K.bq(c.x,c.y,h+f.x,g+f.y,a,b,d);J.free(f)}}function Zf(a,b){if(null!==b)for(a.Cp=!0,a=b.iterator;a.next();)b=a.key,b instanceof S&&(b.suspendsRouting=!0)}
function dg(a,b){if(null!==b){for(b=b.iterator;b.next();){var c=b.key;c instanceof S&&(c.suspendsRouting=!1,bk(c)&&c.Ta())}a.Cp=!1}}function Zj(a,b,c){b=b.containingGroup;if(null!==b){a=Zj(a,b,c);if(null!==a)return a;a=c.K(b);if(null!==a)return a}return null}t=P.prototype;t.rd=function(a,b,c){if(void 0===c)return new bg(gc);var d=a.isGridSnapEnabled;a.uz||null===b.containingGroup||(d=!1);return d?new bg(new J(Math.round(c.x),Math.round(c.y))):new bg(c.copy())};
function ck(a,b,c){w(b,ui,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,ui,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.Ra;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.Vl=function(a){ck(this,a,null);a.ib(this);var b=this.Ra,c=b.count-1;if(!a.isTemporary)for(;0<=c&&b.O(c).isTemporary;)c--;b.Lb(c+1,a);null!==this.ac&&this.cb(qf,"layers",this,null,a,null,c+1);this.S();this.Ya()};
t.Ww=function(a,b){ck(this,a,b);a.ib(this);var c=this.Ra,d=c.indexOf(a);0<=d&&(c.remove(a),null!==this.ac&&this.cb(rf,"layers",this,a,null,d,null));var e=c.count,f;for(f=0;f<e;f++)if(c.O(f)===b){c.Lb(f,a);break}null!==this.ac&&this.cb(qf,"layers",this,null,a,null,f);this.S();0>d&&this.Ya()};
t.ly=function(a,b){ck(this,a,b);a.ib(this);var c=this.Ra,d=c.indexOf(a);0<=d&&(c.remove(a),null!==this.ac&&this.cb(rf,"layers",this,a,null,d,null));var e=c.count,f;for(f=0;f<e;f++)if(c.O(f)===b){c.Lb(f+1,a);break}null!==this.ac&&this.cb(qf,"layers",this,null,a,null,f+1);this.S();0>d&&this.Ya()};
t.Vz=function(a){w(a,ui,P,"removeLayer:layer");a.diagram!==this&&v("Cannot remove a Layer from another Diagram: "+a+" of "+a.diagram);if(""!==a.name){var b=this.Ra,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.cb(rf,"layers",this,a,null,c,null);this.S();this.Ya()}}};t.dm=function(a){for(var b=this.layers;b.next();){var c=b.value;if(c.name===a)return c}return null};
t.Yw=function(a){z(a,"function",P,"addModelChangedListener:listener");null===this.re&&(this.re=new F);this.re.add(a);this.model.sh(a)};t.Xz=function(a){z(a,"function",P,"removeModelChangedListener:listener");null!==this.re&&(this.re.remove(a),0===this.re.count&&(this.re=null));this.model.uk(a)};t.sh=function(a){z(a,"function",P,"addChangedListener:listener");null===this.Cf&&(this.Cf=new F);this.Cf.add(a)};
t.uk=function(a){z(a,"function",P,"removeChangedListener:listener");null!==this.Cf&&(this.Cf.remove(a),0===this.Cf.count&&(this.Cf=null))};t.Qs=function(a){this.skipsUndoManager||this.model.skipsUndoManager||this.model.undoManager.nv(a);a.change!==pf&&(this.isModified=!0);if(null!==this.Cf)for(var b=this.Cf,c=b.length,d=0;d<c;d++)b.O(d)(a)};
t.cb=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.Qs(h)};t.g=function(a,b,c,d,e){this.cb(of,a,this,b,c,d,e)};
t.Wj=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;dk(e,a.propertyName,a.K(b));if(e instanceof N){var f=e.part;null!==f&&f.Mb()}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.zc(h):g.Lb(h,k);var l=g.part;null!==l&&l.Mb()}else{if("number"===typeof h&&k instanceof ek)if(b)k.isRow?g.Hv(h):g.Fv(h);else{var m=
k.isRow?g.getRowDefinition(k.index):g.getColumnDefinition(k.index);m.$l(k)}}else if(g instanceof ui){var n=!0===a.oldParam;"number"===typeof h&&k instanceof T&&(b?(k.isSelected=!1,k.isHighlighted=!1,k.Mb(),g.zc(n?h:-1,k,n)):g.Si(h,k,n))}else g instanceof P?"number"===typeof h&&k instanceof ui&&(b?this.Ra.nb(h):(k.ib(this),this.Ra.Lb(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.Lb(q,r):p.zc(q):"number"===typeof q&&r instanceof ek&&(b?(m=r.isRow?p.getRowDefinition(r.index):p.getColumnDefinition(r.index),m.$l(r)):r.isRow?p.Hv(q):p.Fv(q));else if(p instanceof ui){var u=!0===a.newParam;"number"===typeof q&&r instanceof T&&(b?0>p.Ga.indexOf(r)&&p.Si(q,r,u):(r.isSelected=!1,r.isHighlighted=!1,r.Mb(),p.zc(u?q:-1,r,u)))}else p instanceof P?"number"===typeof q&&r instanceof ui&&(b?(r.ib(this),this.Ra.Lb(q,r)):this.Ra.nb(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.ab=function(a){return this.undoManager.ab(a)};t.xf=function(){return this.undoManager.xf()};
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.ab(b):this.undoManager.xf(),this.skipsUndoManager=c}};P.prototype.updateAllTargetBindings=function(a){this.partManager.updateAllTargetBindings(a)};t=P.prototype;t.Dq=function(){this.partManager.Dq()};
function fk(a,b,c){var d=a.animationManager;if(a.pb||a.$b)a.Da=c,ti(d,b,a.Da);else if(a.pb=!0,null===a.Ea)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.tf()?l.sf(wd)?h=0:l.sf(Ad)&&(h=f-1):h=l.Za()?l.x*(f-1):f/2);isNaN(k)&&(l.tf()?l.sf(vd)?k=0:l.sf(Bd)&&(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.ua.x+h/b-h/c,a.ua.y+k/b-k/c);a.position=f;J.free(f);a.Da=c;a.sq(e,a.viewportBounds,b,!1);a.pb=!1;gj(a,!1);ti(d,b,a.Da);a.S();wj(a)}}
t.sq=function(a,b,c,d){if(!a.A(b)){void 0===d&&(d=!1);d||wj(this);dj(this);var e=this.layout;null===e||!e.isViewportSized||this.autoScale!==Ei||d||a.width===b.width&&a.height===b.height||e.C();e=this.currentTool;!0===this.Se&&e instanceof $a&&(this.lastInput.documentPoint=this.Dt(this.lastInput.viewPoint),Gf(e,this));this.pb||this.ux(a,b);zj(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.Kc(b)&&a.Ta()})}};
function zj(a,b){void 0===b&&(b=null);var c=a.Hb;if(null!==c&&c.visible){for(var d=Zb.alloc(),e=1,f=1,g=c.Z.j,h=g.length,k=0;k<h;k++){var l=g[k],m=l.interval;2>m||(gk(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.bq(a,g,0,0,
d.width,d.height,b);b.offset(-d.width,-d.height);Zb.free(d);c.part.location=b;J.free(b)}}t.Vp=function(){var a=0<this.selection.count;a&&this.ba("ChangingSelection",this.selection);Mf(this);a&&this.ba("ChangedSelection",this.selection)};function Mf(a){a=a.selection;if(0<a.count){for(var b=a.Oa(),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,T,P,"select:part"),a.layer.diagram===this&&(!a.isSelected||1<this.selection.count)&&(this.ba("ChangingSelection",this.selection),Mf(this),a.isSelected=!0,this.ba("ChangedSelection",this.selection)))};
t.Nv=function(a){this.ba("ChangingSelection",this.selection);Mf(this);if(Ka(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];d instanceof T||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 T||v("Diagram.selectCollection given something that is not a Part: "+b),b.isSelected=!0;this.ba("ChangedSelection",this.selection)};
t.Qu=function(){var a=this.highlighteds;if(0<a.count){for(var b=a.Oa(),c=b.length,d=0;d<c;d++)b[d].isHighlighted=!1;a.ja();a.clear();a.freeze()}};t.wz=function(a){null!==a&&a.layer.diagram===this&&(w(a,T,P,"highlight:part"),!a.isHighlighted||1<this.highlighteds.count)&&(this.Qu(),a.isHighlighted=!0)};
t.xz=function(a){a=(new H).addAll(a);for(var b=this.highlighteds.copy().vq(a).iterator;b.next();)b.value.isHighlighted=!1;for(a=a.iterator;a.next();)b=a.value,b instanceof T||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.Mv=function(a){var b=this.viewportBounds;b.pf(a)||(a=a.center,a.x-=b.width/2,a.y-=b.height/2,this.position=a)};t.Ou=function(a){var b=this.viewportBounds;a=a.center;a.x-=b.width/2;a.y-=b.height/2;this.position=a};t.Ct=function(a){var b=this.ub;b.reset();1!==this.Da&&b.scale(this.Da);var c=this.ua;(0!==c.x||0!==c.y)&&isFinite(c.x)&&isFinite(c.y)&&b.translate(-c.x,-c.y);return a.copy().transform(this.ub)};
t.hA=function(a){var b=this.ub,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.Dt=function(a){var b=this.ub;b.reset();1!==this.Da&&b.scale(this.Da);var c=this.ua;(0!==c.x||0!==c.y)&&isFinite(c.x)&&isFinite(c.y)&&b.translate(-c.x,-c.y);return ac(a.copy(),this.ub)};function hk(a){var b=a.isModified;a.Tw!==b&&(a.Tw=b,a.ba("Modified"))}function ik(a){a=Hi.get(a);return null!==a?new a:new Ii}
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.ib(d)});a.mouseMoveTools.each(function(a){a.ib(d)});a.mouseUpTools.each(function(a){a.ib(d)});this.$b||this.je||(this.Wk=!0,this.bl&&(this.sd=!0))}else"StartingUndo"===c||"StartingRedo"===c?(a=this.animationManager,a.isAnimating&&!this.skipsUndoManager&&a.xd(),this.ba("ChangingSelection",
this.selection)):"StartedTransaction"===c&&(a=this.animationManager,a.isAnimating&&!this.skipsUndoManager&&a.xd());else if(this.fa){this.fa=!1;try{if(""===a.modelChange&&b===pf){if("FinishedUndo"===c||"FinishedRedo"===c)this.ba("ChangedSelection",this.selection),ej(this);var e=this.animationManager;"RolledBackTransaction"===c&&e.xd();this.Wk=!0;this.hd();0===this.undoManager.transactionLevel&&gi(e);"CommittedTransaction"===c&&this.undoManager.iu&&(this.ie=Math.min(this.ie,this.undoManager.historyIndex-
1));var f=a.isTransactionFinished;f&&(hk(this),this.lt.clear());if(!this.pu&&f){this.pu=!0;var g=this;wa(function(){g.currentTool.standardMouseOver();g.pu=!1},10)}}}finally{this.fa=!0}}}};function Rj(a,b){b=b.Z.j;for(var c=b.length,d=0;d<c;d++)jk(a,b[d])}
function jk(a,b){if(b instanceof kk){var c=b.element;if(null!==c&&c instanceof HTMLImageElement){var d=b.Mg;null!==d&&(d.dl instanceof Event&&null!==b.Ec&&b.Ec(b,d.dl),!0===d.Jr&&(null!==b.gf&&b.gf(b,d.xu),null!==b.diagram&&b.diagram.ru.add(b)));c=c.src;d=a.Hj.K(c);if(null===d)d=[],d.push(b),a.Hj.add(c,d);else{for(a=0;a<d.length;a++)if(d[a]===b)return;d.push(b)}}}}
function lk(a,b){if(b instanceof kk){var c=b.element;if(null!==c&&c instanceof HTMLImageElement){c=c.src;var d=a.Hj.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.Hj.remove(c),pk(c));break}}}}P.prototype.wd=function(){this.partManager.wd()};P.prototype.Qp=function(a,b){this.Ek.Qp(a,b)};P.prototype.Rp=function(a,b){this.Ek.Rp(a,b)};P.prototype.findPartForKey=function(a){return this.partManager.findPartForKey(a)};t=P.prototype;t.Kb=function(a){return this.partManager.Kb(a)};
t.xc=function(a){return this.partManager.xc(a)};t.Ji=function(a){return this.partManager.Ji(a)};t.wc=function(a){return this.partManager.wc(a)};t.Xs=function(a){for(var b=[],c=0;c<arguments.length;++c)b[c]=arguments[c];return this.partManager.Xs.apply(this.partManager,b instanceof Array?b:da(ca(b)))};t.Ws=function(a){for(var b=[],c=0;c<arguments.length;++c)b[c]=arguments[c];return this.partManager.Ws.apply(this.partManager,b instanceof Array?b:da(ca(b)))};
function jj(a,b){a.Sg=!1;var c=a.zn;c.A(b)||(b=b.J(),a.zn=b,gj(a,!1),a.ba("DocumentBoundsChanged",null,c.copy()),wj(a))}t.cz=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.bz=function(){return this.Bi.iterator};t.Hz=function(a){ej(this);a&&tk(this,!0);this.Wk=!0;Eg(this)};
function tk(a,b){for(var c=a.Bi.iterator;c.next();)uk(a,c.value,b);null!==a.layout&&(b?a.layout.isValidLayout=!1:a.layout.C())}function uk(a,b,c){if(null!==b){for(var d=b.wl.iterator;d.next();)uk(a,d.value,c);null!==b.layout&&(c?b.layout.isValidLayout=!1:b.layout.C())}}
function Aj(a,b){if(a.Dg&&!a.Vt){var c=a.fa;a.fa=!0;var d=a.undoManager.transactionLevel,e=a.layout;try{0===d&&a.Ca("Layout");var f=a.animationManager;1>=d&&!f.isAnimating&&!f.sb&&(b||f.Dh("Layout"));a.Dg=!1;for(var g=a.Bi.iterator;g.next();)vk(a,g.value,b,d);e.isValidLayout||(!b||e.isRealtime||null===e.isRealtime||0===d?(e.doLayout(a),ej(a),e.isValidLayout=!0):a.Dg=!0)}finally{0===d&&a.ab("Layout"),a.Dg=!e.isValidLayout,a.fa=c}}}
function vk(a,b,c,d){if(null!==b){for(var e=b.wl.iterator;e.next();)vk(a,e.value,c,d);e=b.layout;null===e||e.isValidLayout||(!c||e.isRealtime||0===d?(b.sk=!b.location.o(),e.doLayout(b),b.C(32),Cj(a,b),e.isValidLayout=!0):a.Dg=!0)}}t.iz=function(){for(var a=new F,b=this.nodes;b.next();){var c=b.value;c.isTopLevel&&null===c.Mi()&&a.add(c)}return a.iterator};
function Fi(a){function b(a){var b=a.toLowerCase(),e=new F;c.add(a,e);c.add(b,e);d.add(a,a);d.add(b,a)}var c=new Ub,d=new Ub;b("AnimationStarting");b("AnimationFinished");b("BackgroundSingleClicked");b("BackgroundDoubleClicked");b("BackgroundContextClicked");b("ClipboardChanged");b("ClipboardPasted");b("DocumentBoundsChanged");b("ExternalObjectsDropped");b("GainedFocus");b("InitialLayoutCompleted");b("LayoutCompleted");b("LinkDrawn");b("LinkRelinked");b("LinkReshaped");b("LostFocus");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.Xt=c;a.Wt=d}
function Lj(a,b){var c=a.Wt.K(b);return null!==c?c:a.Wt.K(b.toLowerCase())}function wk(a,b){var c=a.Xt.K(b);if(null!==c)return c;c=a.Xt.K(b.toLowerCase());if(null!==c)return c;v("Unknown DiagramEvent name: "+b);return null}t.Sj=function(a,b){z(a,"string",P,"addDiagramListener:name");z(b,"function",P,"addDiagramListener:listener");a=wk(this,a);null!==a&&a.add(b)};t.sm=function(a,b){z(a,"string",P,"removeDiagramListener:name");z(b,"function",P,"addDiagramListener:listener");a=wk(this,a);null!==a&&a.remove(b)};
t.ba=function(a,b,c){E&&z(a,"string",P,"raiseDiagramEvent:name");var d=wk(this,a),e=new mf;e.diagram=this;a=Lj(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.Oa(),c=0;c<b;c++)(0,d[c])(e)};function xk(a){if(a.animationManager.isAnimating)return!1;var b=a.currentTool;return b===a.toolManager.findTool("Dragging")?!a.Cp||b.isComplexRoutingRealtime:!0}
t.jk=function(a,b){void 0===b&&(b=null);return yk(this,!1,null,b).jk(a.x,a.y,a.width,a.height)};P.prototype.computeOccupiedArea=function(){return this.isVirtualized?this.viewportBounds.copy():this.Sg?fj(this):this.documentBounds.copy()};
function yk(a,b,c,d){null===a.Qb&&(a.Qb=new zk);if(a.Qb.ft||a.Qb.group!==c||a.Qb.Qx!==d){if(null===c){b=a.computeOccupiedArea();b.Xc(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&&Ak(a,f,d,b)}L.free(b)}else{0<c.memberParts.count&&(b=a.computePartsBounds(c.memberParts,!1),b.Xc(20,20),a.Qb.initialize(b));b=L.alloc();for(e=c.memberParts;e.next();)f=e.value,f instanceof V&&Ak(a,f,d,b);L.free(b)}a.Qb.group=c;a.Qb.Qx=d;a.Qb.ft=
!1}else b&&Bk(a.Qb);return a.Qb}function Ak(a,b,c,d){if(b!==c)if(b.isVisible()&&b.avoidable&&!b.isLinkLabel){var e=b.getAvoidableRect(d),f=a.Qb.Zl;c=a.Qb.Yl;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)Ck(a.Qb,g,h);Ck(a.Qb,g,b)}for(e=e.y;e<b;e+=c)Ck(a.Qb,d,e);Ck(a.Qb,d,b)}else if(b instanceof xg)for(b=b.memberParts;b.next();)e=b.value,e instanceof V&&Ak(a,e,c,d)}
function Dk(a,b){null!==a.Qb&&!a.Qb.ft&&(void 0===b&&(b=null),null===b||b.avoidable&&!b.isLinkLabel)&&(a.Qb.ft=!0)}t=P.prototype;t.Ts=function(a){this.Tq.assign(a);Ek(this,this.Tq).Sa(this.position)?this.yf():Fk(this)};
function Fk(a){-1===a.Gk&&(a.Gk=wa(function(){if(-1!==a.Gk&&(a.yf(),null!==a.lastInput.event)){var b=Ek(a,a.Tq);b.Sa(a.position)||(a.position=b,a.lastInput.documentPoint=a.Dt(a.Tq),a.doMouseMove(),a.Sg=!0,jj(a,a.documentBounds.copy().Lc(a.computeBounds())),a.oc=!0,a.hd(),Fk(a))}},a.Xm))}t.yf=function(){-1!==this.Gk&&(ra.clearTimeout(this.Gk),this.Gk=-1)};
function Ek(a,b){var c=a.position,d=a.Ym;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.Sa(gc)||(c=new J(c.x+g.x/f,c.y+g.y/f));L.free(e);J.free(g);return c}t.nt=function(){return null};t.tv=function(){return null};t.py=function(a,b){this.uu.add(a,b)};
function Gk(a,b,c){function d(){var a=+new Date;f=!0;for(g.reset();g.next();)if(!g.value[0].sl){f=!1;break}f||a-l>k?b(c,e,h):ra.requestAnimationFrame(d)}for(var e=c.callback,f=!0,g=a.Hj.iterator;g.next();)if(!g.value[0].sl){f=!1;break}if("function"!==typeof e||f)return b(c,e,a);var h=a,k=c.callbackTimeout||300,l=+new Date;ra.requestAnimationFrame(function(){d()});return null}t.Jz=function(a){if(!Ih)return null;void 0===a&&(a=new xb);a.returnType="Image";return this.xx(a)};
t.xx=function(a){void 0===a&&(a=new xb);return Gk(this,this.Kz,a)};
t.Kz=function(a,b,c){var d=Hk(c,a,"canvas",null);if(null===d)return null;c=d.Y.canvas;var e=null;if(null!==c)switch(e=a.returnType,void 0===e?e="string":e=e.toLowerCase(),e){case "imagedata":e=d.getImageData(0,0,c.width,c.height);break;case "image":d=(a.document||document).createElement("img");d.src=c.toDataURL(a.type,a.details);e=d;break;case "blob":"function"!==typeof b&&v('Error: Diagram.makeImageData called with "returnType: toBlob", but no required "callback" function property defined.');if("function"===
typeof c.toBlob)return c.toBlob(b,a.type,a.details),"toBlob";if("function"===typeof c.msToBlob)return b(c.msToBlob()),"msToBlob";b(null);return null;default:e=c.toDataURL(a.type,a.details)}return"function"===typeof b?(b(e),null):e};
function Hk(a,b,c,d){a.animationManager.xd();a.hd();if(null===a.Ea)return null;"object"!==typeof b&&v("properties argument must be an Object.");var e=!1,f=b.size||null,g=b.scale||null;void 0!==b.scale&&isNaN(b.scale)&&(g="NaN");var h=b.maxSize;void 0===b.maxSize&&(e=!0,h="SVG"===c?new Zb(Infinity,Infinity):new Zb(2E3,2E3));var k=b.position||null,l=b.parts||null,m=void 0===b.padding?1:b.padding,n=b.background||null,p=b.omitTemporary;void 0===p&&(p=!0);var q=b.document||document,r=b.elementFinished||
null,u=b.showTemporary;void 0===u&&(u=!p);b=b.showGrid;void 0===b&&(b=u);null!==f&&isNaN(f.width)&&isNaN(f.height)&&(f=null);"number"===typeof m?m=new Hc(m):m instanceof Hc||v("MakeImage padding must be a Margin or a number.");m.left=Math.max(m.left,0);m.right=Math.max(m.right,0);m.top=Math.max(m.top,0);m.bottom=Math.max(m.bottom,0);a.$c.Uc(!0);p=new Ik(null,q);var x=p.context;if(!(f||g||l||k)){p.width=a.Aa+Math.ceil(m.left+m.right);p.height=a.ya+Math.ceil(m.top+m.bottom);if("SVG"===c){if(null===
d)return null;d.resize(p.width,p.height,p.width,p.height);d.ownerDocument=q;d.Zp=r;Jj(a,d.context,m,new Zb(p.width,p.height),a.Da,a.ua,l,n,u,b);return d.context}a.Bn=!1;Jj(a,x,m,new Zb(p.width,p.height),a.Da,a.ua,l,n,u,b);a.Bn=!0;return p.context}var y=a.kr,A=a.documentBounds.copy();A.Vv(a.gb);if(u)for(var C=a.Ra.j,G=C.length,I=0;I<G;I++){var O=C[I];if(O.visible&&O.isTemporary){O=O.Ga.j;for(var R=O.length,U=0;U<R;U++){var ea=O[U];ea.isInDocumentBounds&&ea.isVisible()&&(ea=ea.actualBounds,ea.o()&&
A.Lc(ea))}}}C=new J(A.x,A.y);if(null!==l){G=!0;I=l.iterator;for(I.reset();I.next();)if(O=I.value,O instanceof T&&(R=O.layer,(null===R||R.visible)&&(null===R||u||!R.isTemporary)&&O.isVisible()&&(O=O.actualBounds,O.o())))if(G){G=!1;var Z=O.copy()}else Z.Lc(O);G&&(Z=new L(0,0,0,0));A.width=Z.width;A.height=Z.height;C.x=Z.x;C.y=Z.y}null!==k&&k.o()&&(C=k,g||(g=y));Z=k=0;null!==m&&(k=m.left+m.right,Z=m.top+m.bottom);G=I=0;null!==f&&(I=f.width,G=f.height,isFinite(I)&&(I=Math.max(0,I-k)),isFinite(G)&&(G=
Math.max(0,G-Z)));null!==f&&null!==g?("NaN"===g&&(g=y),f.o()?(f=I,A=G):isNaN(G)?(f=I,A=A.height*g):(f=A.width*g,A=G)):null!==f?f.o()?(g=Math.min(I/A.width,G/A.height),f=I,A=G):isNaN(G)?(g=I/A.width,f=I,A=A.height*g):(g=G/A.height,f=A.width*g,A=G):null!==g?"NaN"===g&&h.o()?(g=Math.min((h.width-k)/A.width,(h.height-Z)/A.height),g>y?(g=y,f=A.width,A=A.height):(f=h.width,A=h.height)):(f=A.width*g,A=A.height*g):(g=y,f=A.width,A=A.height);null!==m?(f+=k,A+=Z):m=new Hc(0);null!==h&&(y=h.width,h=h.height,
"SVG"!==c&&e&&!Jk&&E&&(f>y||A>h)&&(Ha("Diagram.makeImage(data): Diagram width or height is larger than the default max size. ("+Math.ceil(f)+"x"+Math.ceil(A)+" vs 2000x2000) Consider increasing the max size."),Jk=!0),isNaN(y)&&(y=2E3),isNaN(h)&&(h=2E3),isFinite(y)&&(f=Math.min(f,y)),isFinite(h)&&(A=Math.min(A,h)));p.width=Math.ceil(f);p.height=Math.ceil(A);if("SVG"===c){if(null===d)return null;d.resize(p.width,p.height,p.width,p.height);d.ownerDocument=q;d.Zp=r;Jj(a,d.context,m,new Zb(Math.ceil(f),
Math.ceil(A)),g,C,l,n,u,b);return d.context}a.Bn=!1;Jj(a,x,m,new Zb(Math.ceil(f),Math.ceil(A)),g,C,l,n,u,b);a.Bn=!0;return p.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){bb=[];var b=this.Ja;null!==b?(b.D=void 0,b.innerHTML="",null!==this.Ea&&(b=this.Ea.Ha,this.removeEventListener(b,"touchstart",this.$v,!1),this.removeEventListener(b,"touchmove",this.Zv,!1),this.removeEventListener(b,"touchend",this.Yv,!1),this.Ea.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.$c=this.Ea=null,this.removeEventListener(ra,"resize",this.fw,!1),this.removeEventListener(ra,"mousemove",this.nk,!0),this.removeEventListener(ra,"mousedown",this.mk,!0),this.removeEventListener(ra,"mouseup",this.qk,!0),this.removeEventListener(ra,"wheel",this.rk,!0),this.removeEventListener(ra,"mouseout",this.pk,!0),yf===this&&(yf=null)):
this.je=!1;this.Ja=null;if(null!==a){if(b=a.D)b.div=null;Pi(this,a);this.vf()}}}},$w:{configurable:!0,get:function(){return this.Ao}},rv:{configurable:!0,get:function(){return this.pb},set:function(a){this.pb=a}},Ui:{configurable:!0,get:function(){return this.je}},draggedLink:{configurable:!0,get:function(){return this.nr},set:function(a){this.nr!==a&&(this.nr=a,null!==a&&(this.js=a.fromPort,this.ks=a.toPort))}},Ax:{configurable:!0,
get:function(){return this.js},set:function(a){this.js=a}},Bx:{configurable:!0,get:function(){return this.ks},set:function(a){this.ks=a}},animationManager:{configurable:!0,get:function(){return this.Ek}},undoManager:{configurable:!0,get:function(){return this.ac.undoManager}},skipsUndoManager:{configurable:!0,get:function(){return this.fh},set:function(a){z(a,"boolean",P,"skipsUndoManager");this.fh=a;this.ac.skipsUndoManager=a}},delaysLayout:{configurable:!0,
enumerable:!0,get:function(){return this.Vt},set:function(a){this.Vt=a}},validCycle:{configurable:!0,get:function(){return this.Ls},set:function(a){var b=this.Ls;b!==a&&(tb(a,P,P,"validCycle"),this.Ls=a,this.g("validCycle",b,a))}},layers:{configurable:!0,get:function(){return this.Ra.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,
enumerable:!0,get:function(){return this.Of},set:function(a){var b=this.Of;b!==a&&(z(a,"boolean",P,"isReadOnly"),this.Of=a,this.g("isReadOnly",b,a))}},isEnabled:{configurable:!0,get:function(){return this.Fc},set:function(a){var b=this.Fc;b!==a&&(z(a,"boolean",P,"isEnabled"),this.Fc=a,this.g("isEnabled",b,a))}},allowClipboard:{configurable:!0,get:function(){return this.Kq},set:function(a){var b=this.Kq;b!==a&&(z(a,"boolean",P,"allowClipboard"),this.Kq=a,this.g("allowClipboard",
b,a))}},allowCopy:{configurable:!0,get:function(){return this.Hh},set:function(a){var b=this.Hh;b!==a&&(z(a,"boolean",P,"allowCopy"),this.Hh=a,this.g("allowCopy",b,a))}},allowDelete:{configurable:!0,get:function(){return this.Ih},set:function(a){var b=this.Ih;b!==a&&(z(a,"boolean",P,"allowDelete"),this.Ih=a,this.g("allowDelete",b,a))}},allowDragOut:{configurable:!0,get:function(){return this.Lq},set:function(a){var b=this.Lq;b!==a&&(z(a,"boolean",P,"allowDragOut"),
this.Lq=a,this.g("allowDragOut",b,a))}},allowDrop:{configurable:!0,get:function(){return this.Mq},set:function(a){var b=this.Mq;b!==a&&(z(a,"boolean",P,"allowDrop"),this.Mq=a,this.g("allowDrop",b,a))}},allowTextEdit:{configurable:!0,get:function(){return this.Rh},set:function(a){var b=this.Rh;b!==a&&(z(a,"boolean",P,"allowTextEdit"),this.Rh=a,this.g("allowTextEdit",b,a))}},allowGroup:{configurable:!0,get:function(){return this.Jh},set:function(a){var b=this.Jh;
b!==a&&(z(a,"boolean",P,"allowGroup"),this.Jh=a,this.g("allowGroup",b,a))}},allowUngroup:{configurable:!0,get:function(){return this.Sh},set:function(a){var b=this.Sh;b!==a&&(z(a,"boolean",P,"allowUngroup"),this.Sh=a,this.g("allowUngroup",b,a))}},allowInsert:{configurable:!0,get:function(){return this.Oq},set:function(a){var b=this.Oq;b!==a&&(z(a,"boolean",P,"allowInsert"),this.Oq=a,this.g("allowInsert",b,a))}},allowLink:{configurable:!0,get:function(){return this.Kh},
set:function(a){var b=this.Kh;b!==a&&(z(a,"boolean",P,"allowLink"),this.Kh=a,this.g("allowLink",b,a))}},allowRelink:{configurable:!0,get:function(){return this.Mh},set:function(a){var b=this.Mh;b!==a&&(z(a,"boolean",P,"allowRelink"),this.Mh=a,this.g("allowRelink",b,a))}},allowMove:{configurable:!0,get:function(){return this.Lh},set:function(a){var b=this.Lh;b!==a&&(z(a,"boolean",P,"allowMove"),this.Lh=a,this.g("allowMove",b,a))}},allowReshape:{configurable:!0,
get:function(){return this.Nh},set:function(a){var b=this.Nh;b!==a&&(z(a,"boolean",P,"allowReshape"),this.Nh=a,this.g("allowReshape",b,a))}},allowResize:{configurable:!0,get:function(){return this.Oh},set:function(a){var b=this.Oh;b!==a&&(z(a,"boolean",P,"allowResize"),this.Oh=a,this.g("allowResize",b,a))}},allowRotate:{configurable:!0,get:function(){return this.Ph},set:function(a){var b=this.Ph;b!==a&&(z(a,"boolean",P,"allowRotate"),this.Ph=a,this.g("allowRotate",b,a))}},
allowSelect:{configurable:!0,get:function(){return this.Qh},set:function(a){var b=this.Qh;b!==a&&(z(a,"boolean",P,"allowSelect"),this.Qh=a,this.g("allowSelect",b,a))}},allowUndo:{configurable:!0,get:function(){return this.Pq},set:function(a){var b=this.Pq;b!==a&&(z(a,"boolean",P,"allowUndo"),this.Pq=a,this.g("allowUndo",b,a))}},allowZoom:{configurable:!0,get:function(){return this.Rq},set:function(a){var b=this.Rq;b!==a&&(z(a,"boolean",P,"allowZoom"),this.Rq=
a,this.g("allowZoom",b,a))}},hasVerticalScrollbar:{configurable:!0,get:function(){return this.Cr},set:function(a){var b=this.Cr;b!==a&&(z(a,"boolean",P,"hasVerticalScrollbar"),this.Cr=a,wj(this),this.S(),this.g("hasVerticalScrollbar",b,a),gj(this,!1))}},hasHorizontalScrollbar:{configurable:!0,get:function(){return this.Br},set:function(a){var b=this.Br;b!==a&&(z(a,"boolean",P,"hasHorizontalScrollbar"),this.Br=a,wj(this),this.S(),this.g("hasHorizontalScrollbar",b,a),gj(this,
!1))}},allowHorizontalScroll:{configurable:!0,get:function(){return this.Nq},set:function(a){var b=this.Nq;b!==a&&(z(a,"boolean",P,"allowHorizontalScroll"),this.Nq=a,this.g("allowHorizontalScroll",b,a),gj(this,!1))}},allowVerticalScroll:{configurable:!0,get:function(){return this.Qq},set:function(a){var b=this.Qq;b!==a&&(z(a,"boolean",P,"allowVerticalScroll"),this.Qq=a,this.g("allowVerticalScroll",b,a),gj(this,!1))}},scrollHorizontalLineChange:{configurable:!0,
get:function(){return this.vs},set:function(a){var b=this.vs;b!==a&&(z(a,"number",P,"scrollHorizontalLineChange"),0>a&&Ca(a,">= 0",P,"scrollHorizontalLineChange"),this.vs=a,this.g("scrollHorizontalLineChange",b,a))}},scrollVerticalLineChange:{configurable:!0,get:function(){return this.xs},set:function(a){var b=this.xs;b!==a&&(z(a,"number",P,"scrollVerticalLineChange"),0>a&&Ca(a,">= 0",P,"scrollVerticalLineChange"),this.xs=a,this.g("scrollVerticalLineChange",b,a))}},lastInput:{configurable:!0,
enumerable:!0,get:function(){return this.vj},set:function(a){E&&w(a,kf,P,"lastInput");this.vj=a}},firstInput:{configurable:!0,get:function(){return this.$h},set:function(a){E&&w(a,kf,P,"firstInput");this.$h=a}},currentCursor:{configurable:!0,get:function(){return this.dr},set:function(a){""===a&&(a=this.un);if(this.dr!==a){z(a,"string",P,"currentCursor");var b=this.Ea,c=this.Ja;if(null!==b){this.dr=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,get:function(){return this.un},set:function(a){""===a&&(a="auto");var b=this.un;b!==a&&(z(a,"string",P,"defaultCursor"),this.un=a,this.g("defaultCursor",b,a))}},click:{configurable:!0,get:function(){return this.Df},set:function(a){var b=this.Df;b!==
a&&(null!==a&&z(a,"function",P,"click"),this.Df=a,this.g("click",b,a))}},doubleClick:{configurable:!0,get:function(){return this.If},set:function(a){var b=this.If;b!==a&&(null!==a&&z(a,"function",P,"doubleClick"),this.If=a,this.g("doubleClick",b,a))}},contextClick:{configurable:!0,get:function(){return this.Ef},set:function(a){var b=this.Ef;b!==a&&(null!==a&&z(a,"function",P,"contextClick"),this.Ef=a,this.g("contextClick",b,a))}},mouseOver:{configurable:!0,
get:function(){return this.Yf},set:function(a){var b=this.Yf;b!==a&&(null!==a&&z(a,"function",P,"mouseOver"),this.Yf=a,this.g("mouseOver",b,a))}},mouseHover:{configurable:!0,get:function(){return this.Wf},set:function(a){var b=this.Wf;b!==a&&(null!==a&&z(a,"function",P,"mouseHover"),this.Wf=a,this.g("mouseHover",b,a))}},mouseHold:{configurable:!0,get:function(){return this.Vf},set:function(a){var b=this.Vf;b!==a&&(null!==a&&z(a,"function",P,"mouseHold"),this.Vf=a,this.g("mouseHold",
b,a))}},mouseDragOver:{configurable:!0,get:function(){return this.cs},set:function(a){var b=this.cs;b!==a&&(null!==a&&z(a,"function",P,"mouseDragOver"),this.cs=a,this.g("mouseDragOver",b,a))}},mouseDrop:{configurable:!0,get:function(){return this.Tf},set:function(a){var b=this.Tf;b!==a&&(E&&null!==a&&z(a,"function",P,"mouseDrop"),this.Tf=a,this.g("mouseDrop",b,a))}},handlesDragDropForTopLevelParts:{configurable:!0,get:function(){return this.Ar},set:function(a){var b=
this.Ar;b!==a&&(z(a,"boolean",P,"handlesDragDropForTopLevelParts"),this.Ar=a,this.g("handlesDragDropForTopLevelParts",b,a))}},mouseEnter:{configurable:!0,get:function(){return this.Uf},set:function(a){var b=this.Uf;b!==a&&(null!==a&&z(a,"function",P,"mouseEnter"),this.Uf=a,this.g("mouseEnter",b,a))}},mouseLeave:{configurable:!0,get:function(){return this.Xf},set:function(a){var b=this.Xf;b!==a&&(null!==a&&z(a,"function",P,"mouseLeave"),this.Xf=a,this.g("mouseLeave",b,a))}},
toolTip:{configurable:!0,get:function(){return this.jg},set:function(a){var b=this.jg;b!==a&&(!E||null===a||a instanceof Cf||a instanceof Hf||v("Diagram.toolTip must be an Adornment or HTMLInfo."),this.jg=a,this.g("toolTip",b,a))}},contextMenu:{configurable:!0,get:function(){return this.Ff},set:function(a){var b=this.Ff;b!==a&&(!E||a instanceof Cf||a instanceof Hf||v("Diagram.contextMenu must be an Adornment or HTMLInfo."),this.Ff=a,this.g("contextMenu",b,a))}},commandHandler:{configurable:!0,
enumerable:!0,get:function(){return this.L},set:function(a){this.L!==a&&(this.L=a,a.ib(this))}},toolManager:{configurable:!0,get:function(){return this.Wb},set:function(a){this.Wb!==a&&(w(a,$a,P,"toolManager"),this.Wb=a,a.ib(this))}},defaultTool:{configurable:!0,get:function(){return this.Ma},set:function(a){var b=this.Ma;b!==a&&(w(a,vf,P,"defaultTool"),this.Ma=a,a.ib(this),this.currentTool===b&&(this.currentTool=a))}},currentTool:{configurable:!0,get:function(){return this.ca},
set:function(a){var b=this.ca;null!==b&&(b.isActive&&b.doDeactivate(),b.cancelWaitAfter(),b.doStop());null===a&&(a=this.defaultTool);null!==a&&(w(a,vf,P,"currentTool"),this.ca=a,a.ib(this),a.doStart())}},selection:{configurable:!0,get:function(){return this.Iq}},maxSelectionCount:{configurable:!0,get:function(){return this.Yr},set:function(a){var b=this.Yr;if(b!==a)if(z(a,"number",P,"maxSelectionCount"),0<=a&&!isNaN(a)){if(this.Yr=a,this.g("maxSelectionCount",b,a),!this.undoManager.isUndoingRedoing&&
(a=this.selection.count-a,0<a)){this.ba("ChangingSelection",this.selection);b=this.selection.Oa();for(var c=0;c<a;c++)b[c].isSelected=!1;this.ba("ChangedSelection",this.selection)}}else Ca(a,">= 0",P,"maxSelectionCount")}},nodeSelectionAdornmentTemplate:{configurable:!0,get:function(){return this.fs},set:function(a){var b=this.fs;b!==a&&(w(a,Cf,P,"nodeSelectionAdornmentTemplate"),this.fs=a,this.g("nodeSelectionAdornmentTemplate",b,a))}},groupSelectionAdornmentTemplate:{configurable:!0,
enumerable:!0,get:function(){return this.yr},set:function(a){var b=this.yr;b!==a&&(w(a,Cf,P,"groupSelectionAdornmentTemplate"),this.yr=a,this.g("groupSelectionAdornmentTemplate",b,a))}},linkSelectionAdornmentTemplate:{configurable:!0,get:function(){return this.Ur},set:function(a){var b=this.Ur;b!==a&&(w(a,Cf,P,"linkSelectionAdornmentTemplate"),this.Ur=a,this.g("linkSelectionAdornmentTemplate",b,a))}},highlighteds:{configurable:!0,get:function(){return this.Gq}},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||hk(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.");Si(this,!0);this.je=!1;this.bl=!0;this.ie=-2;this.sd=!1;var c=this.$b;this.$b=!0;this.animationManager.Dh("Model");null!==b&&(null!==this.re&&this.re.each(function(a){b.uk(a)}),b.uk(this.Hm));this.ac=a;this.partManager=ik(this.ac.constructor.type);a.sh(this.zg);this.partManager.addAllModeledParts();a.uk(this.zg);a.sh(this.Hm);null!==this.re&&this.re.each(function(b){a.sh(b)});this.$b=c;this.pb||this.S();null!==b&&a.undoManager.copyProperties(b.undoManager)}}},
fa:{configurable:!0,get:function(){return this.Oc},set:function(a){this.Oc=a}},lt:{configurable:!0,get:function(){return this.Hq}},skipsModelSourceBindings:{configurable:!0,get:function(){return this.Fh},set:function(a){this.Fh=a}},Zi:{configurable:!0,get:function(){return this.Bu},set:function(a){this.Bu=a}},nodeTemplate:{configurable:!0,get:function(){return this.Zf.K("")},set:function(a){var b=this.Zf.K("");b!==a&&(w(a,T,P,"nodeTemplate"),
this.Zf.add("",a),this.g("nodeTemplate",b,a),this.undoManager.isUndoingRedoing||this.wd())}},nodeTemplateMap:{configurable:!0,get:function(){return this.Zf},set:function(a){var b=this.Zf;b!==a&&(w(a,Ub,P,"nodeTemplateMap"),this.Zf=a,this.g("nodeTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.wd())}},groupTemplate:{configurable:!0,get:function(){return this.ai.K("")},set:function(a){var b=this.ai.K("");b!==a&&(w(a,xg,P,"groupTemplate"),this.ai.add("",a),this.g("groupTemplate",
b,a),this.undoManager.isUndoingRedoing||this.wd())}},groupTemplateMap:{configurable:!0,get:function(){return this.ai},set:function(a){var b=this.ai;b!==a&&(w(a,Ub,P,"groupTemplateMap"),this.ai=a,this.g("groupTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.wd())}},linkTemplate:{configurable:!0,get:function(){return this.Wg.K("")},set:function(a){var b=this.Wg.K("");b!==a&&(w(a,S,P,"linkTemplate"),this.Wg.add("",a),this.g("linkTemplate",b,a),this.undoManager.isUndoingRedoing||
this.wd())}},linkTemplateMap:{configurable:!0,get:function(){return this.Wg},set:function(a){var b=this.Wg;b!==a&&(w(a,Ub,P,"linkTemplateMap"),this.Wg=a,this.g("linkTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.wd())}},isMouseOverDiagram:{configurable:!0,get:function(){return this.Se},set:function(a){this.Se=a}},isMouseCaptured:{configurable:!0,get:function(){return this.Nc},set:function(a){var b=this.Ea;null!==b&&(b=b.Ha,b instanceof SVGElement||
(a?(this.lastInput.bubbles=!1,this.Sq?(this.removeEventListener(b,"pointermove",this.om,!1),this.removeEventListener(b,"pointerdown",this.nm,!1),this.removeEventListener(b,"pointerup",this.qm,!1),this.removeEventListener(b,"pointerout",this.pm,!1),this.addEventListener(ra,"pointermove",this.om,!0),this.addEventListener(ra,"pointerdown",this.nm,!0),this.addEventListener(ra,"pointerup",this.qm,!0),this.addEventListener(ra,"pointerout",this.pm,!0)):(this.removeEventListener(b,"mousemove",this.nk,!1),
this.removeEventListener(b,"mousedown",this.mk,!1),this.removeEventListener(b,"mouseup",this.qk,!1),this.removeEventListener(b,"mouseout",this.pk,!1),this.addEventListener(ra,"mousemove",this.nk,!0),this.addEventListener(ra,"mousedown",this.mk,!0),this.addEventListener(ra,"mouseup",this.qk,!0),this.addEventListener(ra,"mouseout",this.pk,!0)),this.removeEventListener(b,"wheel",this.rk,!1),this.addEventListener(ra,"wheel",this.rk,!0),this.addEventListener(ra,"selectstart",this.preventDefault,!1)):(this.Sq?
(this.removeEventListener(ra,"pointermove",this.om,!0),this.removeEventListener(ra,"pointerdown",this.nm,!0),this.removeEventListener(ra,"pointerup",this.qm,!0),this.removeEventListener(ra,"pointerout",this.pm,!0),this.addEventListener(b,"pointermove",this.om,!1),this.addEventListener(b,"pointerdown",this.nm,!1),this.addEventListener(b,"pointerup",this.qm,!1),this.addEventListener(b,"pointerout",this.pm,!1)):(this.removeEventListener(ra,"mousemove",this.nk,!0),this.removeEventListener(ra,"mousedown",
this.mk,!0),this.removeEventListener(ra,"mouseup",this.qk,!0),this.removeEventListener(ra,"mouseout",this.pk,!0),this.addEventListener(b,"mousemove",this.nk,!1),this.addEventListener(b,"mousedown",this.mk,!1),this.addEventListener(b,"mouseup",this.qk,!1),this.addEventListener(b,"mouseout",this.pk,!1)),this.removeEventListener(ra,"wheel",this.rk,!0),this.removeEventListener(ra,"selectstart",this.preventDefault,!1),this.addEventListener(b,"wheel",this.rk,!1)),this.Nc=a))}},position:{configurable:!0,
enumerable:!0,get:function(){return this.ua},set:function(a){var b=J.alloc().assign(this.ua);if(!b.A(a)){w(a,J,P,"position");var c=this.viewportBounds.copy();this.ua.assign(a);this.pb||null===this.Ea&&!this.Lp.o()||(this.pb=!0,a=this.scale,ij(this,this.zn,this.Aa/a,this.ya/a,this.hj,!1),this.pb=!1);si(this.animationManager,b,this.ua);this.pb||this.sq(c,this.viewportBounds,this.Da,!1)}J.free(b)}},initialPosition:{configurable:!0,get:function(){return this.Er},set:function(a){this.Er.A(a)||
(w(a,J,P,"initialPosition"),this.Er=a.J())}},initialScale:{configurable:!0,get:function(){return this.Fr},set:function(a){this.Fr!==a&&(z(a,"number",P,"initialScale"),this.Fr=a)}},grid:{configurable:!0,get:function(){null===this.Hb&&Xi(this);return this.Hb},set:function(a){var b=this.Hb;if(b!==a){null===b&&(Xi(this),b=this.Hb);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.Hb=a;a.name="GRID";
null!==c&&c.add(a);zj(this);this.S();this.g("grid",b,a)}}},viewportBounds:{configurable:!0,get:function(){var a=this.Sw,b=this.ua,c=this.Da;if(null===this.Ea)return this.Lp.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.Lp},set:function(a){var b=this.viewSize;b.A(a)||(w(a,Zb,P,"viewSize"),this.Lp=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.vr},set:function(a){var b=this.vr;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.vr=a=a.J(),this.Ya(),this.g("fixedBounds",b,a))}},scrollMargin:{configurable:!0,get:function(){return this.vi},set:function(a){"number"===typeof a?a=new Hc(a):w(a,Hc,P,"scrollMargin");var b=this.vi;
b.A(a)||(this.vi=a=a.J(),this.g("scrollMargin",b,a),this.vf())}},scrollMode:{configurable:!0,get:function(){return this.Lj},set:function(a){var b=this.Lj;b!==a&&(tb(a,P,P,"scrollMode"),this.Lj=a,a===Di&&gj(this,!1),this.g("scrollMode",b,a),this.vf())}},scrollsPageOnFocus:{configurable:!0,get:function(){return this.ys},set:function(a){var b=this.ys;b!==a&&(z(a,"boolean",P,"scrollsPageOnFocus"),this.ys=a,this.g("scrollsPageOnFocus",b,a))}},positionComputation:{configurable:!0,
enumerable:!0,get:function(){return this.ps},set:function(a){var b=this.ps;b!==a&&(null!==a&&z(a,"function",P,"positionComputation"),this.ps=a,gj(this,!1),this.g("positionComputation",b,a))}},scaleComputation:{configurable:!0,get:function(){return this.ts},set:function(a){var b=this.ts;b!==a&&(null!==a&&z(a,"function",P,"scaleComputation"),this.ts=a,fk(this,this.scale,this.scale),this.g("scaleComputation",b,a))}},documentBounds:{configurable:!0,get:function(){return this.zn}},
isVirtualized:{configurable:!0,get:function(){return this.Pr},set:function(a){var b=this.Pr;b!==a&&(z(a,"boolean",P,"isVirtualized"),this.Pr=a,this.g("isVirtualized",b,a))}},scale:{configurable:!0,get:function(){return this.Da},set:function(a){var b=this.Da;B(a,P,"scale");b!==a&&fk(this,b,a)}},defaultScale:{configurable:!0,get:function(){return this.kr},set:function(a){E&&B(a,P,"defaultScale");!E||0<a||v("defaultScale must be larger than zero, not: "+a);this.kr=
a}},autoScale:{configurable:!0,get:function(){return this.fj},set:function(a){var b=this.fj;b!==a&&(tb(a,P,P,"autoScale"),this.fj=a,this.g("autoScale",b,a),a!==Ei&&gj(this,!1))}},initialAutoScale:{configurable:!0,get:function(){return this.di},set:function(a){var b=this.di;b!==a&&(tb(a,P,P,"initialAutoScale"),this.di=a,this.g("initialAutoScale",b,a))}},initialViewportSpot:{configurable:!0,get:function(){return this.Gr},set:function(a){var b=this.Gr;b!==a&&
(w(a,M,P,"initialViewportSpot"),a.Za()||v("initialViewportSpot must be a specific Spot: "+a),this.Gr=a,this.g("initialViewportSpot",b,a))}},initialDocumentSpot:{configurable:!0,get:function(){return this.Dr},set:function(a){var b=this.Dr;b!==a&&(w(a,M,P,"initialDocumentSpot"),a.Za()||v("initialViewportSpot must be a specific Spot: "+a),this.Dr=a,this.g("initialDocumentSpot",b,a))}},minScale:{configurable:!0,get:function(){return this.Zr},set:function(a){B(a,P,"minScale");
var b=this.Zr;b!==a&&(0<a?(this.Zr=a,this.g("minScale",b,a),a>this.scale&&(this.scale=a)):Ca(a,"> 0",P,"minScale"))}},maxScale:{configurable:!0,get:function(){return this.Xr},set:function(a){B(a,P,"maxScale");var b=this.Xr;b!==a&&(0<a?(this.Xr=a,this.g("maxScale",b,a),a<this.scale&&(this.scale=a)):Ca(a,"> 0",P,"maxScale"))}},zoomPoint:{configurable:!0,get:function(){return this.Os},set:function(a){this.Os.A(a)||(w(a,J,P,"zoomPoint"),this.Os=a=a.J())}},contentAlignment:{configurable:!0,
enumerable:!0,get:function(){return this.hj},set:function(a){var b=this.hj;b.A(a)||(w(a,M,P,"contentAlignment"),this.hj=a=a.J(),this.g("contentAlignment",b,a),gj(this,!1))}},initialContentAlignment:{configurable:!0,get:function(){return this.Sn},set:function(a){var b=this.Sn;b.A(a)||(w(a,M,P,"initialContentAlignment"),this.Sn=a=a.J(),this.g("initialContentAlignment",b,a))}},padding:{configurable:!0,get:function(){return this.gb},set:function(a){"number"===typeof a?a=new Hc(a):
w(a,Hc,P,"padding");var b=this.gb;b.A(a)||(this.gb=a=a.J(),this.Ya(),this.g("padding",b,a))}},partManager:{configurable:!0,get:function(){return this.Na},set:function(a){var b=this.Na;b!==a&&(w(a,Ii,P,"partManager"),null!==a.diagram&&v("Cannot share PartManagers between Diagrams: "+a.toString()),null!==b&&b.ib(null),this.Na=a,a.ib(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.ic},set:function(a){var b=this.ic;b!==a&&(w(a,Ni,P,"layout"),this.ic=a,a.diagram=this,a.group=null,this.Dg=!0,this.g("layout",b,a),this.ec())}},isTreePathToChildren:{configurable:!0,get:function(){return this.Or},set:function(a){var b=this.Or;if(b!==a&&(z(a,"boolean",P,"isTreePathToChildren"),this.Or=a,this.g("isTreePathToChildren",
b,a),!this.undoManager.isUndoingRedoing))for(a=this.nodes;a.next();)Kk(a.value)}},treeCollapsePolicy:{configurable:!0,get:function(){return this.Js},set:function(a){var b=this.Js;b!==a&&(a!==Gi&&a!==Lk&&a!==Mk&&v("Unknown Diagram.treeCollapsePolicy: "+a),this.Js=a,this.g("treeCollapsePolicy",b,a))}},He:{configurable:!0,get:function(){return this.Xb},set:function(a){this.Xb=a}},autoScrollInterval:{configurable:!0,get:function(){return this.Xm},set:function(a){var b=
this.Xm;B(a,P,"scale");b!==a&&(this.Xm=a,this.g("autoScrollInterval",b,a))}},autoScrollRegion:{configurable:!0,get:function(){return this.Ym},set:function(a){"number"===typeof a?a=new Hc(a):w(a,Hc,P,"autoScrollRegion");var b=this.Ym;b.A(a)||(this.Ym=a=a.J(),this.Ya(),this.g("autoScrollRegion",b,a))}}});na.Object.defineProperties(P,{licenseKey:{configurable:!0,get:function(){return Nk.Ub()},set:function(a){Nk.add(a)}},version:{configurable:!0,get:function(){return Ok}}});
P.prototype.makeImageData=P.prototype.xx;P.prototype.makeImage=P.prototype.Jz;P.prototype.addRenderer=P.prototype.py;P.prototype.makeSVG=P.prototype.tv;P.prototype.makeSvg=P.prototype.nt;P.prototype.stopAutoScroll=P.prototype.yf;P.prototype.doAutoScroll=P.prototype.Ts;P.prototype.isUnoccupied=P.prototype.jk;P.prototype.raiseDiagramEvent=P.prototype.ba;P.prototype.removeDiagramListener=P.prototype.sm;P.prototype.addDiagramListener=P.prototype.Sj;P.prototype.findTreeRoots=P.prototype.iz;
P.prototype.layoutDiagram=P.prototype.Hz;P.prototype.findTopLevelGroups=P.prototype.bz;P.prototype.findTopLevelNodesAndLinks=P.prototype.cz;P.prototype.findLinksByExample=P.prototype.Ws;P.prototype.findNodesByExample=P.prototype.Xs;P.prototype.findLinkForData=P.prototype.wc;P.prototype.findNodeForData=P.prototype.Ji;P.prototype.findPartForData=P.prototype.xc;P.prototype.findNodeForKey=P.prototype.Kb;P.prototype.findPartForKey=P.prototype.findPartForKey;P.prototype.rebuildParts=P.prototype.wd;
P.prototype.transformViewToDoc=P.prototype.Dt;P.prototype.transformRectDocToView=P.prototype.hA;P.prototype.transformDocToView=P.prototype.Ct;P.prototype.centerRect=P.prototype.Ou;P.prototype.scrollToRect=P.prototype.Mv;P.prototype.scroll=P.prototype.scroll;P.prototype.highlightCollection=P.prototype.xz;P.prototype.highlight=P.prototype.wz;P.prototype.clearHighlighteds=P.prototype.Qu;P.prototype.selectCollection=P.prototype.Nv;P.prototype.select=P.prototype.select;P.prototype.clearSelection=P.prototype.Vp;
P.prototype.updateAllRelationshipsFromData=P.prototype.Dq;P.prototype.updateAllTargetBindings=P.prototype.updateAllTargetBindings;P.prototype.commit=P.prototype.commit;P.prototype.rollbackTransaction=P.prototype.xf;P.prototype.commitTransaction=P.prototype.ab;P.prototype.startTransaction=P.prototype.Ca;P.prototype.raiseChanged=P.prototype.g;P.prototype.raiseChangedEvent=P.prototype.cb;P.prototype.removeChangedListener=P.prototype.uk;P.prototype.addChangedListener=P.prototype.sh;
P.prototype.removeModelChangedListener=P.prototype.Xz;P.prototype.addModelChangedListener=P.prototype.Yw;P.prototype.findLayer=P.prototype.dm;P.prototype.removeLayer=P.prototype.Vz;P.prototype.addLayerAfter=P.prototype.ly;P.prototype.addLayerBefore=P.prototype.Ww;P.prototype.addLayer=P.prototype.Vl;P.prototype.moveParts=P.prototype.moveParts;P.prototype.copyParts=P.prototype.bk;P.prototype.removeParts=P.prototype.wt;P.prototype.remove=P.prototype.remove;P.prototype.add=P.prototype.add;
P.prototype.clearDelayedGeometries=P.prototype.Pu;P.prototype.setProperties=P.prototype.Tv;P.prototype.resetInputOptions=P.prototype.Jv;P.prototype.setInputOption=P.prototype.aA;P.prototype.getInputOption=P.prototype.gm;P.prototype.resetRenderingHints=P.prototype.Kv;P.prototype.setRenderingHint=P.prototype.Nx;P.prototype.getRenderingHint=P.prototype.Ge;P.prototype.maybeUpdate=P.prototype.hd;P.prototype.requestUpdate=P.prototype.ec;P.prototype.delayInitialization=P.prototype.Fy;
P.prototype.isUpdateRequested=P.prototype.Dz;P.prototype.redraw=P.prototype.vf;P.prototype.invalidateDocumentBounds=P.prototype.Ya;P.prototype.findObjectsNear=P.prototype.qg;P.prototype.findPartsNear=P.prototype.Zy;P.prototype.findObjectsIn=P.prototype.pg;P.prototype.findPartsIn=P.prototype.ox;P.prototype.findObjectsAt=P.prototype.Ki;P.prototype.findPartsAt=P.prototype.Yy;P.prototype.findObjectAt=P.prototype.Tb;P.prototype.findPartAt=P.prototype.em;P.prototype.alignDocument=P.prototype.qy;
P.prototype.zoomToRect=P.prototype.kA;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){Ih=a?void 0!==ra.document:!1};P.isUsingDOM=function(){return Ih};
var yf=null,Hi=new Ub,Vi=null,Ui=null,Ih=void 0!==ra.document,Qi=null,Ri="",Ei=new D(P,"None",0),kj=new D(P,"Uniform",1),lj=new D(P,"UniformToFill",2),Jg=new D(P,"CycleAll",10),Ng=new D(P,"CycleNotDirected",11),Pg=new D(P,"CycleNotDirectedFast",12),Qg=new D(P,"CycleNotUndirected",13),Kg=new D(P,"CycleDestinationTree",14),Mg=new D(P,"CycleSourceTree",15),Di=new D(P,"DocumentScroll",1),Mj=new D(P,"InfiniteScroll",2),Gi=new D(P,"TreeParentCollapsed",21),Lk=new D(P,"AllParentsCollapsed",22),Mk=new D(P,
"AnyParentsCollapsed",23),Nk=new F,Ok="2.0.12",Jk=!1,Pk=null,Bi=!1;
function Ci(){if(Ih){var a=ra.document.createElement("canvas"),b=a.getContext("2d"),c=eb("7ca11abfd022028846");b[c]=eb("398c3597c01238");for(var d=["5da73c80a36455d4038e4972187c3cae51fd22",sa.Dx+"4ae6247590da4bb21c324ba3a84e385776",$b.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);Pk=a}}P.className="Diagram";
P.fromDiv=function(a){var b=a;"string"===typeof a&&(b=ra.document.getElementById(a));return b instanceof HTMLDivElement&&b.D instanceof P?b.D: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=Ei;P.Uniform=kj;P.UniformToFill=lj;P.CycleAll=Jg;P.CycleNotDirected=Ng;
P.CycleNotDirectedFast=Pg;P.CycleNotUndirected=Qg;P.CycleDestinationTree=Kg;P.CycleSourceTree=Mg;P.DocumentScroll=Di;P.InfiniteScroll=Mj;P.TreeParentCollapsed=Gi;P.AllParentsCollapsed=Lk;P.AnyParentsCollapsed=Mk;function Oi(){this.gy=null;this.l="zz@orderNum";"63ad05bbe23a1786468a4c741b6d2"===this._tk?this.Pe=this.l=!0:this.Pe=null}
function Ij(a,b){b.$c.setTransform(b.Pb,0,0,b.Pb,0,0);if(null===a.Pe){b="f";var c=ra[eb("76a715b2f73f148a")][eb("72ba13b5")];a.Pe=!0;if(Ih){var d=P[eb("76a115b6ed251eaf4692")];if(d)for(var e=Nk.iterator;e.next();){d=e.value;d=eb(d).split(eb("39e9"));if(6>d.length)break;var f=eb(d[1]).split(".");if("7da71ca0"!==d[4])break;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];f=b[eb("73a612b6fb191d")](eb(d[2]));
0>f&&eb(d[2])!==eb("7da71ca0ad381e90")&&(f=b[eb("73a612b6fb191d")](eb("76a715b2ef3e149757")));0>f&&(f=b[eb("73a612b6fb191d")](eb("76a715b2ef3e149757")));a.Pe=!(0<=f&&f<b[eb("73a612b6fb191d")](eb("35")));if(!a.Pe)break;f=eb(d[2]);if("#"!==f[0])break;g=ra.document.createElement("div");for(var h=d[0].replace(/[A-Za-z]/g,"");4>h.length;)h+="9";h=h.substr(h.length-4);d="";d+=["gsh","gsf"][parseInt(h.substr(0,1),10)%2];d+=["Header","Background","Display","Feedback"][parseInt(h.substr(0,1),10)%4];g[eb("79a417a0f0181a8946")]=
d;if(ra.document[eb("78a712aa")]){ra.document[eb("78a712aa")][eb("7bb806b6ed32388c4a875b")](g);h=ra.getComputedStyle(g).getPropertyValue(eb("78a704b7e62456904c9b12701b6532a8"));ra.document[eb("78a712aa")][eb("68ad1bbcf533388c4a875b")](g);if(!h)break;if(-1!==h.indexOf(parseInt(f[1]+f[2],16))&&-1!==h.indexOf(parseInt(f[3]+f[4],16))){a.Pe=!1;break}else if(fb||gb||ib||jb)for(d="."+d,f=0;f<document.styleSheets.length;f++){g=document.styleSheets[f].rules||document.styleSheets[f].cssRules;for(var k in g)if(d===
g[k].selectorText){a.Pe=!1;break}}}else a.Pe=null,a.Pe=!1}}else{k=c[eb("76ad18b4f73e")];for(e=c[eb("73a612b6fb191d")](eb("35e7"))+2;e<k;e++)b+=c[e];c=b[eb("73a612b6fb191d")](eb("7da71ca0ad381e90"));a.Pe=!(0<=c&&c<b[eb("73a612b6fb191d")](eb("35")))}}}return 0<a.Pe&&a!==a.gy?!0:!1}
function Pi(a,b){if(Ih){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.D&&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.D=a;var c=a.Gs?new Nj(a):new Ik(a);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.Xn=!0),c.style.zIndex="2",c.style.userSelect="none",c.style.webkitUserSelect="none",c.style.MozUserSelect="none");a.Ea=c;a.$c=c.context;b=a.$c;a.Pb=a.computePixelRatio();a.Aa=a.Ja.clientWidth||
1;a.ya=a.Ja.clientHeight||1;Pj(a,a.Aa,a.ya);a.pr=b.Y[eb("7eba17a4ca3b1a8346")][eb("78a118b7")](b.Y,Pk,4,4);a.Ja.insertBefore(c.Ha,a.Ja.firstChild);c=new Ik(null);c.width=1;c.height=1;a.Zt=c;a.zw=c.context;if(Ih){c=ya("div");var d=ya("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=Yi;c.onmousedown=cj;c.ontouchstart=
cj;c.D=a;c.by=!0;c.ey=!0;a.ws=c;a.mp=d}a.tt=va(function(){a.kh=null;a.S()},300);a.fw=va(function(){hi(a)},250);a.preventDefault=function(a){a.preventDefault();return!1};a.nk=function(b){if(a.isEnabled){a.Se=!0;var c=pj(a,b,!0);a.doMouseMove();a.currentTool.isBeyondDragSize()&&(a.Hd=0);vj(a,c,b)}};a.mk=function(b){if(a.isEnabled)if(a.Se=!0,a.Te)b.preventDefault();else{var c=pj(a,b,!0);c.down=!0;c.clickCount=b.detail;if(gb||ib)b.timeStamp-a.pl<a.Gu&&!a.currentTool.isBeyondDragSize()?a.Hd++:a.Hd=1,a.pl=
b.timeStamp,c.clickCount=a.Hd;c.clone(a.firstInput);a.doMouseDown();1===b.button?b.preventDefault():vj(a,c,b)}};a.qk=function(b){if(a.isEnabled)if(a.Te&&2===b.button)b.preventDefault();else if(a.Te&&0===b.button&&(a.Te=!1),a.Rl)b.preventDefault();else{a.Se=!0;var c=pj(a,b,!0);c.up=!0;c.clickCount=b.detail;if(gb||ib)c.clickCount=a.Hd;c.bubbles=b.bubbles;c.targetDiagram=rj(b);a.doMouseUp();a.yf();vj(a,c,b)}};a.rk=function(b){if(a.isEnabled){var c=pj(a,b,!0);c.bubbles=!0;var d=0,e=0;c.delta=0;void 0!==
b.deltaX?(0!==b.deltaX&&(d=0<b.deltaX?1:-1),0!==b.deltaY&&(e=0<b.deltaY?1:-1),c.delta=Math.abs(b.deltaX)>Math.abs(b.deltaY)?-d:-e):void 0!==b.wheelDeltaX?(0!==b.wheelDeltaX&&(d=0<b.wheelDeltaX?-1:1),0!==b.wheelDeltaY&&(e=0<b.wheelDeltaY?-1:1),c.delta=Math.abs(b.wheelDeltaX)>Math.abs(b.wheelDeltaY)?-d:-e):void 0!==b.wheelDelta&&0!==b.wheelDelta&&(c.delta=0<b.wheelDelta?1:-1);a.doMouseWheel();vj(a,c,b)}};a.pk=function(b){a.isEnabled&&(a.Se=!1,pj(a,b,!0),b=a.currentTool,b.cancelWaitAfter(),b.standardMouseOver())};
a.$v=function(b){if(a.isEnabled){a.Rl=!1;a.Te=!0;var c=sj(a,b,b.targetTouches[0],1<b.touches.length),d=null;0<b.targetTouches.length?d=b.targetTouches[0]:0<b.changedTouches.length&&(d=b.changedTouches[0]);if(null!==d){var e=d.screenX;d=d.screenY;var k=a.Rr;b.timeStamp-a.pl<a.Gu&&!(25<Math.abs(k.x-e)||25<Math.abs(k.y-d))?a.Hd++:a.Hd=1;c.clickCount=a.Hd;a.pl=b.timeStamp;a.Rr.h(e,d)}a.doMouseDown();vj(a,c,b)}};a.Zv=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=uj(a,b,c,1<b.touches.length);a.doMouseMove();vj(a,c,b)}};a.Yv=function(b){if(a.isEnabled)if(a.Rl)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=tj(a,b,!1,!0,!1,!1);null!==d&&(c=ra.document.elementFromPoint(d.clientX,d.clientY),null!==c&&c.D instanceof P&&c.D!==a&&qj(c.D,d,e),qj(a,d,e),e.clickCount=a.Hd);null===c?e.targetDiagram=
rj(b):c.D?e.targetDiagram=c.D:e.targetDiagram=null;e.targetObject=null;a.doMouseUp();vj(a,e,b);a.Te=!1}};a.nm=function(b){if(a.isEnabled){a.Se=!0;var c=a.su;void 0===c[b.pointerId]&&(c[b.pointerId]=b);c=a.Al;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.Rl=!1,a.Te=!0;c=sj(a,b,b,d);
d=a.Rr;var e="touch"===b.pointerType||"pen"===b.pointerType?25:10;b.timeStamp-a.pl<a.Gu&&!(Math.abs(d.x-b.screenX)>e||Math.abs(d.y-b.screenY)>e)?a.Hd++:a.Hd=1;c.clickCount=a.Hd;a.pl=b.timeStamp;a.Rr.wg(b.screenX,b.screenY);a.doMouseDown();1===b.button?b.preventDefault():vj(a,c,b)}};a.om=function(b){if(a.isEnabled){a.Se=!0;var c=a.Al;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=uj(a,b,b,null!==c[1]),a.doMouseMove(),vj(a,c,b))}};a.qm=function(b){if(a.isEnabled){a.Se=!0;var c="touch"===b.pointerType||"pen"===b.pointerType,d=a.su;if(c&&a.Rl)delete d[b.pointerId],b.preventDefault();else if(d=a.Al,null!==d[0]&&d[0].pointerId===b.pointerId){d[0]=null;d=tj(a,b,!1,!0,!0,!1);var e=ra.document.elementFromPoint(b.clientX,b.clientY);null!==e&&e.D instanceof P&&e.D!==a&&qj(e.D,b,d);qj(a,b,d);d.clickCount=a.Hd;null===e?d.targetDiagram=rj(b):e.D?d.targetDiagram=e.D:d.targetDiagram=
null;d.targetObject=null;a.doMouseUp();vj(a,d,b);c&&(a.Te=!1)}else null!==d[1]&&d[1].pointerId===b.pointerId&&(d[1]=null)}};a.pm=function(b){if(a.isEnabled){a.Se=!1;var c=a.su;c[b.pointerId]&&delete c[b.pointerId];c=a.Al;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.Uc(!0);Wi(a)}}Oi.className="DiagramHelper";
function bg(a){this.l=void 0===a?new J:a;this.w=new J}na.Object.defineProperties(bg.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}}});bg.className="DraggingInfo";function ak(a,b,c){this.node=a;this.info=b;this.mv=c}ak.className="DraggingNodeInfoPair";function Lf(){this.reset()}
Lf.prototype.reset=function(){this.isGridSnapEnabled=!1;this.isGridSnapRealtime=!0;this.gridSnapCellSize=(new Zb(NaN,NaN)).freeze();this.gridSnapCellSpot=fd;this.gridSnapOrigin=(new J(NaN,NaN)).freeze();this.uz=this.dragsTree=this.dragsLink=!1};function Qk(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=gd;this.layout=new Rk}ma(Qk,P);
Qk.className="Palette";
function Sk(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.pb=!0;this.$f=null;this.qr=!0;this.Nx("drawShadows",!1);var b=new T,c=new Hg;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 Hc(0,0,0,0);this.Du=new Ik(null);this.hy=this.Du.context;If(this.toolManager,"Dragging",new Tk,this.toolManager.mouseMoveTools);var d=this;this.click=function(){var a=d.$f;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.Lm=function(){d.Ya();Uk(d)};this.Jm=function(){null!==d.$f&&(d.Ya(),d.S())};this.Km=function(){d.S()};this.Im=function(){null!==
d.$f&&Uk(d)};this.autoScale=kj;this.pb=!1}ma(Sk,P);
function Vk(a){a.pb||a.$b||!1!==a.sd||(a.sd=!0,ra.requestAnimationFrame(function(){if(a.sd&&!a.$b&&(a.sd=!1,null!==a.Ja)){a.$b=!0;ej(a);a.documentBounds.o()||jj(a,a.computeBounds());null===a.Ja&&v("No div specified");null===a.Ea&&v("No canvas specified");vi(a.box);if(a.oc){var b=a.$f;if(null!==b&&!b.animationManager.isAnimating&&!b.animationManager.sb){b=a.$c;var c=a.Du;b.setTransform(1,0,0,1,0,0);b.clearRect(0,0,a.Ea.width,a.Ea.height);b.drawImage(c.Ha,0,0);c=a.ub;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.Pb,a.Pb);b.transform(c.m11,c.m12,c.m21,c.m22,c.dx,c.dy);c=a.Ra.j;for(var d=c.length,e=0;e<d;e++)c[e].jc(b,a);a.ei=!1;a.oc=!1}}a.$b=!1}}))}Sk.prototype.computePixelRatio=function(){return 1};
Sk.prototype.jc=function(){null===this.Ja&&v("No div specified");null===this.Ea&&v("No canvas specified");if(!(this.Ea instanceof Nj)&&(vi(this.box),this.oc)){var a=this.$f;if(null!==a&&!a.animationManager.isAnimating){Gj(this);var b=a.grid;null===b||!b.visible||isNaN(b.width)||isNaN(b.height)||(b=L.alloc().assign(this.viewportBounds).Lc(a.viewportBounds),zj(a,b),L.free(b),ej(a));var c=this.Ea;b=this.$c;var d=this.Du,e=this.hy;d.width=c.width;d.height=c.height;b.Uc(!0);b.setTransform(1,0,0,1,0,0);
b.clearRect(0,0,c.width,c.height);var f=this.ub;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.Pb,this.Pb);b.transform(f.m11,f.m12,f.m21,f.m22,f.dx,f.dy);var g=this.qr,h=this.viewportBounds;a=a.Ra.j;for(var k=a.length,l=0;l<k;l++){var m=a[l],n=g;if(m.visible&&0!==m.mb&&(void 0===n&&(n=!0),n||!m.isTemporary)){1!==m.mb&&(b.globalAlpha=m.mb);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.Kc(h)&&(u.width*n>this.qe||u.height*n>this.qe?r.jc(b,this):xi(b,r))}b.globalAlpha=1}}e.drawImage(c.Ha,0,0);E&&E.Gi&&(e.fillStyle="red",e.fillRect(0,d.height/2,d.width,4));c=this.Ra.j;d=c.length;for(e=0;e<d;e++)c[e].jc(b,this);E&&(E.$u||E.Gi)&&E.Yp&&E.Yp(b,this,f);this.oc=this.ei=!1}}};
function Uk(a){var b=a.box;if(null!==b){var c=a.$f;if(null!==c){a.oc=!0;c=c.viewportBounds;var d=b.selectionObject,e=Zb.alloc();e.h(c.width,c.height);d.desiredSize=e;Zb.free(e);a=2/a.scale;d instanceof Hg&&(d.strokeWidth=a);b.location=new J(c.x-a/2,c.y-a/2);b.isSelected=!0}}}Sk.prototype.computeBounds=function(){var a=this.$f;if(null===a)return Tc;var b=a.documentBounds.copy();b.Lc(a.viewportBounds);return b};Sk.prototype.ux=function(){!0!==this.oc&&(this.oc=!0,Vk(this))};
Sk.prototype.sq=function(a,b,c,d){this.pb||(dj(this),this.S(),wj(this),this.Ya(),Uk(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(Sk.prototype,{observed:{configurable:!0,get:function(){return this.$f},set:function(a){var b=this.$f;null!==a&&w(a,P,Sk,"observed");a instanceof Sk&&v("Overview.observed Diagram may not be an Overview itself: "+a);b!==a&&(null!==b&&(this.remove(this.box),b.sm("ViewportBoundsChanged",this.Lm),b.sm("DocumentBoundsChanged",this.Jm),b.sm("InvalidateDraw",this.Km),b.sm("AnimationFinished",this.Im)),this.$f=a,null!==a&&(a.Sj("ViewportBoundsChanged",this.Lm),a.Sj("DocumentBoundsChanged",
this.Jm),a.Sj("InvalidateDraw",this.Km),a.Sj("AnimationFinished",this.Im),this.add(this.box),Uk(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),Uk(this),this.g("box",b,a))}},drawsTemporaryLayers:{configurable:!0,get:function(){return this.qr},set:function(a){this.qr!==a&&(this.qr=a,this.vf())}}});Sk.className="Overview";
function Tk(){Kf.call(this);this.l=null}ma(Tk,Kf);
Tk.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};
Tk.prototype.doActivate=function(){this.l=null;Kf.prototype.doActivate.call(this)};Tk.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)}}};Tk.className="OverviewDraggingTool";
function Wk(){0<arguments.length&&Da(Wk);qb(this);this.D=yf;this.Wb=this.L=this.w=!0;this.ca=this.Ma=this.Xb=this.Na=!1;this.mi=this.l=null;this.Oc=1.05;this.ju=NaN;this.Fw=null;this.Ju=NaN;this.Iu=Tc;this.fg=null;this.Nc=200}Wk.prototype.toString=function(){return"CommandHandler"};Wk.prototype.ib=function(a){this.D=a};
Wk.prototype.doKeyDown=function(){var a=this.diagram,b=a.lastInput,c=kb?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()};
Wk.prototype.doKeyUp=function(){this.diagram.lastInput.bubbles=!0};Wk.prototype.stopCommand=function(){var a=this.diagram,b=a.currentTool;b instanceof $a&&a.allowSelect&&a.Vp();null!==b&&b.doCancel()};Wk.prototype.canStopCommand=function(){return!0};
Wk.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=""}};Wk.prototype.canSelectAll=function(){return this.diagram.allowSelect};
Wk.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();)Xk(b,c.value,!0,this.deletesTree?Infinity:0,this.deletesConnectedLinks?null:!1,function(a){return a.canDelete()});E&&!0===E.animationExperiments&&a.animationManager.Dh("Remove",{duration:300,Py:fi});a.wt(b,!0);a.ba("SelectionDeleted",b)}finally{a.ba("ChangedSelection",a.selection),
a.ab("Delete"),a.currentCursor=""}};Wk.prototype.canDeleteSelection=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowDelete||0===a.selection.count?!1:!0};Wk.prototype.copySelection=function(){var a=this.diagram,b=new H;for(a=a.selection.iterator;a.next();)Xk(b,a.value,!0,this.copiesTree?Infinity:0,this.copiesConnectedLinks,function(a){return a.canCopy()});this.copyToClipboard(b)};
Wk.prototype.canCopySelection=function(){var a=this.diagram;return a.allowCopy&&a.allowClipboard&&0!==a.selection.count?!0:!1};Wk.prototype.cutSelection=function(){this.copySelection();this.deleteSelection()};Wk.prototype.canCutSelection=function(){var a=this.diagram;return!a.isReadOnly&&!a.isModelReadOnly&&a.allowCopy&&a.allowDelete&&a.allowClipboard&&0!==a.selection.count?!0:!1};
Wk.prototype.copyToClipboard=function(a){var b=this.diagram,c=null;if(null===a)Qi=null,Ri="";else{c=b.model;var d=!1,e=!1,f=null;try{c.km()&&(d=c.ak,c.ak=this.copiesParentKey),c.ik()&&(e=c.$j,c.$j=this.copiesGroupKey),f=b.bk(a,null,!0)}finally{c.km()&&(c.ak=d),c.ik()&&(c.$j=e),c=new F,c.addAll(f),Qi=c,Ri=b.model.dataFormat}}b.ba("ClipboardChanged",c)};
Wk.prototype.pasteFromClipboard=function(){var a=new H,b=Qi;if(null===b)return a;var c=this.diagram;if(Ri!==c.model.dataFormat)return a;var d=c.model,e=!1,f=!1,g=null;try{d.km()&&(e=d.ak,d.ak=this.copiesParentKey),d.ik()&&(f=d.$j,d.$j=this.copiesGroupKey),g=c.bk(b,c,!1)}finally{for(d.km()&&(d.ak=e),d.ik()&&(d.$j=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};
Wk.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&&Mf(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.Qk);pg(b,f,new J(a.x-e.centerX,a.y-e.centerY),b.Qk,!1)}}b.ba("ClipboardPasted",c)}finally{b.ab("Paste"),
b.currentCursor=""}};Wk.prototype.canPasteSelection=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowClipboard||null===Qi||0===Qi.count||Ri!==a.model.dataFormat?!1:!0};Wk.prototype.undo=function(){this.diagram.undoManager.undo()};Wk.prototype.canUndo=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly?!1:a.allowUndo&&a.undoManager.canUndo()};Wk.prototype.redo=function(){this.diagram.undoManager.redo()};
Wk.prototype.canRedo=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly?!1:a.allowUndo&&a.undoManager.canRedo()};Wk.prototype.decreaseZoom=function(a){void 0===a&&(a=1/this.zoomFactor);B(a,Wk,"decreaseZoom:factor");var b=this.diagram;b.autoScale===Ei&&(a=b.scale*a,a<b.minScale||a>b.maxScale||(b.scale=a))};
Wk.prototype.canDecreaseZoom=function(a){void 0===a&&(a=1/this.zoomFactor);B(a,Wk,"canDecreaseZoom:factor");var b=this.diagram;if(b.autoScale!==Ei)return!1;a=b.scale*a;return a<b.minScale||a>b.maxScale?!1:b.allowZoom};Wk.prototype.increaseZoom=function(a){void 0===a&&(a=this.zoomFactor);B(a,Wk,"increaseZoom:factor");var b=this.diagram;b.autoScale===Ei&&(a=b.scale*a,a<b.minScale||a>b.maxScale||(b.scale=a))};
Wk.prototype.canIncreaseZoom=function(a){void 0===a&&(a=this.zoomFactor);B(a,Wk,"canIncreaseZoom:factor");var b=this.diagram;if(b.autoScale!==Ei)return!1;a=b.scale*a;return a<b.minScale||a>b.maxScale?!1:b.allowZoom};Wk.prototype.resetZoom=function(a){void 0===a&&(a=this.defaultScale);B(a,Wk,"resetZoom:newscale");var b=this.diagram;a<b.minScale||a>b.maxScale||(b.scale=a)};
Wk.prototype.canResetZoom=function(a){void 0===a&&(a=this.defaultScale);B(a,Wk,"canResetZoom:newscale");var b=this.diagram;return a<b.minScale||a>b.maxScale?!1:b.allowZoom};Wk.prototype.zoomToFit=function(){var a=this.diagram,b=a.scale,c=a.position;b===this.Ju&&!isNaN(this.ju)&&a.documentBounds.A(this.Iu)?(a.scale=this.ju,a.position=this.Fw,this.Ju=NaN,this.Iu=Tc):(this.ju=b,this.Fw=c.copy(),a.zoomToFit(),this.Ju=a.scale,this.Iu=a.documentBounds.copy())};Wk.prototype.canZoomToFit=function(){return this.diagram.allowZoom};
Wk.prototype.scrollToPart=function(a){void 0===a&&(a=null);null!==a&&w(a,T,Wk,"part");var b=this.diagram;if(null===a){try{null!==this.fg&&(this.fg.next()?a=this.fg.value:this.fg=null)}catch(k){this.fg=null}null===a&&(0<b.highlighteds.count?this.fg=b.highlighteds.iterator:0<b.selection.count&&(this.fg=b.selection.iterator),null!==this.fg&&this.fg.next()&&(a=this.fg.value))}if(null!==a){var c=b.animationManager;c.Dh("Scroll To Part");var d=this.scrollToPartPause;if(0<d){var e=Yk(this,a,[a]),f=function(){b.Ca();
for(var a=e.pop();0<e.length&&a instanceof V&&a.isTreeExpanded&&(!(a instanceof xg)||a.isSubGraphExpanded);)a=e.pop();0<e.length?(a instanceof T&&b.Mv(a.actualBounds),a instanceof V&&!a.isTreeExpanded&&(a.isTreeExpanded=!0),a instanceof xg&&!a.isSubGraphExpanded&&(a.isSubGraphExpanded=!0)):(a instanceof T&&b.Ou(a.actualBounds),b.sm("LayoutCompleted",g));b.ab("Scroll To Part")},g=function(){wa(f,(c.isEnabled?c.duration:0)+d)};b.Sj("LayoutCompleted",g);f()}else{var h=b.position.copy();b.Ou(a.actualBounds);
h.Sa(b.position)&&c.xd()}}};function Yk(a,b,c){if(b.isVisible())return c;if(b instanceof Cf)Yk(a,b.adornedPart,c);else if(b instanceof S){var d=b.fromNode;null!==d&&Yk(a,d,c);b=b.toNode;null!==b&&Yk(a,b,c)}else b instanceof V&&(d=b.labeledLink,null!==d&&Yk(a,d,c),d=b.rg(),null!==d&&(d.isTreeExpanded||d.wasTreeExpanded||c.push(d),Yk(a,d,c))),b=b.containingGroup,null!==b&&(b.isSubGraphExpanded||b.wasSubGraphExpanded||c.push(b),Yk(a,b,c));return c}
Wk.prototype.canScrollToPart=function(a){void 0===a&&(a=null);if(null!==a&&!(a instanceof T))return!1;a=this.diagram;return 0===a.selection.count&&0===a.highlighteds.count?!1:a.allowHorizontalScroll&&a.allowVerticalScroll};
Wk.prototype.collapseTree=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Collapse Tree");b.animationManager.Dh("Collapse Tree");var c=new F;if(null!==a&&a.isTreeExpanded)a.collapseTree(),c.add(a);else if(null===a)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.ab("Collapse Tree")}};
Wk.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.cq().count)return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof V&&b.isTreeExpanded&&0<b.cq().count)return!0;return!1};
Wk.prototype.expandTree=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Expand Tree");b.animationManager.Dh("Expand Tree");var c=new F;if(null!==a&&!a.isTreeExpanded)a.expandTree(),c.add(a);else if(null===a)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof V&&!e.isTreeExpanded&&(e.expandTree(),c.add(e))}b.ba("TreeExpanded",c)}finally{b.ab("Expand Tree")}};
Wk.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.cq().count)return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof V&&!b.isTreeExpanded&&0<b.cq().count)return!0;return!1};
Wk.prototype.groupSelection=function(){var a=this.diagram,b=a.model;if(b.Ti()){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 F,f=a.selection.iterator;f.next();){var g=f.value;g.dc()&&g.canGroup()&&e.add(g)}for(var h=new F,k=e.iterator;k.next();){var l=k.value;f=!1;for(var m=e.iterator;m.next();)if(l.Xd(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.Xd(n)){e=!0;break}if(e)n=n.containingGroup;else break}if(c instanceof xg)mh(c),d=c.copy(),null!==d&&a.add(d);else if(b.ht(c)){var q=b.copyNodeData(c);Ja(q)&&(b.lf(q),d=a.Ji(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.ab("Group"),a.currentCursor=
""}}}};Wk.prototype.canGroupSelection=function(){var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowGroup||!a.model.Ti()||null===this.archetypeGroupData)return!1;for(a=a.selection.iterator;a.next();){var b=a.value;if(b.dc()&&b.canGroup())return!0}return!1};
function Zk(a){var b=Qa();for(a=a.iterator;a.next();){var c=a.value;c instanceof S||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.Xd(b[g])){f=!1;break}f&&a.add(e)}Ta(b);return a}
Wk.prototype.isValidMember=function(a,b){if(null===b||a===b||b instanceof S)return!1;if(null!==a){if(a===b||a.Xd(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};
Wk.prototype.ungroupSelection=function(a){void 0===a&&(a=null);var b=this.diagram,c=b.model;if(c.Ti())try{b.currentCursor="wait";b.Ca("Ungroup");b.ba("ChangingSelection",b.selection);var d=new F;if(null!==a)d.add(a);else for(var e=b.selection.iterator;e.next();){var f=e.value;f instanceof xg&&f.canUngroup()&&d.add(f)}var g=new F;if(0<d.count){b.Vp();for(var h=d.iterator;h.next();){var k=h.value;k.expandSubGraph();var l=k.containingGroup,m=null!==l&&null!==l.data?c.ra(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 S)){var q=p.data;null!==q?c.zt(q,m):p.containingGroup=l}}b.remove(k)}}b.ba("ChangedSelection",b.selection);b.ba("SelectionUngrouped",d,g)}finally{b.ab("Ungroup"),b.currentCursor=""}};
Wk.prototype.canUngroupSelection=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly||b.isModelReadOnly||!b.allowDelete||!b.allowUngroup||!b.model.Ti())return!1;if(null!==a){if(!(a instanceof xg))return!1;if(a.canUngroup())return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof xg&&b.canUngroup())return!0;return!1};
Wk.prototype.addTopLevelParts=function(a,b){var c=!0;for(a=Zk(a).iterator;a.next();){var d=a.value;null!==d.containingGroup&&(!b||this.isValidMember(null,d)?d.containingGroup=null:c=!1)}return c};
Wk.prototype.collapseSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Collapse SubGraph");b.animationManager.Dh("Collapse SubGraph");var c=new F;if(null!==a&&a.isSubGraphExpanded)a.collapseSubGraph(),c.add(a);else if(null===a)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof xg&&e.isSubGraphExpanded&&(e.collapseSubGraph(),c.add(e))}b.ba("SubGraphCollapsed",c)}finally{b.ab("Collapse SubGraph")}};
Wk.prototype.canCollapseSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a)return a instanceof xg&&a.isSubGraphExpanded?!0:!1;for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof xg&&b.isSubGraphExpanded)return!0;return!1};
Wk.prototype.expandSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Expand SubGraph");b.animationManager.Dh("Expand SubGraph");var c=new F;if(null!==a&&!a.isSubGraphExpanded)a.expandSubGraph(),c.add(a);else if(null===a)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof xg&&!e.isSubGraphExpanded&&(e.expandSubGraph(),c.add(e))}b.ba("SubGraphExpanded",c)}finally{b.ab("Expand SubGraph")}};
Wk.prototype.canExpandSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a)return a instanceof xg&&!a.isSubGraphExpanded?!0:!1;for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof xg&&!b.isSubGraphExpanded)return!0;return!1};
Wk.prototype.editTextBlock=function(a){void 0===a&&(a=null);null!==a&&w(a,Kh,Wk,"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.cm(function(a){return a instanceof Kh&&a.editable})}null!==a&&(b.currentTool=null,c.textBlock=a,b.currentTool=c)}};
Wk.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 Kh))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.cm(function(a){return a instanceof Kh&&a.editable}),null!==a))return!0;return!1};
Wk.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(qd):b.isMouseOverDiagram||(e=b.viewportBounds,e=new J(e.x+e.width/2,e.y+e.height/2));null!==e&&(d.viewPoint=b.Ct(e),d.documentPoint=e,d.left=!1,d.right=!0,d.up=!0);b.currentTool=c;Gh(c,!1,a)}};
Wk.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};
Wk.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.Qk);d=new Ub;if(null===a)return d;for(var f=a.iterator;f.next();)Yj(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 S&&(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(Wk.prototype,{diagram:{configurable:!0,get:function(){return this.D}},copiesClipboardData:{configurable:!0,get:function(){return this.w},set:function(a){z(a,"boolean",Wk,"copiesClipboardData");this.w=a}},copiesConnectedLinks:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"boolean",Wk,"copiesConnectedLinks");this.L=a}},deletesConnectedLinks:{configurable:!0,get:function(){return this.Wb},set:function(a){z(a,
"boolean",Wk,"deletesConnectedLinks");this.Wb=a}},copiesTree:{configurable:!0,get:function(){return this.Na},set:function(a){z(a,"boolean",Wk,"copiesTree");this.Na=a}},deletesTree:{configurable:!0,get:function(){return this.Xb},set:function(a){z(a,"boolean",Wk,"deletesTree");this.Xb=a}},copiesParentKey:{configurable:!0,get:function(){return this.Ma},set:function(a){z(a,"boolean",Wk,"copiesParentKey");this.Ma=a}},copiesGroupKey:{configurable:!0,
get:function(){return this.ca},set:function(a){z(a,"boolean",Wk,"copiesGroupKey");this.ca=a}},archetypeGroupData:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&z(a,"object",Wk,"archetypeGroupData");var b=this.diagram;E&&(b=b.model,!b.Ti()||a instanceof xg||b.ht(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.mi},set:function(a){null!==a&&z(a,"function",Wk,"memberValidation");this.mi=a}},defaultScale:{configurable:!0,get:function(){return this.diagram.defaultScale},set:function(a){this.diagram.defaultScale=a}},zoomFactor:{configurable:!0,get:function(){return this.Oc},set:function(a){B(a,Wk,"zoomFactor");1<a||v("zoomFactor must be larger than 1.0, not: "+a);this.Oc=a}},scrollToPartPause:{configurable:!0,get:function(){return this.Nc},
set:function(a){B(a,Wk,"scrollToPartPause");this.Nc=a}}});Wk.className="CommandHandler";Li=function(){return new Wk};
function N(){qb(this);this.I=4225027;this.mb=1;this.cg=null;this.Wa="";this.fc=this.jb=null;this.ua=(new J(NaN,NaN)).freeze();this.Qc=xc;this.Sf=rc;this.Rf=wc;this.ub=new $b;this.Gh=new $b;this.Qf=new $b;this.Da=this.Xk=1;this.Bc=0;this.ye=$k;this.Xg=Zc;this.qc=(new L(NaN,NaN,NaN,NaN)).freeze();this.wb=(new L(NaN,NaN,NaN,NaN)).freeze();this.rc=(new L(0,0,NaN,NaN)).freeze();this.R=this.Vo=this.Wo=null;this.Ck=this.xb=Qd;this.ip=0;this.jp=1;this.Gg=0;this.cn=1;this.zp=null;this.np=-Infinity;this.Dl=
0;this.El=gc;this.Fl=ch;this.nn="";this.eb=this.P=null;this.Ik=-1;this.Hl=this.md=this.Vh=this.Kl=null;this.qs=nh;this.Fj=null}var oe,nh,ph,$k,al,bl,cl,dl,el,fl;
N.prototype.cloneProtected=function(a){a.I=this.I|6144;a.mb=this.mb;a.Wa=this.Wa;a.jb=this.jb;a.fc=this.fc;a.ua.assign(this.ua);a.Qc=this.Qc.J();a.Sf=this.Sf.J();a.Rf=this.Rf.J();a.Qf=this.Qf.copy();a.Da=this.Da;a.Bc=this.Bc;a.ye=this.ye;a.Xg=this.Xg.J();a.qc.assign(this.qc);a.wb.assign(this.wb);a.rc.assign(this.rc);a.Vo=this.Vo;null!==this.R&&(a.R=this.R.copy());a.xb=this.xb.J();a.Ck=this.Ck.J();a.ip=this.ip;a.jp=this.jp;a.Gg=this.Gg;a.cn=this.cn;a.zp=this.zp;a.np=this.np;a.Dl=this.Dl;a.El=this.El.J();
a.Fl=this.Fl;a.nn=this.nn;null!==this.P&&(a.P=this.P.copy());a.eb=this.eb;a.Ik=this.Ik;null!==this.Vh&&(a.Vh=Ma(this.Vh));null!==this.md&&(a.md=this.md.copy());a.Hl=this.Hl};N.prototype.Vw=function(a){var b=this.Vh;if(Ka(b))for(var c=0;c<b.length;c++){if(b[c]===a)return}else this.Vh=b=[];b.push(a)};N.prototype.qf=function(a){a.Wo=null;a.Fj=null;a.v()};
N.prototype.clone=function(){var a=new this.constructor;this.cloneProtected(a);if(null!==this.Vh)for(var b=0;b<this.Vh.length;b++){var c=this.Vh[b];a[c]=this[c]}return a};N.prototype.copy=function(){return this.clone()};t=N.prototype;t.hb=function(a){a.classType===S?0===a.name.indexOf("Orient")?this.segmentOrientation=a:v("Unknown Link enum value for GraphObject.segmentOrientation property: "+a):a.classType===N?this.stretch=a:Fa(this,a)};t.toString=function(){return Va(this.constructor)+"#"+Jb(this)};
function gl(a){null===a.P&&(a.P=new hl)}t.Jc=function(){if(null===this.R){var a=new il;a.Pg=ed;a.oh=ed;a.Ng=10;a.mh=10;a.Og=0;a.nh=0;this.R=a}};t.cb=function(a,b,c,d,e,f,g){var h=this.part;if(null!==h&&(h.tk(a,b,c,d,e,f,g),c===this&&a===of&&jl(this)&&kl(this,h,b),this instanceof W&&c===h&&0!==(h.I&16777216)&&null!==h.data))for(a=this.Z.j,c=a.length,d=0;d<c;d++)e=a[d],e instanceof W&&Qj(e,function(a){null!==a.data&&0!==(a.I&16777216)&&a.Fa(b)})};
function kl(a,b,c){var d=a.Li();if(null!==d)for(var e=a.eb.iterator;e.next();){var f=e.value,g=null;if(null!==f.sourceName){g=ll(f,d,a);if(null===g)continue;f.Eq(a,g,c,null)}else if(f.isToModel){var h=b.diagram;null===h||h.skipsModelSourceBindings||f.Eq(a,h.model.modelData,c,d)}else{h=d.data;if(null===h)continue;var k=b.diagram;null===k||k.skipsModelSourceBindings||f.Eq(a,h,c,d)}g===a&&(h=d.Vs(f.bj),null!==h&&f.dw(h,g,c))}}t.Vs=function(a){return this.Ik===a?this:null};
t.g=function(a,b,c){this.cb(of,a,this,b,c)};function ml(a,b,c,d,e){var f=a.qc,g=a.Qf;g.reset();nl(a,g,b,c,d,e);a.Qf=g;f.h(b,c,d,e);g.it()||g.aw(f)}function ol(a,b,c,d){if(!1===a.pickable)return!1;d.multiply(a.transform);return c?a.Kc(b,d):a.wh(b,d)}
t.nx=function(a,b,c){if(!1===this.pickable)return!1;var d=this.naturalBounds;b=a.Ee(b);return c?cc(a.x,a.y,0,0,0,d.height)<=b||cc(a.x,a.y,0,d.height,d.width,d.height)<=b||cc(a.x,a.y,d.width,d.height,d.width,0)<=b||cc(a.x,a.y,d.width,0,0,0)<=b:a.ed(0,0)<=b&&a.ed(0,d.height)<=b&&a.ed(d.width,0)<=b&&a.ed(d.width,d.height)<=b};t.ae=function(){return!0};
t.ea=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.Te){var e=d.gm("extraTouchThreshold"),f=d.gm("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=Qc(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 Cf||this instanceof Hg?Qc(c.x-5,c.y-5,c.width+10,c.height+10,b.x,b.y):
c.ea(b))this.md&&!this.md.ea(b)?e=!1:null!==this.fc&&c.ea(b)?e=!0:null!==this.jb&&this.rc.ea(a)?e=!0:e=this.xh(a);J.free(b);return e};t.xh=function(a){var b=this.naturalBounds;return Qc(0,0,b.width,b.height,a.x,a.y)};
t.pf=function(a){E&&w(a,L,N,"containsRect:r");if(0===this.angle)return this.actualBounds.pf(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.ea(c.Wd(e))&&(e.h(a.x,a.bottom),b.ea(c.Wd(e))&&(e.h(a.right,a.bottom),b.ea(c.Wd(e))&&(e.h(a.right,a.y),b.ea(c.Wd(e))&&(d=!0))));J.free(e);L.free(b);return d};
t.wh=function(a,b){E&&w(a,L,N,"containedInRect:r");if(void 0===b)return a.pf(this.actualBounds);var c=this.naturalBounds,d=!1,e=J.allocAt(0,0);a.ea(b.va(e))&&(e.h(0,c.height),a.ea(b.va(e))&&(e.h(c.width,c.height),a.ea(b.va(e))&&(e.h(c.width,0),a.ea(b.va(e))&&(d=!0))));J.free(e);return d};
t.Kc=function(a,b){E&&w(a,L,N,"intersectsRect:r");if(void 0===b&&(b=this.transform,0===this.angle))return a.Kc(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.ea(b.va(d))||a.ea(b.va(e))||a.ea(b.va(f))||a.ea(b.va(g)))h=!0;else{c=L.allocAt(0,0,c.width,c.height);var k=J.allocAt(a.x,a.y);c.ea(b.Wd(k))?h=!0:(k.h(a.x,a.bottom),c.ea(b.Wd(k))?h=!0:(k.h(a.right,a.bottom),c.ea(b.Wd(k))?h=!0:(k.h(a.right,a.y),
c.ea(b.Wd(k))&&(h=!0))));J.free(k);L.free(c);!h&&(K.et(a,d,e)||K.et(a,e,f)||K.et(a,f,g)||K.et(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.Nb()&&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.td.va(b);return b};
t.eq=function(a){void 0===a&&(a=new L);var b=this.naturalBounds,c=this.td,d=J.allocAt(0,0).transform(c);a.h(d.x,d.y,0,0);d.h(b.width,0).transform(c);Mc(a,d.x,d.y,0,0);d.h(b.width,b.height).transform(c);Mc(a,d.x,d.y,0,0);d.h(0,b.height).transform(c);Mc(a,d.x,d.y,0,0);J.free(d);return a};t.Oi=function(){var a=this.td;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.I&4096)===!1)return this.Xk;var a=this.Da;return null!==this.panel?a*this.panel.Fe():a};t.at=function(a,b){void 0===b&&(b=new J);b.assign(a);this.td.Wd(b);return b};t.Wc=function(a,b,c){return this.gk(a.x,a.y,b.x,b.y,c)};
t.gk=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.Wc(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.Wc(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!==Dj(this)){var e=this.Xg,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 Hg&&(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(pl(this,!0)){case nh:g=e=0;h&&(b=a=Infinity);
break;case oe:isFinite(a)&&a>c&&(e=a);isFinite(b)&&b>d&&(g=b);break;case al:isFinite(a)&&a>c&&(e=a);g=0;h&&(b=Infinity);break;case bl: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.qc.ja();this.mm(a,b,c,d);this.qc.freeze();this.qc.o()||v("Non-real measuredBounds has been set. Object "+this+", measuredBounds: "+this.qc.toString());yj(this,!1)}};N.prototype.mm=function(){};N.prototype.vg=function(){return!1};
N.prototype.arrange=function(a,b,c,d,e){this.kl();var f=L.alloc();f.assign(this.wb);this.wb.ja();!1===Ej(this)?this.wb.h(a,b,c,d):this.vh(a,b,c,d);this.wb.freeze();void 0===e?this.md=null:this.md=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.rc,d=this.measuredBounds,null!==this.areaBackground&&(d=this.wb),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 Kh&&(a=this.naturalBounds,
this.Wr>a.height||this.metrics.maxLineWidth>a.width)))c=!0;this.I=c?this.I|256:this.I&-257;this.wb.o()||v("Non-real actualBounds has been set. Object "+this+", actualBounds: "+this.wb.toString());this.qt(f,this.wb);ql(this,!1);L.free(f)};t=N.prototype;t.vh=function(){};
function rl(a,b,c,d,e){a.wb.h(b,c,d,e);if(!a.desiredSize.o()){var f=a.qc;c=a.Xg;b=c.right+c.left;var g=c.top+c.bottom;c=f.width+b;f=f.height+g;d+=b;e+=g;b=pl(a,!0);c===d&&f===e&&(b=nh);switch(b){case nh:if(c>d||f>e)yj(a,!0),a.measure(c>d?d:c,f>e?e:f,0,0);break;case oe:yj(a,!0);a.measure(d,e,0,0);break;case al:yj(a,!0);a.measure(d,f,0,0);break;case bl:yj(a,!0),a.measure(c,e,0,0)}}}
t.qt=function(a,b){var c=this.part;null!==c&&null!==c.diagram&&(c.selectionObject!==this&&c.resizeObject!==this&&c.rotateObject!==this||sl(c,!0),this.S(),Fc(a,b)||(c.Ah(),this.Ko(c)))};t.Ko=function(a){null!==this.portId&&(sl(a,!0),a instanceof V&&tl(a,this))};
t.jc=function(a,b){if(this.visible){var c=this instanceof W&&(this.type===W.TableRow||this.type===W.TableColumn),d=this.wb;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)ul(this,a,b);else{this instanceof S&&this.lk(!1);E&&E.Gi&&E.My&&E.My(a,this);c=this.transform;var g=this.panel;0!==(this.I&4096)===!0&&vl(this);var h=this.part,k=!1,l=0;if(h&&b.Ge("drawShadows")&&(k=h.isShadowed)){var m=
h.wi;l=Math.max(m.y,m.x)*b.scale*b.Pb}if(!(m=b.rj)){var n=this.naturalBounds;m=this.Gh;var p=m.m11,q=m.m21,r=m.dx,u=m.m12,x=m.m22,y=m.dy,A,C=A=0;m=A*p+C*q+r;var G=A*u+C*x+y;A=n.width+l;C=0;var I=A*p+C*q+r;A=A*u+C*x+y;m=Math.min(m,I);G=Math.min(G,A);var O=Math.max(m,I)-m;var R=Math.max(G,A)-G;A=n.width+l;C=n.height+l;I=A*p+C*q+r;A=A*u+C*x+y;m=Math.min(m,I);G=Math.min(G,A);O=Math.max(m+O,I)-m;R=Math.max(G+R,A)-G;A=0;C=n.height+l;I=A*p+C*q+r;A=A*u+C*x+y;m=Math.min(m,I);G=Math.min(G,A);O=Math.max(m+O,
I)-m;R=Math.max(G+R,A)-G;l=b.viewportBounds;n=l.x;p=l.y;m=!(m>l.aa+n||n>O+m||G>l.$+p||p>R+G)}if(m){m=0!==(this.I&256);a.clipInsteadOfFill&&(m=!1);this instanceof Kh&&(a.font=this.font);if(m){E&&E.Oy&&Ha("clip"+this.toString());G=g.ae()?g.naturalBounds:g.actualBounds;null!==this.md?(n=this.md,O=n.x,R=n.y,l=n.width,n=n.height):(O=Math.max(d.x,G.x),R=Math.max(d.y,G.y),l=Math.min(d.right,G.right)-O,n=Math.min(d.bottom,G.bottom)-R);if(O>d.width+d.x||d.x>G.width+G.x){1!==e&&(a.globalAlpha=f);return}a.save();
a.beginPath();a.rect(O,R,l,n);a.clip()}if(this.vg()){if(!h.isVisible()){1!==e&&(a.globalAlpha=f);return}k&&(G=h.wi,a.Uv(G.x*b.scale*b.Pb,G.y*b.scale*b.Pb,h.Qd),wl(a),a.shadowColor=h.Nj)}!0===this.shadowVisible?wl(a):!1===this.shadowVisible&&xl(a);h=this.naturalBounds;null!==this.fc&&(yi(this,a,this.fc,!0,!0,h,d),this.fc instanceof yl&&this.fc.type===zl?(a.beginPath(),a.rect(d.x,d.y,d.width,d.height),a.Vd(this.fc)):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.I&512)||null!==g&&(g.type===W.Auto||g.type===W.Spot)&&g.Bb()!==this)&&null===this.shadowVisible&&xl(a);null!==this.jb&&(l=this.naturalBounds,O=G=0,R=l.width,l=l.height,n=0,this instanceof Hg&&(l=this.sa.bounds,G=l.x,O=l.y,R=l.width,l=l.height,n=this.strokeWidth),yi(this,a,this.jb,!0,!1,h,d),this.jb instanceof yl&&this.jb.type===zl?(a.beginPath(),a.rect(G-n/2,O-n/2,R+n,l+n),a.Vd(this.jb)):a.fillRect(G-n/2,O-n/2,R+n,l+n));E&&E.Gi&&E.Ny&&E.Ny(a,this);k&&(null!==this.jb||null!==this.fc||
null!==g&&0!==(g.I&512)||null!==g&&(g.type===W.Auto||g.type===W.Spot)&&g.Bb()!==this)?(Al(this,!0),null===this.shadowVisible&&xl(a)):Al(this,!1);this.Hi(a,b);k&&0!==(this.I&512)===!0&&wl(a);this.vg()&&k&&xl(a);m?(a.restore(),this instanceof W?a.Uc(!0):a.Uc(!1)):c.it()||(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 ul(a,b,c){var d=a.wb,e=a.rc;null!==a.fc&&(yi(a,b,a.fc,!0,!0,e,d),a.fc instanceof yl&&a.fc.type===zl?(b.beginPath(),b.rect(d.x,d.y,d.width,d.height),b.Vd(a.fc)):b.fillRect(d.x,d.y,d.width,d.height));null!==a.jb&&(yi(a,b,a.jb,!0,!1,e,d),a.jb instanceof yl&&a.jb.type===zl?(b.beginPath(),b.rect(d.x,d.y,d.width,d.height),b.Vd(a.jb)):b.fillRect(d.x,d.y,d.width,d.height));a.Hi(b,c)}t.Hi=function(){};
function yi(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===Bl)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 Cl)&&c.fe&&(c.type===Dl||c.Lk===h&&c.Qt===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===El)l=
b.createLinearGradient(m,n,p,q);else if(c.type===zl)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===Dl)try{l=b.createPattern(c.pattern,"repeat")}catch(y){l=null}else Ba(c.type,"Brush type");if(c.type!==Dl&&(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.Lk=h,c.Qt=k),null===l&&c.type===Dl&&-1!==c.Lk)){c.Lk=-1;var x=a.diagram;
null!==x&&-1===c.Lk&&wa(function(){x.vf()},600)}}d?b.fillStyle=l:b.strokeStyle=l}}}t.tg=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.uf=function(){if(!this.visible)return!1;var a=this.panel;return null!==a?a.uf():!0};t.ug=function(){for(var a=this instanceof W?this:this.panel;null!==a&&a.isEnabled;)a=a.panel;return null===a};
function vl(a){if(0!==(a.I&2048)===!0){var b=a.ub;b.reset();if(!a.wb.o()||!a.qc.o()){Fl(a,!1);return}b.translate(a.wb.x-a.qc.x,a.wb.y-a.qc.y);if(1!==a.scale||0!==a.angle){var c=a.naturalBounds;nl(a,b,c.x,c.y,c.width,c.height)}Fl(a,!1);Gl(a,!0)}0!==(a.I&4096)===!0&&(b=a.panel,null===b?(a.Gh.set(a.ub),a.Xk=a.scale,Gl(a,!1)):null!==b.td&&(c=a.Gh,c.reset(),b.ae()?c.multiply(b.Gh):null!==b.panel&&c.multiply(b.panel.Gh),c.multiply(a.ub),a.Xk=a.scale*b.Xk,Gl(a,!1)))}
function nl(a,b,c,d,e,f){1!==a.scale&&b.scale(a.scale);if(0!==a.angle){var g=qd;a.vg()&&a.locationSpot.Za()&&(g=a.locationSpot);var h=J.alloc();if(a instanceof T&&a.locationObject!==a)for(c=a.locationObject,d=c.naturalBounds,h.vk(d.x,d.y,d.width,d.height,g),c.Qf.va(h),h.offset(-c.measuredBounds.x,-c.measuredBounds.y),g=c.panel;null!==g&&g!==a;)g.Qf.va(h),h.offset(-g.measuredBounds.x,-g.measuredBounds.y),g=g.panel;else h.vk(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!==Dj(this)){yj(this,!0);ql(this,!0);var b=this.panel;null===b||a||b.v()}};t.im=function(){!0!==Dj(this)&&(yj(this,!0),ql(this,!0))};function Hl(a){if(!1===Ej(a)){var b=a.panel;null!==b?b.v():a.vg()&&(b=a.diagram,null!==b&&(b.Fd.add(a),a instanceof V&&a.gd(),b.ec()));ql(a,!0)}}t.kl=function(){0!==(this.I&2048)===!1&&(Fl(this,!0),Gl(this,!0))};t.qv=function(){Gl(this,!0)};t.S=function(){var a=this.part;null!==a&&a.S()};
function pl(a,b){var c=a.stretch,d=a.panel;if(null!==d&&d.type===W.Table)return Il(a,d.getRowDefinition(a.row),d.getColumnDefinition(a.column),b);if(null!==d&&d.type===W.Auto&&d.Bb()===a)return Jl(a,oe,b);if(c===$k){if(null!==d){if(d.type===W.Spot&&d.Bb()===a)return Jl(a,oe,b);c=d.defaultStretch;return c===$k?Jl(a,nh,b):Jl(a,c,b)}return Jl(a,nh,b)}return Jl(a,c,b)}
function Il(a,b,c,d){var e=a.stretch;if(e!==$k)return Jl(a,e,d);var f=e=null;switch(b.stretch){case bl:f=!0;break;case oe:f=!0}switch(c.stretch){case al:e=!0;break;case oe:e=!0}b=a.panel.defaultStretch;null===e&&(e=b===al||b===oe);null===f&&(f=b===bl||b===oe);return!0===e&&!0===f?Jl(a,oe,d):!0===e?Jl(a,al,d):!0===f?Jl(a,bl,d):Jl(a,nh,d)}
function Jl(a,b,c){if(c)return b;if(b===nh)return nh;c=a.desiredSize;if(c.o())return nh;a=a.angle;if(!isNaN(c.width))if(90!==a&&270!==a){if(b===al)return nh;if(b===oe)return bl}else{if(b===bl)return nh;if(b===oe)return al}if(!isNaN(c.height))if(90!==a&&270!==a){if(b===bl)return nh;if(b===oe)return al}else{if(b===al)return nh;if(b===oe)return bl}return b}function Al(a,b){a.I=b?a.I|512:a.I&-513}function jl(a){return 0!==(a.I&1024)}function Kl(a,b){a.I=b?a.I|1024:a.I&-1025}
function Fl(a,b){a.I=b?a.I|2048:a.I&-2049}function Gl(a,b){a.I=b?a.I|4096:a.I&-4097}function Dj(a){return 0!==(a.I&8192)}function yj(a,b){a.I=b?a.I|8192:a.I&-8193}function Ej(a){return 0!==(a.I&16384)}function ql(a,b){a.I=b?a.I|16384:a.I&-16385}t.Xi=function(a){this.cg=a};t.Sv=function(){};t.Rv=function(a){this.ua=a;Hl(this);return!0};t.Bt=function(a,b){this.ua.h(a,b);this.kl()};
function Ll(a){var b=a.part;if(b instanceof V&&(null!==a.portId||a===b.port)){var c=b.diagram;null===c||c.undoManager.isUndoingRedoing||tl(b,a)}}function Ml(a){var b=a.diagram;null===b||b.undoManager.isUndoingRedoing||(a instanceof W?a instanceof V?a.gd():a.xk(a,function(a){Ll(a)}):Ll(a))}t.bind=function(a){a.Sd=this;var b=this.Li();null!==b&&Nl(b)&&v("Cannot add a Binding to a template that has already been copied: "+a);null===this.eb&&(this.eb=new F);this.eb.add(a)};
t.Li=function(){for(var a=this instanceof W?this:this.panel;null!==a;){if(null!==a.Th)return a;a=a.panel}return null};t.Tv=function(a){Kj(this,a)};
function Ol(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=Pl.K(a);"function"===typeof f?(c=Ma(arguments),d=f(c),Ja(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)Pi(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):Ql(d,f);return d}
function Ql(a,b){if("string"===typeof b)if(a instanceof Kh)a.text=b;else if(a instanceof Hg)a.figure=b;else if(a instanceof kk)a.source=b;else if(a instanceof W){var c=Rl.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 yl?(c=sb(yl,b),null!==c?a.type=c:v("Unknown Brush type as an argument to GraphObject.make: "+b)):a instanceof me?(c=sb(me,b),null!==c?a.type=c:E&&v("Unknown Geometry type as an argument to GraphObject.make: "+
b)):a instanceof Ye?(c=sb(Ye,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 ek){var d;b.isRow&&"function"===typeof a.getRowDefinition?d=a.getRowDefinition(b.index):b.isRow||"function"!==typeof a.getColumnDefinition||(d=a.getColumnDefinition(b.index));d instanceof
ek?d.$l(b):v("A RowColumnDefinition can only be added to an object that implements getRowDefinition/getColumnDefinition, not to: "+a)}else if(b instanceof D)"function"===typeof a.hb?a.hb(b):Fa(a,b);else if(b instanceof Sl)a.type=b;else if(b instanceof Ti)a instanceof N?a.bind(b):a instanceof ek?a.bind(b):v("A Binding can only be applied to a GraphObject or RowColumnDefinition, not to: "+a);else if(b instanceof Xe)a instanceof me?a.figures.add(b):v("A PathFigure can only be added to a Geometry, not to: "+
a);else if(b instanceof Ye)a instanceof Xe?a.segments.add(b):v("A PathSegment can only be added to a PathFigure, not to: "+a);else if(b instanceof Ni)a instanceof P?a.layout=b:a instanceof xg?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++)Ql(a,b[c]);else if("object"===typeof b&&null!==b)if(a instanceof yl){c=new xb;for(var e in b)d=parseFloat(e),isNaN(d)?c[e]=b[e]:a.addColorStop(d,b[e]);Kj(a,c)}else if(a instanceof
ek){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 xb;for(c in b)"row"!==c&&"column"!==c&&(e[c]=b[c]);Kj(a,e)}else Kj(a,b);else v('Unknown initializer "'+b+'" for object being constructed by GraphObject.make: '+
a)}function Tl(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);Pl.add(a,b)}
function Ul(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.Hl},set:function(a){var b=this.Hl;b!==a&&(E&&null!==a&&z(a,"boolean",N,"shadowVisible"),this.Hl=a,this.S(),this.g("shadowVisible",b,a))}},enabledChanged:{configurable:!0,get:function(){return null!==this.P?this.P.Fn:null},set:function(a){gl(this);var b=this.P.Fn;b!==a&&(null!==a&&z(a,"function",N,"enabledChanged"),this.P.Fn=a,this.g("enabledChanged",b,a))}},segmentOrientation:{configurable:!0,
enumerable:!0,get:function(){return this.Fl},set:function(a){var b=this.Fl;b!==a&&(E&&tb(a,S,N,"segmentOrientation"),this.Fl=a,this.v(),this.g("segmentOrientation",b,a),a===ch&&(this.angle=0))}},segmentIndex:{configurable:!0,get:function(){return this.np},set:function(a){E&&z(a,"number",N,"segmentIndex");a=Math.round(a);var b=this.np;b!==a&&(this.np=a,this.v(),this.g("segmentIndex",b,a))}},segmentFraction:{configurable:!0,get:function(){return this.Dl},set:function(a){E&&
z(a,"number",N,"segmentFraction");isNaN(a)?a=0:0>a?a=0:1<a&&(a=1);var b=this.Dl;b!==a&&(this.Dl=a,this.v(),this.g("segmentFraction",b,a))}},segmentOffset:{configurable:!0,get:function(){return this.El},set:function(a){var b=this.El;b.A(a)||(E&&w(a,J,N,"segmentOffset"),this.El=a=a.J(),this.v(),this.g("segmentOffset",b,a))}},stretch:{configurable:!0,get:function(){return this.ye},set:function(a){var b=this.ye;b!==a&&(E&&tb(a,N,N,"stretch"),this.ye=a,this.v(),this.g("stretch",
b,a))}},name:{configurable:!0,get:function(){return this.Wa},set:function(a){var b=this.Wa;b!==a&&(E&&z(a,"string",N,"name"),this.Wa=a,null!==this.part&&(this.part.Aj=null),this.g("name",b,a))}},opacity:{configurable:!0,get:function(){return this.mb},set:function(a){var b=this.mb;b!==a&&(z(a,"number",N,"opacity"),(0>a||1<a)&&Ca(a,"0 <= value <= 1",N,"opacity"),this.mb=a,this.g("opacity",b,a),a=this.diagram,b=this.part,null!==a&&null!==b&&a.S(Oj(b,b.actualBounds)))}},visible:{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",N,"visible"),this.I^=1,this.g("visible",b,a),b=this.panel,null!==b?b.v():this.vg()&&this.Ob(a),this.S(),Ml(this))}},pickable:{configurable:!0,get:function(){return 0!==(this.I&2)},set:function(a){var b=0!==(this.I&2);b!==a&&(E&&z(a,"boolean",N,"pickable"),this.I^=2,this.g("pickable",b,a))}},fromLinkableDuplicates:{configurable:!0,get:function(){return 0!==(this.I&
4)},set:function(a){var b=0!==(this.I&4);b!==a&&(E&&z(a,"boolean",N,"fromLinkableDuplicates"),this.I^=4,this.g("fromLinkableDuplicates",b,a))}},fromLinkableSelfNode:{configurable:!0,get:function(){return 0!==(this.I&8)},set:function(a){var b=0!==(this.I&8);b!==a&&(E&&z(a,"boolean",N,"fromLinkableSelfNode"),this.I^=8,this.g("fromLinkableSelfNode",b,a))}},toLinkableDuplicates:{configurable:!0,get:function(){return 0!==(this.I&16)},set:function(a){var b=0!==(this.I&16);b!==
a&&(E&&z(a,"boolean",N,"toLinkableDuplicates"),this.I^=16,this.g("toLinkableDuplicates",b,a))}},toLinkableSelfNode:{configurable:!0,get:function(){return 0!==(this.I&32)},set:function(a){var b=0!==(this.I&32);b!==a&&(E&&z(a,"boolean",N,"toLinkableSelfNode"),this.I^=32,this.g("toLinkableSelfNode",b,a))}},isPanelMain:{configurable:!0,get:function(){return 0!==(this.I&64)},set:function(a){var b=0!==(this.I&64);b!==a&&(E&&z(a,"boolean",N,"isPanelMain"),this.I^=64,this.v(),
this.g("isPanelMain",b,a))}},isActionable:{configurable:!0,get:function(){return 0!==(this.I&128)},set:function(a){var b=0!==(this.I&128);b!==a&&(E&&z(a,"boolean",N,"isActionable"),this.I^=128,this.g("isActionable",b,a))}},areaBackground:{configurable:!0,get:function(){return this.fc},set:function(a){var b=this.fc;b!==a&&(null!==a&&Vl(a,"GraphObject.areaBackground"),a instanceof yl&&a.freeze(),this.fc=a,this.S(),this.g("areaBackground",b,a))}},background:{configurable:!0,
enumerable:!0,get:function(){return this.jb},set:function(a){var b=this.jb;b!==a&&(null!==a&&Vl(a,"GraphObject.background"),a instanceof yl&&a.freeze(),this.jb=a,this.S(),this.g("background",b,a))}},part:{configurable:!0,get:function(){if(this.vg())return this;if(null!==this.Fj)return this.Fj;var a;for(a=this.panel;a;){if(a instanceof T)return this.Fj=a;a=a.panel}return null}},svg:{configurable:!0,get:function(){return this.Gs},set:function(a){this.Gs=a}},panel:{configurable:!0,
enumerable:!0,get:function(){return this.cg}},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.ua},set:function(a){E&&w(a,J,N,"position");var b=a.x,c=a.y,d=this.ua,e=d.x,f=d.y;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))?this.Sv():(a=a.J(),this.Rv(a,d)&&this.g("position",
d,a))}},actualBounds:{configurable:!0,get:function(){return this.wb}},scale:{configurable:!0,get:function(){return this.Da},set:function(a){var b=this.Da;b!==a&&(E&&B(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.Bc},set:function(a){var b=this.Bc;b!==a&&(E&&B(a,N,"angle"),a%=360,0>a&&(a+=360),b!==a&&(this.Bc=a,Ml(this),this.v(),
this.g("angle",b,a)))}},desiredSize:{configurable:!0,get:function(){return this.Qc},set:function(a){E&&w(a,Zb,N,"desiredSize");var b=a.width,c=a.height,d=this.Qc,e=d.width,f=d.height;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))||(this.Qc=a=a.J(),this.v(),this instanceof Hg&&this.cc(),this.g("desiredSize",d,a),jl(this)&&(a=this.part,null!==a&&(kl(this,a,"width"),kl(this,a,"height"))))}},width:{configurable:!0,get:function(){return this.Qc.width},set:function(a){var b=
this.Qc.width;b===a||isNaN(b)&&isNaN(a)||(E&&z(a,"number",N,"width"),b=this.Qc,this.Qc=a=(new Zb(a,this.Qc.height)).freeze(),this.v(),this instanceof Hg&&this.cc(),this.g("desiredSize",b,a),jl(this)&&(a=this.part,null!==a&&kl(this,a,"width")))}},height:{configurable:!0,get:function(){return this.Qc.height},set:function(a){var b=this.Qc.height;b===a||isNaN(b)&&isNaN(a)||(E&&z(a,"number",N,"height"),b=this.Qc,this.Qc=a=(new Zb(this.Qc.width,a)).freeze(),this.v(),this instanceof Hg&&this.cc(),
this.g("desiredSize",b,a),jl(this)&&(a=this.part,null!==a&&kl(this,a,"height")))}},minSize:{configurable:!0,get:function(){return this.Sf},set:function(a){var b=this.Sf;b.A(a)||(E&&w(a,Zb,N,"minSize"),a=a.copy(),isNaN(a.width)&&(a.width=0),isNaN(a.height)&&(a.height=0),a.freeze(),this.Sf=a,this.v(),this.g("minSize",b,a))}},maxSize:{configurable:!0,get:function(){return this.Rf},set:function(a){var b=this.Rf;b.A(a)||(E&&w(a,Zb,N,"maxSize"),a=a.copy(),isNaN(a.width)&&(a.width=
Infinity),isNaN(a.height)&&(a.height=Infinity),a.freeze(),this.Rf=a,this.v(),this.g("maxSize",b,a))}},measuredBounds:{configurable:!0,get:function(){return this.qc}},naturalBounds:{configurable:!0,get:function(){return this.rc}},margin:{configurable:!0,get:function(){return this.Xg},set:function(a){"number"===typeof a?a=new Hc(a):E&&w(a,Hc,N,"margin");var b=this.Xg;b.A(a)||(this.Xg=a=a.J(),this.v(),this.g("margin",b,a))}},transform:{configurable:!0,
get:function(){0!==(this.I&2048)===!0&&vl(this);return this.ub}},td:{configurable:!0,get:function(){0!==(this.I&4096)===!0&&vl(this);return this.Gh}},alignment:{configurable:!0,get:function(){return this.xb},set:function(a){var b=this.xb;b.A(a)||(E&&w(a,M,N,"alignment"),a.Nb()&&!a.Cb()&&v("GraphObject.alignment for "+this+" must be a real Spot or Spot.Default, not: "+a),this.xb=a=a.J(),Hl(this),this.g("alignment",b,a))}},column:{configurable:!0,get:function(){return this.Gg},
set:function(a){E&&B(a,N,"column");a=Math.round(a);var b=this.Gg;b!==a&&(0>a&&Ca(a,">= 0",N,"column"),this.Gg=a,this.v(),this.g("column",b,a))}},columnSpan:{configurable:!0,get:function(){return this.cn},set:function(a){E&&z(a,"number",N,"columnSpan");a=Math.round(a);var b=this.cn;b!==a&&(1>a&&Ca(a,">= 1",N,"columnSpan"),this.cn=a,this.v(),this.g("columnSpan",b,a))}},row:{configurable:!0,get:function(){return this.ip},set:function(a){E&&B(a,N,"row");a=Math.round(a);var b=
this.ip;b!==a&&(0>a&&Ca(a,">= 0",N,"row"),this.ip=a,this.v(),this.g("row",b,a))}},rowSpan:{configurable:!0,get:function(){return this.jp},set:function(a){E&&z(a,"number",N,"rowSpan");a=Math.round(a);var b=this.jp;b!==a&&(1>a&&Ca(a,">= 1",N,"rowSpan"),this.jp=a,this.v(),this.g("rowSpan",b,a))}},spanAllocation:{configurable:!0,get:function(){return this.zp},set:function(a){var b=this.zp;b!==a&&(null!==a&&z(a,"function",N,"spanAllocation"),this.zp=a,this.v(),this.g("spanAllocation",
b,a))}},alignmentFocus:{configurable:!0,get:function(){return this.Ck},set:function(a){var b=this.Ck;b.A(a)||(E&&w(a,M,N,"alignmentFocus"),!E||!a.Nb()||a.Cb()||a.kq()&&this instanceof V||v("GraphObject.alignmentFocus must be a real Spot or Spot.Default, not: "+a),this.Ck=a=a.J(),this.v(),this.g("alignmentFocus",b,a))}},portId:{configurable:!0,get:function(){return this.Vo},set:function(a){var b=this.Vo;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&&Wl(c,this);this.Vo=a;null!==a&&null!==c&&(c.zh=!0,Xl(c,this));this.g("portId",b,a)}}},toSpot:{configurable:!0,get:function(){return null!==this.R?this.R.oh:ed},set:function(a){this.Jc();var b=this.R.oh;b.A(a)||(E&&w(a,M,N,"toSpot"),a=a.J(),this.R.oh=a,this.g("toSpot",b,a),Ll(this))}},toEndSegmentLength:{configurable:!0,get:function(){return null!==this.R?this.R.mh:10},set:function(a){this.Jc();
var b=this.R.mh;b!==a&&(E&&z(a,"number",N,"toEndSegmentLength"),0>a&&Ca(a,">= 0",N,"toEndSegmentLength"),this.R.mh=a,this.g("toEndSegmentLength",b,a),Ll(this))}},toShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.nh:0},set:function(a){this.Jc();var b=this.R.nh;b!==a&&(E&&z(a,"number",N,"toShortLength"),this.R.nh=a,this.g("toShortLength",b,a),Ll(this))}},toLinkable:{configurable:!0,get:function(){return null!==this.R?this.R.Gp:null},set:function(a){this.Jc();
var b=this.R.Gp;b!==a&&(E&&null!==a&&z(a,"boolean",N,"toLinkable"),this.R.Gp=a,this.g("toLinkable",b,a))}},toMaxLinks:{configurable:!0,get:function(){return null!==this.R?this.R.Hp:Infinity},set:function(a){this.Jc();var b=this.R.Hp;b!==a&&(E&&z(a,"number",N,"toMaxLinks"),0>a&&Ca(a,">= 0",N,"toMaxLinks"),this.R.Hp=a,this.g("toMaxLinks",b,a))}},fromSpot:{configurable:!0,get:function(){return null!==this.R?this.R.Pg:ed},set:function(a){this.Jc();var b=this.R.Pg;b.A(a)||(E&&
w(a,M,N,"fromSpot"),a=a.J(),this.R.Pg=a,this.g("fromSpot",b,a),Ll(this))}},fromEndSegmentLength:{configurable:!0,get:function(){return null!==this.R?this.R.Ng:10},set:function(a){this.Jc();var b=this.R.Ng;b!==a&&(E&&z(a,"number",N,"fromEndSegmentLength"),0>a&&Ca(a,">= 0",N,"fromEndSegmentLength"),this.R.Ng=a,this.g("fromEndSegmentLength",b,a),Ll(this))}},fromShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.Og:0},set:function(a){this.Jc();var b=this.R.Og;
b!==a&&(E&&z(a,"number",N,"fromShortLength"),this.R.Og=a,this.g("fromShortLength",b,a),Ll(this))}},fromLinkable:{configurable:!0,get:function(){return null!==this.R?this.R.Hn:null},set:function(a){this.Jc();var b=this.R.Hn;b!==a&&(E&&null!==a&&z(a,"boolean",N,"fromLinkable"),this.R.Hn=a,this.g("fromLinkable",b,a))}},fromMaxLinks:{configurable:!0,get:function(){return null!==this.R?this.R.In:Infinity},set:function(a){this.Jc();var b=this.R.In;b!==a&&(E&&z(a,"number",N,"fromMaxLinks"),
0>a&&Ca(a,">= 0",N,"fromMaxLinks"),this.R.In=a,this.g("fromMaxLinks",b,a))}},cursor:{configurable:!0,get:function(){return this.nn},set:function(a){var b=this.nn;b!==a&&(z(a,"string",N,"cursor"),this.nn=a,this.g("cursor",b,a))}},click:{configurable:!0,get:function(){return null!==this.P?this.P.Df:null},set:function(a){gl(this);var b=this.P.Df;b!==a&&(null!==a&&z(a,"function",N,"click"),this.P.Df=a,this.g("click",b,a))}},doubleClick:{configurable:!0,get:function(){return null!==
this.P?this.P.If:null},set:function(a){gl(this);var b=this.P.If;b!==a&&(null!==a&&z(a,"function",N,"doubleClick"),this.P.If=a,this.g("doubleClick",b,a))}},contextClick:{configurable:!0,get:function(){return null!==this.P?this.P.Ef:null},set:function(a){gl(this);var b=this.P.Ef;b!==a&&(null!==a&&z(a,"function",N,"contextClick"),this.P.Ef=a,this.g("contextClick",b,a))}},mouseEnter:{configurable:!0,get:function(){return null!==this.P?this.P.Uf:null},set:function(a){gl(this);
var b=this.P.Uf;b!==a&&(null!==a&&z(a,"function",N,"mouseEnter"),this.P.Uf=a,this.g("mouseEnter",b,a))}},mouseLeave:{configurable:!0,get:function(){return null!==this.P?this.P.Xf:null},set:function(a){gl(this);var b=this.P.Xf;b!==a&&(null!==a&&z(a,"function",N,"mouseLeave"),this.P.Xf=a,this.g("mouseLeave",b,a))}},mouseOver:{configurable:!0,get:function(){return null!==this.P?this.P.Yf:null},set:function(a){gl(this);var b=this.P.Yf;b!==a&&(null!==a&&z(a,"function",N,"mouseOver"),
this.P.Yf=a,this.g("mouseOver",b,a))}},mouseHover:{configurable:!0,get:function(){return null!==this.P?this.P.Wf:null},set:function(a){gl(this);var b=this.P.Wf;b!==a&&(null!==a&&z(a,"function",N,"mouseHover"),this.P.Wf=a,this.g("mouseHover",b,a))}},mouseHold:{configurable:!0,get:function(){return null!==this.P?this.P.Vf:null},set:function(a){gl(this);var b=this.P.Vf;b!==a&&(null!==a&&z(a,"function",N,"mouseHold"),this.P.Vf=a,this.g("mouseHold",b,a))}},mouseDragEnter:{configurable:!0,
enumerable:!0,get:function(){return null!==this.P?this.P.xo:null},set:function(a){gl(this);var b=this.P.xo;b!==a&&(null!==a&&z(a,"function",N,"mouseDragEnter"),this.P.xo=a,this.g("mouseDragEnter",b,a))}},mouseDragLeave:{configurable:!0,get:function(){return null!==this.P?this.P.yo:null},set:function(a){gl(this);var b=this.P.yo;b!==a&&(null!==a&&z(a,"function",N,"mouseDragLeave"),this.P.yo=a,this.g("mouseDragLeave",b,a))}},mouseDrop:{configurable:!0,get:function(){return null!==
this.P?this.P.Tf:null},set:function(a){gl(this);var b=this.P.Tf;b!==a&&(null!==a&&z(a,"function",N,"mouseDrop"),this.P.Tf=a,this.g("mouseDrop",b,a))}},actionDown:{configurable:!0,get:function(){return null!==this.P?this.P.Nm:null},set:function(a){gl(this);var b=this.P.Nm;b!==a&&(null!==a&&z(a,"function",N,"actionDown"),this.P.Nm=a,this.g("actionDown",b,a))}},actionMove:{configurable:!0,get:function(){return null!==this.P?this.P.Om:null},set:function(a){gl(this);var b=this.P.Om;
b!==a&&(null!==a&&z(a,"function",N,"actionMove"),this.P.Om=a,this.g("actionMove",b,a))}},actionUp:{configurable:!0,get:function(){return null!==this.P?this.P.Pm:null},set:function(a){gl(this);var b=this.P.Pm;b!==a&&(null!==a&&z(a,"function",N,"actionUp"),this.P.Pm=a,this.g("actionUp",b,a))}},actionCancel:{configurable:!0,get:function(){return null!==this.P?this.P.Mm:null},set:function(a){gl(this);var b=this.P.Mm;b!==a&&(null!==a&&z(a,"function",N,"actionCancel"),this.P.Mm=
a,this.g("actionCancel",b,a))}},toolTip:{configurable:!0,get:function(){return null!==this.P?this.P.jg:null},set:function(a){gl(this);var b=this.P.jg;b!==a&&(!E||null===a||a instanceof Cf||a instanceof Hf||v("GraphObject.toolTip must be an Adornment or HTMLInfo."),this.P.jg=a,this.g("toolTip",b,a))}},contextMenu:{configurable:!0,get:function(){return null!==this.P?this.P.Ff:null},set:function(a){gl(this);var b=this.P.Ff;b!==a&&(!E||a instanceof Cf||a instanceof Hf||v("GraphObject.contextMenu must be an Adornment or HTMLInfo."),
this.P.Ff=a,this.g("contextMenu",b,a))}}});N.prototype.setProperties=N.prototype.Tv;N.prototype.findTemplateBinder=N.prototype.Li;N.prototype.bind=N.prototype.bind;N.prototype.isEnabledObject=N.prototype.ug;N.prototype.isVisibleObject=N.prototype.uf;N.prototype.isContainedBy=N.prototype.tg;N.prototype.getNearestIntersectionPoint=N.prototype.Wc;N.prototype.getLocalPoint=N.prototype.at;N.prototype.getDocumentScale=N.prototype.Fe;N.prototype.getDocumentAngle=N.prototype.Oi;
N.prototype.getDocumentBounds=N.prototype.eq;N.prototype.getDocumentPoint=N.prototype.oa;N.prototype.intersectsRect=N.prototype.Kc;N.prototype.containedInRect=N.prototype.wh;N.prototype.containsRect=N.prototype.pf;N.prototype.containsPoint=N.prototype.ea;N.prototype.raiseChanged=N.prototype.g;N.prototype.raiseChangedEvent=N.prototype.cb;N.prototype.addCopyProperty=N.prototype.Vw;var Pl=null;N.className="GraphObject";Pl=new Ub;
Tl("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=Ol(W,W.Auto,{isActionable:!0,enabledChanged:function(a,b){if(a instanceof W){var c=a.bb("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"},Ol(Hg,{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.ug()&&b instanceof W&&(a=b.bb("ButtonBorder"),a instanceof Hg)){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.ug()&&b instanceof W&&(a=b.bb("ButtonBorder"),a instanceof Hg&&(a.fill=b._buttonFillNormal,a.stroke=b._buttonStrokeNormal))};b.actionDown=function(a,b){if(b.ug()&&b instanceof W&&null!==b._buttonFillPressed&&0===a.button){var c=b.bb("ButtonBorder");if(c instanceof Hg){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.ug()&&d instanceof W&&null!==d._buttonFillPressed&&0===b.button){var c=d.bb("ButtonBorder");if(c instanceof Hg){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.ug()&&d instanceof W&&null!==d._buttonFillPressed){var c=d.bb("ButtonBorder");if(c instanceof Hg){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.ug()&&d instanceof W&&null!==d._buttonFillPressed){var c=b.diagram;if(0===c.firstInput.button&&(c.currentTool.standardMouseOver(),a(b,d)&&(b=d.bb("ButtonBorder"),b instanceof Hg))){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});
Tl("TreeExpanderButton",function(){var a=Ol("Button",{_treeExpandedFigure:"MinusLine",_treeCollapsedFigure:"PlusLine"},Ol(Hg,{name:"ButtonIcon",figure:"MinusLine",stroke:"#424242",strokeWidth:2,desiredSize:uc},(new Ti("figure","isTreeExpanded",function(a,c){c=c.panel;return a?c._treeExpandedFigure:c._treeCollapsedFigure})).rq()),{visible:!1},(new Ti("visible","isTreeLeaf",function(a){return!a})).rq());a.click=function(a,c){c=c.part;c instanceof Cf&&(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});
Tl("SubGraphExpanderButton",function(){var a=Ol("Button",{_subGraphExpandedFigure:"MinusLine",_subGraphCollapsedFigure:"PlusLine"},Ol(Hg,{name:"ButtonIcon",figure:"MinusLine",stroke:"#424242",strokeWidth:2,desiredSize:uc},(new Ti("figure","isSubGraphExpanded",function(a,c){c=c.panel;return a?c._subGraphExpandedFigure:c._subGraphCollapsedFigure})).rq()));a.click=function(a,c){c=c.part;c instanceof Cf&&(c=c.adornedPart);if(c instanceof xg){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});Tl("ToolTip",function(){return Ol(Cf,W.Auto,{isShadowed:!0,shadowColor:"rgba(0, 0, 0, .4)",shadowOffset:new J(0,3),shadowBlur:5},Ol(Hg,{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)}))});
Tl("ContextMenu",function(){return Ol(Cf,W.Vertical,{background:"#F5F5F5",isShadowed:!0,shadowColor:"rgba(0, 0, 0, .4)",shadowOffset:new J(0,3),shadowBlur:5},new Ti("background","",function(a){return null!==a.adornedPart&&null!==a.placeholder?null:"#F5F5F5"}))});Tl("ContextMenuButton",function(){var a=Ol("Button");a.stretch=al;var b=a.bb("ButtonBorder");b instanceof Hg&&(b.figure="Rectangle",b.strokeWidth=0,b.spot1=new M(0,0,2,3),b.spot2=new M(1,1,-2,-2));return a});
Tl("PanelExpanderButton",function(a){var b=Ul(a,"COLLAPSIBLE"),c=Ol("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},Ol(Hg,{name:"ButtonIcon",strokeWidth:2},(new Ti("geometryString","visible",function(a){return a?c._buttonExpandedFigure:c._buttonCollapsedFigure})).rq(b)));
a=c.bb("ButtonBorder");a instanceof Hg&&(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.Li();null===d&&(d=c.part);null!==d&&(c=d.bb(b),null!==c&&(a.Ca("Collapse/Expand Panel"),c.visible=!c.visible,a.ab("Collapse/Expand Panel")))}};return c});
Tl("CheckBoxButton",function(a){var b=Ul(a);a=Ol("Button",{desiredSize:new Zb(14,14)},Ol(Hg,{name:"ButtonIcon",geometryString:"M0 0 M0 8.85 L4.9 13.75 16.2 2.45 M16.2 16.2",strokeWidth:2,stretch:oe,geometryStretch:ph,visible:!1},""!==b?(new Ti("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.bb("ButtonIcon");c.Ca("checkbox");f.visible=!f.visible;"function"===typeof d._doClick&&d._doClick(a,
d);c.ab("checkbox")}}};return a});
Tl("CheckBox",function(a){a=Ul(a);a=Ol("CheckBoxButton",a,{name:"Button",isActionable:!1,margin:new Hc(0,1,0,0)});var b=Ol(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=nh=new D(N,"None",0);N.Default=$k=new D(N,"Default",0);N.Vertical=bl=new D(N,"Vertical",4);N.Horizontal=al=new D(N,"Horizontal",5);N.Fill=oe=new D(N,"Fill",3);N.Uniform=ph=new D(N,"Uniform",1);
N.UniformToFill=cl=new D(N,"UniformToFill",2);N.FlipVertical=dl=new D(N,"FlipVertical",1);N.FlipHorizontal=el=new D(N,"FlipHorizontal",2);N.FlipBoth=fl=new D(N,"FlipBoth",3);N.make=Ol;N.getBuilders=function(){var a=new Ub,b;for(b in Pl)if(b!==b.toLowerCase()){var c=Pl.K(b);"function"===typeof c&&a.add(b,c)}a.freeze();return a};N.defineBuilder=Tl;N.takeBuilderArgument=Ul;
function hl(){this.Fn=this.Ff=this.jg=this.Mm=this.Pm=this.Om=this.Nm=this.Tf=this.yo=this.xo=this.Vf=this.Wf=this.Yf=this.Xf=this.Uf=this.Ef=this.If=this.Df=null}hl.prototype.copy=function(){var a=new hl;a.Df=this.Df;a.If=this.If;a.Ef=this.Ef;a.Uf=this.Uf;a.Xf=this.Xf;a.Yf=this.Yf;a.Wf=this.Wf;a.Vf=this.Vf;a.xo=this.xo;a.yo=this.yo;a.Tf=this.Tf;a.Nm=this.Nm;a.Om=this.Om;a.Pm=this.Pm;a.Mm=this.Mm;a.jg=this.jg;a.Ff=this.Ff;a.Fn=this.Fn;return a};hl.className="GraphObjectEventHandlers";
function Yl(){this.Qa=[1,0,0,1,0,0]}Yl.prototype.copy=function(){var a=new Yl;a.Qa[0]=this.Qa[0];a.Qa[1]=this.Qa[1];a.Qa[2]=this.Qa[2];a.Qa[3]=this.Qa[3];a.Qa[4]=this.Qa[4];a.Qa[5]=this.Qa[5];return a};Yl.prototype.translate=function(a,b){this.Qa[4]+=this.Qa[0]*a+this.Qa[2]*b;this.Qa[5]+=this.Qa[1]*a+this.Qa[3]*b};Yl.prototype.scale=function(a,b){this.Qa[0]*=a;this.Qa[1]*=a;this.Qa[2]*=b;this.Qa[3]*=b};Yl.className="STransform";
function Zl(a){this.type=a;this.r2=this.y2=this.x2=this.r1=this.y1=this.x1=0;this.bx=[];this.pattern=null}Zl.prototype.addColorStop=function(a,b){this.bx.push({offset:a,color:b})};Zl.className="SGradient";
function Nj(a,b){this.ownerDocument=a=void 0===b?ra.document:b;this.Oz="http://www.w3.org/2000/svg";void 0!==a&&(this.Ha=this.vb("svg",{width:"1px",height:"1px",viewBox:"0 0 1 1"}),this.Ha.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns","http://www.w3.org/2000/svg"),this.Ha.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"));this.Zp=null;this.context=new $l(this)}
Nj.prototype.resize=function(a,b,c,d){return this.width!==a||this.height!==b?(this.style.width=c+"px",this.style.height=d+"px",this.Ha.setAttributeNS(null,"width",c+"px"),this.Ha.setAttributeNS(null,"height",d+"px"),this.Ha.setAttributeNS(null,"viewBox","0 0 "+c+" "+d),this.context.lu.firstElementChild.setAttributeNS(null,"width",c+"px"),this.context.lu.firstElementChild.setAttributeNS(null,"height",d+"px"),!0):!1};
Nj.prototype.vb=function(a,b,c){a=this.ownerDocument.createElementNS(this.Oz,a);if(Ja(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};Nj.prototype.getBoundingClientRect=function(){return this.Ha.getBoundingClientRect()};Nj.prototype.focus=function(){this.Ha.focus()};Nj.prototype.jx=function(){this.ownerDocument=null};
na.Object.defineProperties(Nj.prototype,{width:{configurable:!0,get:function(){return this.Ha.width.baseVal.value},set:function(a){this.Ha.width=a}},height:{configurable:!0,get:function(){return this.Ha.height.baseVal.value},set:function(a){this.Ha.height=a}},style:{configurable:!0,get:function(){return this.Ha.style}}});Nj.className="SVGSurface";
function $l(a){this.wk=a;this.svg=a.Ha;this.stack=[];this.yc=[];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.Qd=this.vp=this.tp=0;this.lq=null;this.path=[];this.hu=!1;this.hh=null;this.ih=0;this.Ud=new Yl;
am(this,1,0,0,1,0,0);var b=Pb++,c=this.vb("clipPath",{id:"mainClip"+b});c.appendChild(this.vb("rect",{x:0,y:0,width:a.width,height:a.height}));this.lu=c;this.wk.Ha.appendChild(c);this.yc[0].setAttributeNS(null,"clip-path","url(#mainClip"+b+")");this.Qz={}}t=$l.prototype;
t.reset=function(){this.stack=[];this.yc=[];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.Qd=this.vp=this.tp=0;this.lq=null;this.path=[];this.Ud=new Yl;am(this,1,0,0,1,0,0);var a=Pb++,b=this.vb("clipPath",
{id:"mainClip"+a});b.appendChild(this.vb("rect",{x:0,y:0,width:this.wk.width,height:this.wk.height}));this.lu=b;this.wk.Ha.appendChild(b);this.yc[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,this.Ud);this.addPath("clipPath",this.path,new Yl)};t.closePath=function(){this.path.push(["z"])};t.createLinearGradient=function(a,b,c,d){var e=new Zl("linear");e.x1=a;e.y1=b;e.x2=c;e.y2=d;return e};
t.createPattern=function(a){var b="";a instanceof HTMLCanvasElement&&(b=a.toDataURL());a instanceof HTMLImageElement&&(b=a.src);var c=this.Qz;if(c[b])return"url(#"+c[b]+")";var d="PATTERN"+Pb++,e={x:0,y:0,width:a.width,height:a.height,href:b};a=this.vb("pattern",{width:a.width,height:a.height,id:d,patternUnits:"userSpaceOnUse"});a.appendChild(this.vb("image",e));this.svg.appendChild(a);c[b]=d;return"url(#"+d+")"};
t.createRadialGradient=function(a,b,c,d,e,f){var g=new Zl("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||d,height:n||e,href:l,preserveAspectRatio:"xMidYMid slice"};K.da(d,h)&&K.da(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"+Pb++,g=this.vb("clipPath",{id:f}),g.appendChild(this.vb("rect",{x:b,y:c,width:d,height:e})),this.svg.appendChild(g),l["clip-path"]="url(#"+f+")";bm(this,"image",l,this.Ud,a);this.addElement("image",l)};t.fill=function(){this.addPath("fill",this.path,this.Ud)};t.Vd=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]};bm(this,"fill",a,this.Ud);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};bm(this,"fill",b,this.Ud);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.Ud=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.Ud.copy())};
t.setTransform=function(a,b,c,d,e,f){1===a&&0===b&&0===c&&1===d&&0===e&&0===f||am(this,a,b,c,d,e,f)};t.scale=function(a,b){this.Ud.scale(a,b)};t.translate=function(a,b){this.Ud.translate(a,b)};t.transform=function(){};t.stroke=function(){this.addPath("stroke",this.path,this.Ud)};t.aj=function(){this.clipInsteadOfFill||this.stroke()};t.vb=function(a,b,c){return this.wk.vb(a,b,c)};
t.addElement=function(a,b,c){a=this.vb(a,b,c);0<this.yc.length?this.yc[this.yc.length-1].appendChild(a):this.svg.appendChild(a);return this.lq=a};
function bm(a,b,c,d,e){1!==a.globalAlpha&&(c.opacity=a.globalAlpha);"fill"===b?(a.fillStyle instanceof Zl?c.fill=cm(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 Zl?c.stroke=cm(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.Qa;a="matrix("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+")";void 0!==e&&(a+=e);c.transform=a}
function cm(a,b){var c="GRAD"+Pb++;if("linear"===b.type)var d=a.vb("linearGradient",{x1:b.x1,x2:b.x2,y1:b.y1,y2:b.y2,id:c,gradientUnits:"userSpaceOnUse"});else if("radial"===b.type)d=a.vb("radialGradient",{x1:b.x1,x2:b.x2,y1:b.y1,y2:b.y2,r1:b.r1,r2:b.r2,id:c});else throw Error("invalid gradient");var e=b.bx;b=e.length;for(var f=[],g=0;g<b;g++){var h=e[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]);f.push(h)}f.sort(function(a,b){return a.offset>b.offset?1:-1});for(e=0;e<b;e++)d.appendChild(a.vb("stop",f[e]));a.svg.appendChild(d);return"url(#"+c+")"}
t.addPath=function(a,b,c){for(var d=[],e=0;e<b.length;e++){var f=Ma(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(" ")};"stroke"===a&&this.hu&&(b["stroke-dasharray"]=this.hh.toString(),b["stroke-dashoffset"]=this.ih);bm(this,a,b,c);"clipPath"===a?(a="CLIP"+Pb++,c=this.vb("clipPath",{id:a}),c.appendChild(this.vb("path",b)),this.svg.appendChild(c),
0<this.yc.length&&this.yc[this.yc.length-1].setAttributeNS(null,"clip-path","url(#"+a+")")):this.addElement("path",b)};function am(a,b,c,d,e,f,g){var h=new Yl;h.Qa=[b,c,d,e,f,g];b={};bm(a,"g",b,h);h=a.addElement("g",b);a.yc.push(h)}
t.Aq=function(){if(0!==this.shadowOffsetX||0!==this.shadowOffsetY||0!==this.shadowBlur){var a="SHADOW"+Pb++,b=this.addElement("filter",{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},null);var c=this.vb("feGaussianBlur",{"in":"SourceAlpha",result:"blur",vA:this.shadowBlur/2});var d=this.vb("feFlood",{"in":"blur",result:"flood","flood-color":this.shadowColor});var e=this.vb("feComposite",{"in":"flood",in2:"blur",operator:"in",result:"comp"});var f=this.vb("feOffset",{"in":"comp",result:"offsetBlur",
dx:this.shadowOffsetX,dy:this.shadowOffsetY});var g=this.vb("feMerge",{});g.appendChild(this.vb("feMergeNode",{"in":"offsetBlur"}));g.appendChild(this.vb("feMergeNode",{"in":"SourceGraphic"}));b.appendChild(c);b.appendChild(d);b.appendChild(e);b.appendChild(f);b.appendChild(g);0<this.yc.length&&this.yc[this.yc.length-1].setAttributeNS(null,"filter","url(#"+a+")")}};t.Uv=function(a,b,c){this.tp=a;this.vp=b;this.Qd=c};function xl(a){a.shadowOffsetX=0;a.shadowOffsetY=0;a.shadowBlur=0}
function wl(a){a.shadowOffsetX=a.tp;a.shadowOffsetY=a.vp;a.shadowBlur=a.Qd}t.Us=function(a,b){this.hu=!0;this.hh=a;this.ih=b};t.Ss=function(){this.hu=!1};t.Uc=function(){};t.Mx=function(){};$l.prototype.rotate=function(){};$l.prototype.getImageData=function(){return null};$l.prototype.measureText=function(){return null};$l.className="SVGContext";
P.prototype.nt=function(a){var b=new Nj(this,ra.document);void 0===a&&(a=new xb);var c=this;return Gk(this,function(a,e){a=Hk(c,a,"SVG",b);a=null!==a?a.svg:null;return"function"===typeof e?(e(a),null):a},a)};P.prototype.makeSvg=P.prototype.nt;P.prototype.tv=function(a){return this.nt(a)};P.prototype.makeSVG=P.prototype.tv;
N.prototype.kx=function(a,b){if(!(a instanceof $l))return!1;if(!this.visible)return!0;var c=null,d=a.lq;if(this instanceof W&&(this.type===W.TableRow||this.type===W.TableColumn))return ul(this,a,b),!0;var e=this.wb;if(0===e.width||0===e.height||isNaN(e.x)||isNaN(e.y))return!0;var f=this.transform,g=this.panel;0!==(this.I&4096)===!0&&vl(this);var h=0!==(this.I&256),k=!1;this instanceof Kh&&(a.font=this.font);if(h){k=g.ae()?g.naturalBounds:g.actualBounds;if(null!==this.md){var l=this.md;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;am(a,1,0,0,1,0,0);a.save();a.beginPath();a.rect(m,n,p,l);a.clip()}if(this.vg()&&!this.isVisible())return!0;a.Ud.Qa=[1,0,0,1,0,0];this instanceof Kh&&1<this.lineCount&&am(a,1,0,0,1,0,0);m=!1;this.vg()&&this.isShadowed&&b.Ge("drawShadows")&&(n=this.wi,a.Uv(n.x*b.scale*b.Pb,n.y*b.scale*
b.Pb,this.Qd),wl(a),a.shadowColor=this.Nj);n=!1;this.part&&b.Ge("drawShadows")&&(n=this.part.isShadowed);!0===this.shadowVisible?(wl(a),!1===m&&n&&(am(a,1,0,0,1,0,0),a.Aq(),m=!0)):!1===this.shadowVisible&&xl(a);p=this.naturalBounds;null!==this.areaBackground&&(yi(this,a,this.areaBackground,!0,!0,p,e),!1===m&&n&&(am(a,1,0,0,1,0,0),a.Aq(),m=!0),this.areaBackground instanceof yl&&this.areaBackground.type===zl?(a.beginPath(),a.rect(e.x,e.y,e.width,e.height),a.Vd(this.areaBackground)):a.fillRect(e.x,e.y,
e.width,e.height));this instanceof W?am(a,f.m11,f.m12,f.m21,f.m22,f.dx,f.dy):a.Ud.Qa=[f.m11,f.m12,f.m21,f.m22,f.dx,f.dy];if(null!==this.background){!1===m&&n&&(am(a,1,0,0,1,0,0),a.Aq(),m=!0);var q=this.naturalBounds;l=f=0;var r=q.width;q=q.height;var u=0;this instanceof Hg&&(q=this.geometry.bounds,f=q.x,l=q.y,r=q.width,q=q.height,u=this.strokeWidth);yi(this,a,this.background,!0,!1,p,e);this.background instanceof yl&&this.background.type===zl?(a.beginPath(),a.rect(f-u/2,l-u/2,r+u,q+u),a.Vd(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.I&512)||null!==g&&(g.type===W.Auto||g.type===W.Spot)&&g.Bb()!==this)?(Al(this,!0),null===this.shadowVisible&&xl(a)):Al(this,!1);this.Hi(a,b);n&&0!==(this.I&512)===!0&&wl(a);this.vg()&&n&&xl(a);h&&(a.restore(),k&&a.yc.pop());this instanceof W&&(c=a.yc.pop());!0===m&&a.yc.pop();this instanceof Kh&&1<this.lineCount&&(c=a.yc.pop());null!==a.wk.Zp&&(null===c&&(d===a.lq?(am(a,1,0,0,1,0,0),c=a.yc.pop()):
c=a.lq),a.wk.Zp(this,c));this.svg=c;return!0};function Ik(a,b){this.ownerDocument=b=void 0===b?ra.document:b;this.Zp=null;b=b.createElement("canvas");b.tabIndex=0;this.Ha=b;this.Ha.innerHTML="This text is displayed if your browser does not support the Canvas HTML element.";this.context=new Cl(b);b.D=a}Ik.prototype.resize=function(a,b,c,d){return this.width!==a||this.height!==b?(this.width=a,this.height=b,this.style.width=c+"px",this.style.height=d+"px",!0):!1};
Ik.prototype.toDataURL=function(a,b){return this.Ha.toDataURL(a,b)};Ik.prototype.getBoundingClientRect=function(){return this.Ha.getBoundingClientRect()};Ik.prototype.focus=function(){this.Ha.focus()};Ik.prototype.jx=function(){this.ownerDocument=this.Ha.D=null};
na.Object.defineProperties(Ik.prototype,{width:{configurable:!0,get:function(){return this.Ha.width},set:function(a){this.Ha.width=a}},height:{configurable:!0,get:function(){return this.Ha.height},set:function(a){this.Ha.height=a}},style:{configurable:!0,get:function(){return this.Ha.style}}});Ik.className="CanvasSurface";
function Cl(a){a.getContext&&a.getContext("2d")||v("Browser does not support HTML Canvas Element");this.Y=a.getContext("2d");this.Nt=this.Pt=this.Ot="";this.bn=!1;this.Qd=this.vp=this.tp=0}t=Cl.prototype;t.Mx=function(a){this.Y.imageSmoothingEnabled=a};t.arc=function(a,b,c,d,e,f){this.Y.arc(a,b,c,d,e,f)};t.beginPath=function(){this.Y.beginPath()};t.bezierCurveTo=function(a,b,c,d,e,f){this.Y.bezierCurveTo(a,b,c,d,e,f)};t.clearRect=function(a,b,c,d){this.Y.clearRect(a,b,c,d)};t.clip=function(){this.Y.clip()};
t.closePath=function(){this.Y.closePath()};t.createLinearGradient=function(a,b,c,d){return this.Y.createLinearGradient(a,b,c,d)};t.createPattern=function(a,b){return this.Y.createPattern(a,b)};t.createRadialGradient=function(a,b,c,d,e,f){return this.Y.createRadialGradient(a,b,c,d,e,f)};t.drawImage=function(a,b,c,d,e,f,g,h,k){void 0===d?this.Y.drawImage(a,b,c):this.Y.drawImage(a,b,c,d,e,f,g,h,k)};t.fill=function(){this.Y.fill()};t.fillRect=function(a,b,c,d){this.Y.fillRect(a,b,c,d)};
t.fillText=function(a,b,c){this.Y.fillText(a,b,c)};t.getImageData=function(a,b,c,d){return this.Y.getImageData(a,b,c,d)};t.lineTo=function(a,b){this.Y.lineTo(a,b)};t.measureText=function(a){return this.Y.measureText(a)};t.moveTo=function(a,b){this.Y.moveTo(a,b)};t.quadraticCurveTo=function(a,b,c,d){this.Y.quadraticCurveTo(a,b,c,d)};t.rect=function(a,b,c,d){this.Y.rect(a,b,c,d)};t.restore=function(){this.Y.restore()};Cl.prototype.rotate=function(a){this.Y.rotate(a)};t=Cl.prototype;t.save=function(){this.Y.save()};
t.setTransform=function(a,b,c,d,e,f){this.Y.setTransform(a,b,c,d,e,f)};t.scale=function(a,b){this.Y.scale(a,b)};t.stroke=function(){this.Y.stroke()};t.transform=function(a,b,c,d,e,f){1===a&&0===b&&0===c&&1===d&&0===e&&0===f||this.Y.transform(a,b,c,d,e,f)};t.translate=function(a,b){this.Y.translate(a,b)};
t.Vd=function(a){if(a instanceof yl&&a.type===zl){var b=a.Lk;a=a.Qt;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.bn?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.bn?this.clip():this.fill()};t.aj=function(){this.bn||this.stroke()};t.Uv=function(a,b,c){this.tp=a;this.vp=b;this.Qd=c};
t.Us=function(a,b){var c=this.Y;void 0!==c.setLineDash&&(c.setLineDash(a),c.lineDashOffset=b)};t.Ss=function(){var a=this.Y;void 0!==a.setLineDash&&(a.setLineDash(dm),a.lineDashOffset=0)};t.Uc=function(a){a&&(this.Ot="");this.Nt=this.Pt=""};
na.Object.defineProperties(Cl.prototype,{fillStyle:{configurable:!0,get:function(){return this.Y.fillStyle},set:function(a){this.Nt!==a&&(this.Nt=this.Y.fillStyle=a)}},font:{configurable:!0,get:function(){return this.Y.font},set:function(a){this.Ot!==a&&(this.Ot=this.Y.font=a)}},globalAlpha:{configurable:!0,get:function(){return this.Y.globalAlpha},set:function(a){this.Y.globalAlpha=a}},lineCap:{configurable:!0,get:function(){return this.Y.lineCap},
set:function(a){this.Y.lineCap=a}},lineDashOffset:{configurable:!0,get:function(){return this.Y.lineDashOffset},set:function(a){this.Y.lineDashOffset=a}},lineJoin:{configurable:!0,get:function(){return this.Y.lineJoin},set:function(a){this.Y.lineJoin=a}},lineWidth:{configurable:!0,get:function(){return this.Y.lineWidth},set:function(a){this.Y.lineWidth=a}},miterLimit:{configurable:!0,get:function(){return this.Y.miterLimit},set:function(a){this.Y.miterLimit=
a}},shadowBlur:{configurable:!0,get:function(){return this.Y.shadowBlur},set:function(a){this.Y.shadowBlur=a}},shadowColor:{configurable:!0,get:function(){return this.Y.shadowColor},set:function(a){this.Y.shadowColor=a}},shadowOffsetX:{configurable:!0,get:function(){return this.Y.shadowOffsetX},set:function(a){this.Y.shadowOffsetX=a}},shadowOffsetY:{configurable:!0,get:function(){return this.Y.shadowOffsetY},set:function(a){this.Y.shadowOffsetY=
a}},strokeStyle:{configurable:!0,get:function(){return this.Y.strokeStyle},set:function(a){this.Pt!==a&&(this.Pt=this.Y.strokeStyle=a)}},textAlign:{configurable:!0,get:function(){return this.Y.textAlign},set:function(a){this.Y.textAlign=a}},imageSmoothingEnabled:{configurable:!0,get:function(){return this.Y.imageSmoothingEnabled},set:function(a){this.Y.imageSmoothingEnabled=a}},clipInsteadOfFill:{configurable:!0,get:function(){return this.bn},
set:function(a){this.bn=a}}});var dm=Object.freeze([]);Cl.className="CanvasSurfaceContext";function em(){this.ca=this.w=this.L=this.l=0}em.className="ColorNumbers";
function yl(a){E&&1<arguments.length&&v("Brush constructor can take at most one optional argument, the Brush type.");fm||(gm(),fm=!0);qb(this);this.u=!1;void 0===a?(this.wa=Bl,this.Kk="black"):"string"===typeof a?(this.wa=Bl,E&&!hm(a)&&v('Color "'+a+'" is not a valid color string for Brush constructor'),this.Kk=a):(E&&tb(a,yl,yl,"constructor:type"),this.wa=a,this.Kk="black");var b=this.wa;b===El?(this.Ll=gd,this.Yk=td):this.Yk=b===zl?this.Ll=qd:this.Ll=ed;this.Es=0;this.sr=NaN;this.fe=this.ns=this.ee=
null;this.Qt=this.Lk=0}yl.prototype.copy=function(){var a=new yl;a.wa=this.wa;a.Kk=this.Kk;a.Ll=this.Ll.J();a.Yk=this.Yk.J();a.Es=this.Es;a.sr=this.sr;null!==this.ee&&(a.ee=this.ee.copy());a.ns=this.ns;return a};t=yl.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.hb=function(a){a.classType===yl?this.type=a:Fa(this,a)};
t.toString=function(){var a="Brush(";if(this.type===Bl)a+=this.color;else if(a=this.type===El?a+"Linear ":this.type===zl?a+"Radial ":this.type===Dl?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&&za(this);("number"!==typeof a||!isFinite(a)||1<a||0>a)&&Ca(a,"0 <= loc <= 1",yl,"addColorStop:loc");z(b,"string",yl,"addColorStop:color");E&&!hm(b)&&v('Color "'+b+'" is not a valid color string for Brush.addColorStop');null===this.ee&&(this.ee=new Ub);this.ee.add(a,b);this.wa===Bl&&(this.type=El);this.fe=null;return this};
function hm(a){if("black"===a)return!0;if(""===a)return!1;E&&z(a,"string",yl,"isValidColor");fm||(gm(),fm=!0);var b=im;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.Iz=function(a,b){this.u&&za(this);a=void 0===a||"number"!==typeof a?.2:a;b=void 0===b?jm:b;if(this.type===Bl)km(this.color),this.color=lm(a,b);else if((this.type===El||this.type===zl)&&null!==this.colorStops)for(var c=this.colorStops.iterator;c.next();)km(c.value),this.addColorStop(c.key,lm(a,b));return this};function mm(a,b,c){b=void 0===b||"number"!==typeof b?.2:b;c=void 0===c?jm:c;km(a);return lm(b,c)}
t.Ey=function(a,b){this.u&&za(this);a=void 0===a||"number"!==typeof a?.2:a;b=void 0===b?jm:b;if(this.type===Bl)km(this.color),this.color=lm(-a,b);else if((this.type===El||this.type===zl)&&null!==this.colorStops)for(var c=this.colorStops.iterator;c.next();)km(c.value),this.addColorStop(c.key,lm(-a,b));return this};function nm(a,b,c){b=void 0===b||"number"!==typeof b?.2:b;c=void 0===c?jm:c;km(a);return lm(-b,c)}
function om(a,b,c){km(a);a=pm.l;var d=pm.L,e=pm.w,f=pm.ca;km(b);void 0===c&&(c=.5);return"rgba("+Math.round((pm.l-a)*c+a)+", "+Math.round((pm.L-d)*c+d)+", "+Math.round((pm.w-e)*c+e)+", "+Math.round((pm.ca-f)*c+f)+")"}
t.vx=function(){if(this.type===Bl)return qm(this.color);if((this.type===El||this.type===zl)&&null!==this.colorStops){var a=this.colorStops;if(this.type===zl)return qm(a.first().value);if(null!==a.get(.5))return qm(a.get(.5));if(2===a.count)return a=a.Oa(),qm(om(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 qm(om(a.get(c),a.get(d),1-e/b))}return!1};
function qm(a){if(null===a)return null;if(a instanceof yl)return a.vx();km(a);return 128>(299*pm.l+587*pm.L+114*pm.w)/1E3}
function lm(a,b){switch(b){case jm:var c=100*rm(pm.l);b=100*rm(pm.L);var d=100*rm(pm.w);sm.l=.4124564*c+.3575761*b+.1804375*d;sm.L=.2126729*c+.7151522*b+.072175*d;sm.w=.0193339*c+.119192*b+.9503041*d;sm.ca=pm.ca;c=tm(sm.l/um[0]);b=tm(sm.L/um[1]);d=tm(sm.w/um[2]);vm.l=116*b-16;vm.L=500*(c-b);vm.w=200*(b-d);vm.ca=sm.ca;vm.l=Math.min(100,Math.max(0,vm.l+100*a));a=(vm.l+16)/116;c=a-vm.w/200;sm.l=um[0]*wm(vm.L/500+a);sm.L=um[1]*(vm.l>xm*ym?Math.pow(a,3):vm.l/xm);sm.w=um[2]*wm(c);sm.ca=vm.ca;a=-.969266*
sm.l+1.8760108*sm.L+.041556*sm.w;c=.0556434*sm.l+-.2040259*sm.L+1.0572252*sm.w;pm.l=255*zm((3.2404542*sm.l+-1.5371385*sm.L+-.4985314*sm.w)/100);pm.L=255*zm(a/100);pm.w=255*zm(c/100);pm.ca=sm.ca;pm.l=Math.round(pm.l);255<pm.l?pm.l=255:0>pm.l&&(pm.l=0);pm.L=Math.round(pm.L);255<pm.L?pm.L=255:0>pm.L&&(pm.L=0);pm.w=Math.round(pm.w);255<pm.w?pm.w=255:0>pm.w&&(pm.w=0);return"rgba("+pm.l+", "+pm.L+", "+pm.w+", "+pm.ca+")";case Am:b=pm.l/255;d=pm.L/255;var e=pm.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))}Bm.l=Math.round(c);Bm.L=Math.round(100*b);Bm.w=Math.round(100*g);Bm.ca=pm.ca;Bm.w=Math.min(100,Math.max(0,Bm.w+100*a));return"hsla("+Bm.l+", "+Bm.L+"%, "+Bm.w+"%, "+Bm.ca+")";default:return v("Unknown color space: "+b),"rgba(0, 0, 0, 1)"}}
function km(a){fm||(gm(),fm=!0);var b=im;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,pm.l=a[0],pm.L=a[1],pm.w=a[2],pm.ca=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'),pm.l=0,pm.L=0,pm.w=0,pm.ca=1)}}function rm(a){a/=255;return.04045>=a?a/12.92:Math.pow((a+.055)/1.055,2.4)}
function zm(a){return.0031308>=a?12.92*a:1.055*Math.pow(a,1/2.4)-.055}function tm(a){return a>ym?Math.pow(a,1/3):(xm*a+16)/116}function wm(a){var b=a*a*a;return b>ym?b:(116*a-16)/xm}function Vl(a,b){"string"===typeof a?E&&!hm(a)&&v('Color "'+a+'" is not a valid color string for '+b):a instanceof yl||v("Value for "+b+" must be a color string or a Brush, not "+a)}function gm(){im=Ih?(new Ik(null)).context:null}
na.Object.defineProperties(yl.prototype,{type:{configurable:!0,get:function(){return this.wa},set:function(a){this.u&&za(this,a);tb(a,yl,yl,"type");this.wa=a;this.start.Nb()&&(a===El?this.start=gd:a===zl&&(this.start=qd));this.end.Nb()&&(a===El?this.end=td:a===zl&&(this.end=qd));this.fe=null}},color:{configurable:!0,get:function(){return this.Kk},set:function(a){this.u&&za(this,a);E&&!hm(a)&&v('Color "'+a+'" is not a valid color string for Brush.color');this.Kk=a;this.fe=
null}},start:{configurable:!0,get:function(){return this.Ll},set:function(a){this.u&&za(this,a);w(a,M,yl,"start");this.Ll=a.J();this.fe=null}},end:{configurable:!0,get:function(){return this.Yk},set:function(a){this.u&&za(this,a);w(a,M,yl,"end");this.Yk=a.J();this.fe=null}},startRadius:{configurable:!0,get:function(){return this.Es},set:function(a){this.u&&za(this,a);B(a,yl,"startRadius");0>a&&Ca(a,">= zero",yl,"startRadius");this.Es=a;this.fe=null}},endRadius:{configurable:!0,
enumerable:!0,get:function(){return this.sr},set:function(a){this.u&&za(this,a);B(a,yl,"endRadius");0>a&&Ca(a,">= zero",yl,"endRadius");this.sr=a;this.fe=null}},colorStops:{configurable:!0,get:function(){return this.ee},set:function(a){this.u&&za(this,a);E&&w(a,Ub,yl,"colorStops");this.ee=a;this.fe=null}},pattern:{configurable:!0,get:function(){return this.ns},set:function(a){this.u&&za(this,a);this.ns=a;this.fe=null}}});yl.prototype.isDark=yl.prototype.vx;
yl.prototype.darkenBy=yl.prototype.Ey;yl.prototype.lightenBy=yl.prototype.Iz;yl.prototype.addColorStop=yl.prototype.addColorStop;var ym=216/24389,xm=24389/27,um=[95.047,100,108.883],im=null,pm=new em,Bm=new em,sm=new em,vm=new em,fm=!1;yl.className="Brush";var Bl;yl.Solid=Bl=new D(yl,"Solid",0);var El;yl.Linear=El=new D(yl,"Linear",1);var zl;yl.Radial=zl=new D(yl,"Radial",2);var Dl;yl.Pattern=Dl=new D(yl,"Pattern",4);var jm;yl.Lab=jm=new D(yl,"Lab",5);var Am;yl.HSL=Am=new D(yl,"HSL",6);
yl.randomColor=function(a,b){void 0===a&&(a=128);E&&(B(a,yl,"randomColor:min"),(0>a||255<a)&&Ca(a,"0 <= min <= 255",yl,"randomColor:min"));void 0===b&&(b=Math.max(a,255));E&&(B(b,yl,"randomColor:max"),(b<a||255<b)&&Ca(b,"min <= max <= 255",yl,"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};yl.isValidColor=hm;yl.lighten=function(a){return mm(a)};yl.lightenBy=mm;yl.darken=function(a){return nm(a)};yl.darkenBy=nm;yl.mix=om;yl.isDark=qm;function Sl(){this.name="Base"}Sl.prototype.measure=function(){};Sl.prototype.Lz=function(a,b,c,d,e){a.measure(b,c,d,e)};Sl.prototype.arrange=function(){};Sl.prototype.ty=function(a,b,c,d,e,f){a.arrange(b,c,d,e,f)};na.Object.defineProperties(Sl.prototype,{classType:{configurable:!0,get:function(){return W}}});
Sl.prototype.arrangeElement=Sl.prototype.ty;Sl.prototype.measureElement=Sl.prototype.Lz;Sl.className="PanelLayout";function Cm(){this.name="Base";this.name="Position"}ma(Cm,Sl);
Cm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length;a=Dm(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 Hg&&l.isGeometryPositioned&&(l=l.strokeWidth/2,p-=l,q-=l);Mc(e,p,q,n,m)}}};
Cm.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 Hg&&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 Em(){this.name="Base";this.name="Horizontal"}ma(Em,Sl);
Em.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length;b=Qa();f=Dm(a);for(var k=0;k<h;k++){var l=d[k];if(l.visible||l===f){var m=pl(l,!1);if(m!==nh&&m!==al)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);Ta(b)};
Em.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,x=pl(m,!1);if(isNaN(m.desiredSize.height)&&x===oe||x===bl)u=Math.max(c.height-q-r,0);q=u+q+r;r=m.alignment;r.Cb()&&(r=a.defaultAlignment);r.Za()||(r=qd);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 Fm(){this.name="Base";this.name="Vertical"}ma(Fm,Sl);
Fm.prototype.measure=function(a,b,c,d,e,f){var g=d.length;c=Qa();for(var h=Dm(a),k=0;k<g;k++){var l=d[k];if(l.visible||l===h){var m=pl(l,!1);if(m!==nh&&m!==bl)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;Cc(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;Ta(c)}};
Fm.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,x=pl(m,!1);if(isNaN(m.desiredSize.width)&&x===oe||x===al)u=Math.max(c.width-q-r,0);q=u+q+r;r=m.alignment;r.Cb()&&(r=a.defaultAlignment);r.Za()||(r=qd);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 Gm(){this.name="Base";this.name="Spot"}ma(Gm,Sl);
Gm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length,k=a.Bb(),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,x=L.allocAt(-l.left,-l.top,q,r),y=!0,A=Dm(a),C=0;C<h;C++){var G=d[C];if(G!==k&&(G.visible||G===A)){l=G.margin;q=l.right+l.left;r=l.top+l.bottom;p=pl(G,!1);switch(p){case oe:b=f;c=g;break;case al:b=f;break;case bl:c=g}G.measure(b,c,0,0);p=G.measuredBounds;q=
Math.max(p.width+q,0);r=Math.max(p.height+r,0);var I=G.alignment;I.Cb()&&(I=a.defaultAlignment);I.Za()||(I=qd);var O=G.alignmentFocus;O.Cb()&&(O=qd);var R=null;G instanceof W&&""!==G.Bg&&(G.arrange(0,0,p.width,p.height),R=G.bb(G.Bg),R===G&&(R=null));if(null!==R){l=R.naturalBounds;p=R.margin;for(l=J.allocAt(O.x*l.width-O.offsetX-p.left,O.y*l.height-O.offsetY-p.top);R!==G;)R.transform.va(l),R=R.panel;G=I.x*f+I.offsetX-l.x;p=I.y*g+I.offsetY-l.y;J.free(l)}else G=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;y?(y=!1,e.h(G,p,q,r)):Mc(e,G,p,q,r)}}y?e.assign(x):u?e.ov(x.x,x.y,x.width,x.height):Mc(e,x.x,x.y,x.width,x.height);L.free(x);p=k.stretch;p===$k&&(p=pl(k,!1));switch(p){case nh:return;case oe:if(!isFinite(b)&&!isFinite(c))return;break;case al:if(!isFinite(b))return;break;case bl: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;x=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.Cb()&&(m=a.defaultAlignment),m.Za()||(m=qd),c=c.alignmentFocus,c.Cb()&&(c=qd),y?(y=!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)):Mc(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));y?e.assign(x):u?e.ov(x.x,x.y,x.width,x.height):Mc(e,x.x,
x.y,x.width,x.height);L.free(x)};
Gm.prototype.arrange=function(a,b,c){var d=b.length,e=a.Bb(),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.Cb()&&(m=a.defaultAlignment);m.Za()||(m=qd);var u=p.alignmentFocus;u.Cb()&&(u=qd);l=null;p instanceof W&&""!==p.Bg&&(l=p.bb(p.Bg),l===p&&(l=null));if(null!==l){var x=l.naturalBounds;for(u=J.allocAt(u.x*x.width-u.offsetX,u.y*x.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 Hm(){this.name="Base";this.name="Auto"}ma(Hm,Sl);
Hm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length,k=a.Bb(),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 Hg&&(u=k,r=u.strokeWidth*u.scale);var x=Math.max(l.width+p,0);l=Math.max(l.height+q,0);var y=Im(k),A=y.x*x+y.offsetX;y=y.y*l+y.offsetY;var C=Jm(k),G=C.x*x+C.offsetX;C=C.y*l+C.offsetY;isFinite(b)&&(m=Math.max(Math.abs(A-G)-r,0));isFinite(c)&&(n=Math.max(Math.abs(y-C)-r,0));r=Zb.alloc();r.h(0,0);a=Dm(a);for(C=0;C<
h;C++)y=d[C],y===k||!y.visible&&y!==a||(l=y.margin,x=l.right+l.left,A=l.top+l.bottom,y.measure(m,n,0,0),l=y.measuredBounds,x=Math.max(l.width+x,0),l=Math.max(l.height+A,0),r.h(Math.max(x,r.width),Math.max(l,r.height)));if(1===h)e.width=x,e.height=l,Zb.free(r);else{y=Im(k);C=Jm(k);h=d=0;C.x!==y.x&&C.y!==y.y&&(d=r.width/Math.abs(C.x-y.x),h=r.height/Math.abs(C.y-y.y));Zb.free(r);r=0;null!==u&&(r=u.strokeWidth*u.scale,oh(u)===ph&&(d=h=Math.max(d,h)));d+=Math.abs(y.offsetX)+Math.abs(C.offsetX)+r;h+=Math.abs(y.offsetY)+
Math.abs(C.offsetY)+r;u=k.stretch;u===$k&&(u=pl(k,!1));switch(u){case nh:g=f=0;break;case oe:isFinite(b)&&(d=b);isFinite(c)&&(h=c);break;case al:isFinite(b)&&(d=b);g=0;break;case bl:f=0,isFinite(c)&&(h=c)}k.im();k.measure(d,h,f,g);e.width=k.measuredBounds.width+p;e.height=k.measuredBounds.height+q}};
Hm.prototype.arrange=function(a,b){var c=b.length,d=a.Bb(),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=Im(d),n=Jm(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;Mc(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.Cb()&&(p=a.defaultAlignment),p.Za()||(p=qd),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&&(Qc(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 Km(){this.name="Base";this.name="Table"}ma(Km,Sl);
Km.prototype.measure=function(a,b,c,d,e,f,g){for(var h=d.length,k=Qa(),l=Qa(),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(rc)||v(p.toString()+" TableRow/TableColumn Panels cannot set a minSize: "+p.minSize.toString()),p.maxSize.A(wc)||v(p.toString()+" TableRow/TableColumn Panels cannot set a maxSize: "+
p.maxSize.toString()));l.push(p);for(var q=p.Z.j,r=q.length,u=0;u<r;u++){var x=q[u];p.type===W.TableRow?x.row=n.row:p.type===W.TableColumn&&(x.column=n.column);k.push(x)}}}h=k.length;0===h&&(a.getRowDefinition(0),a.getColumnDefinition(0));for(var y=[],A=0;A<h;A++){var C=k[A];yj(C,!0);ql(C,!0);y[C.row]||(y[C.row]=[]);y[C.row][C.column]||(y[C.row][C.column]=[]);y[C.row][C.column].push(C)}Ta(k);var G=Qa(),I=Qa(),O=Qa(),R={count:0},U={count:0},ea=b,Z=c,qa=a.tb;h=qa.length;for(var xa=0;xa<h;xa++){var Q=
qa[xa];void 0!==Q&&(Q.actual=0)}qa=a.ob;h=qa.length;for(var aa=0;aa<h;aa++)Q=qa[aa],void 0!==Q&&(Q.actual=0);for(var Ga=y.length,yb=0,Xa=0;Xa<Ga;Xa++)y[Xa]&&(yb=Math.max(yb,y[Xa].length));var Sa=Math.min(a.topIndex,Ga-1),Ua=Math.min(a.leftIndex,yb-1),hb=0;Ga=y.length;for(var kc=Dm(a),rb=0;rb<Ga;rb++)if(y[rb]){yb=y[rb].length;for(var mb=a.getRowDefinition(rb),cb=mb.actual=0;cb<yb;cb++)if(y[rb][cb]){var ua=a.getColumnDefinition(cb);void 0===G[cb]&&(ua.actual=0,G[cb]=!0);for(var ta=y[rb][cb],wb=ta.length,
zb=0;zb<wb;zb++){var db=ta[zb];if(db.visible||db===kc){var qe=1<db.rowSpan||1<db.columnSpan;qe&&(rb<Sa||cb<Ua||I.push(db));var Yd=db.margin,Lb=Yd.right+Yd.left,Pf=Yd.top+Yd.bottom;var Wb=Il(db,mb,ua,!1);var De=db.desiredSize,id=!isNaN(De.height),lc=!isNaN(De.width)&&id;qe||Wb===nh||lc||rb<Sa||cb<Ua||(void 0!==R[cb]||Wb!==oe&&Wb!==al||(R[cb]=-1,R.count++),void 0!==U[rb]||Wb!==oe&&Wb!==bl||(U[rb]=-1,U.count++),O.push(db));db.measure(Infinity,Infinity,0,0);if(!(rb<Sa||cb<Ua)){var Zd=db.measuredBounds,
Wc=Math.max(Zd.width+Lb,0),Ze=Math.max(Zd.height+Pf,0);if(1===db.rowSpan&&(Wb===nh||Wb===al)){Q=a.getRowDefinition(rb);var $e=Q.vc();hb=Math.max(Ze-Q.actual,0);hb+$e>Z&&(hb=Math.max(Z-$e,0));var Qf=0===Q.actual;Q.actual=Q.actual+hb;Z=Math.max(Z-(hb+(Qf?$e:0)),0)}if(1===db.columnSpan&&(Wb===nh||Wb===bl)){Q=a.getColumnDefinition(cb);var wf=Q.vc();hb=Math.max(Wc-Q.actual,0);hb+wf>ea&&(hb=Math.max(ea-wf,0));var Rf=0===Q.actual;Q.actual=Q.actual+hb;ea=Math.max(ea-(hb+(Rf?wf:0)),0)}qe&&db.im()}}}}}Ta(G);
var mc=0,ob=0;h=a.columnCount;for(var nb=0;nb<h;nb++){var Nc=a.ob[nb];void 0!==Nc&&(mc+=Nc.ma,0!==Nc.ma&&(mc+=Nc.vc()))}h=a.rowCount;for(var Sf=0;Sf<h;Sf++){var zc=a.tb[Sf];void 0!==zc&&(ob+=zc.ma,0!==zc.ma&&(ob+=zc.vc()))}ea=Math.max(b-mc,0);var $d=Z=Math.max(c-ob,0),Ic=ea;h=O.length;for(var ae=0;ae<h;ae++){var nc=O[ae],Zh=a.getRowDefinition(nc.row),$h=a.getColumnDefinition(nc.column),af=nc.measuredBounds,Fb=nc.margin,Tf=Fb.right+Fb.left,bf=Fb.top+Fb.bottom;R[nc.column]=0===$h.actual&&void 0!==R[nc.column]?
Math.max(af.width+Tf,R[nc.column]):null;U[nc.row]=0===Zh.actual&&void 0!==U[nc.row]?Math.max(af.height+bf,U[nc.row]):null}var oc=0,cf=0,ad;for(ad in U)"count"!==ad&&(oc+=U[ad]);for(ad in R)"count"!==ad&&(cf+=R[ad]);for(var vb=Zb.alloc(),df=0;df<h;df++){var Ib=O[df];if(Ib.visible||Ib===kc){var Jc=a.getRowDefinition(Ib.row),Ab=a.getColumnDefinition(Ib.column),jd=0;isFinite(Ab.width)?jd=Ab.width:(isFinite(ea)&&null!==R[Ib.column]?0===cf?jd=Ab.actual+ea:jd=R[Ib.column]/cf*Ic:null!==R[Ib.column]?jd=ea:
jd=Ab.actual||ea,jd=Math.max(0,jd-Ab.vc()));var kd=0;isFinite(Jc.height)?kd=Jc.height:(isFinite(Z)&&null!==U[Ib.row]?0===oc?kd=Jc.actual+Z:kd=U[Ib.row]/oc*$d:null!==U[Ib.row]?kd=Z:kd=Jc.actual||Z,kd=Math.max(0,kd-Jc.vc()));vb.h(Math.max(Ab.minimum,Math.min(jd,Ab.maximum)),Math.max(Jc.minimum,Math.min(kd,Jc.maximum)));Wb=Il(Ib,Jc,Ab,!1);switch(Wb){case al:vb.height=Math.max(vb.height,Jc.actual+Z);break;case bl:vb.width=Math.max(vb.width,Ab.actual+ea)}var Jd=Ib.margin,Vg=Jd.right+Jd.left,Uf=Jd.top+
Jd.bottom;Ib.im();Ib.measure(vb.width,vb.height,Ab.minimum,Jc.minimum);var Vf=Ib.measuredBounds,xf=Math.max(Vf.width+Vg,0),xd=Math.max(Vf.height+Uf,0);isFinite(ea)&&(xf=Math.min(xf,vb.width));isFinite(Z)&&(xd=Math.min(xd,vb.height));var Kd=0;Kd=Jc.actual;Jc.actual=Math.max(Jc.actual,xd);hb=Jc.actual-Kd;Z=Math.max(Z-hb,0);Kd=Ab.actual;Ab.actual=Math.max(Ab.actual,xf);hb=Ab.actual-Kd;ea=Math.max(ea-hb,0)}}Ta(O);var bd=Zb.alloc(),yd=Qa(),Bb=Qa();h=I.length;if(0!==h)for(var pb=0;pb<Ga;pb++)if(y[pb]){yb=
y[pb].length;var cd=a.getRowDefinition(pb);yd[pb]=cd.actual;for(var ld=0;ld<yb;ld++)if(y[pb][ld]){var zd=a.getColumnDefinition(ld);Bb[ld]=zd.actual}}for(var Oc=0;Oc<h;Oc++){var Pa=I[Oc];if(Pa.visible||Pa===kc){var md=a.getRowDefinition(Pa.row),pc=a.getColumnDefinition(Pa.column);vb.h(Math.max(pc.minimum,Math.min(b,pc.maximum)),Math.max(md.minimum,Math.min(c,md.maximum)));Wb=Il(Pa,md,pc,!1);switch(Wb){case oe:0!==Bb[pc.index]&&(vb.width=Math.min(vb.width,Bb[pc.index]));0!==yd[md.index]&&(vb.height=
Math.min(vb.height,yd[md.index]));break;case al:0!==Bb[pc.index]&&(vb.width=Math.min(vb.width,Bb[pc.index]));break;case bl:0!==yd[md.index]&&(vb.height=Math.min(vb.height,yd[md.index]))}isFinite(pc.width)&&(vb.width=pc.width);isFinite(md.height)&&(vb.height=md.height);bd.h(0,0);for(var re=1;re<Pa.rowSpan&&!(Pa.row+re>=a.rowCount);re++)Q=a.getRowDefinition(Pa.row+re),hb=0,hb=Wb===oe||Wb===bl?Math.max(Q.minimum,0===yd[Pa.row+re]?Q.maximum:Math.min(yd[Pa.row+re],Q.maximum)):Math.max(Q.minimum,isNaN(Q.Sc)?
Q.maximum:Math.min(Q.Sc,Q.maximum)),bd.height+=hb;for(var ef=1;ef<Pa.columnSpan&&!(Pa.column+ef>=a.columnCount);ef++)Q=a.getColumnDefinition(Pa.column+ef),hb=0,hb=Wb===oe||Wb===al?Math.max(Q.minimum,0===Bb[Pa.column+ef]?Q.maximum:Math.min(Bb[Pa.column+ef],Q.maximum)):Math.max(Q.minimum,isNaN(Q.Sc)?Q.maximum:Math.min(Q.Sc,Q.maximum)),bd.width+=hb;vb.width+=bd.width;vb.height+=bd.height;var se=Pa.margin,Pc=se.right+se.left,Ee=se.top+se.bottom;Pa.measure(vb.width,vb.height,f,g);for(var nd=Pa.measuredBounds,
Mb=Math.max(nd.width+Pc,0),be=Math.max(nd.height+Ee,0),bc=0,Fe=0;Fe<Pa.rowSpan&&!(Pa.row+Fe>=a.rowCount);Fe++)Q=a.getRowDefinition(Pa.row+Fe),bc+=Q.total||0;if(bc<be){var Ld=be-bc,te=be-bc;if(null!==Pa.spanAllocation)for(var Wg=Pa.spanAllocation,od=0;od<Pa.rowSpan&&!(0>=Ld)&&!(Pa.row+od>=a.rowCount);od++){Q=a.getRowDefinition(Pa.row+od);var ff=Q.ma||0,Wf=Wg(Pa,Q,te);E&&"number"!==typeof Wf&&v(Pa+" spanAllocation does not return a number: "+Wf);Q.actual=Math.min(Q.maximum,ff+Wf);Q.ma!==ff&&(Ld-=Q.ma-
ff)}for(;0<Ld;){var Xf=Q.ma||0;isNaN(Q.height)&&Q.maximum>Xf&&(Q.actual=Math.min(Q.maximum,Xf+Ld),Q.ma!==Xf&&(Ld-=Q.ma-Xf));if(0===Q.index)break;Q=a.getRowDefinition(Q.index-1)}}for(var gf=0,Xg=0;Xg<Pa.columnSpan&&!(Pa.column+Xg>=a.columnCount);Xg++)Q=a.getColumnDefinition(Pa.column+Xg),gf+=Q.total||0;if(gf<Mb){var rg=Mb-gf,$i=Mb-gf;if(null!==Pa.spanAllocation)for(var hf=Pa.spanAllocation,Ge=0;Ge<Pa.columnSpan&&!(0>=rg)&&!(Pa.column+Ge>=a.columnCount);Ge++){Q=a.getColumnDefinition(Pa.column+Ge);var sg=
Q.ma||0,Cn=hf(Pa,Q,$i);E&&"number"!==typeof Cn&&v(Pa+" spanAllocation does not return a number: "+Cn);Q.actual=Math.min(Q.maximum,sg+Cn);Q.ma!==sg&&(rg-=Q.ma-sg)}for(;0<rg;){var mk=Q.ma||0;isNaN(Q.width)&&Q.maximum>mk&&(Q.actual=Math.min(Q.maximum,mk+rg),Q.ma!==mk&&(rg-=Q.ma-mk));if(0===Q.index)break;Q=a.getColumnDefinition(Q.index-1)}}}}Ta(I);Zb.free(bd);Zb.free(vb);void 0!==yd&&Ta(yd);void 0!==Bb&&Ta(Bb);var Yg=0,Zg=0,nk=a.desiredSize,fr=a.maxSize;Wb=pl(a,!0);var aj=ob=mc=0,bj=0;h=a.columnCount;
for(var ok=0;ok<h;ok++)void 0!==a.ob[ok]&&(Q=a.getColumnDefinition(ok),isFinite(Q.width)?(aj+=Q.width,aj+=Q.vc()):Lm(Q)===Mm?(aj+=Q.ma,aj+=Q.vc()):0!==Q.ma&&(mc+=Q.ma,mc+=Q.vc()));isFinite(nk.width)?Yg=Math.min(nk.width,fr.width):Yg=Wb!==nh&&isFinite(b)?b:mc;Yg=Math.max(Yg,a.minSize.width);Yg=Math.max(Yg-aj,0);for(var Jt=0===mc?1:Math.max(Yg/mc,1),qk=0;qk<h;qk++)void 0!==a.ob[qk]&&(Q=a.getColumnDefinition(qk),isFinite(Q.width)||Lm(Q)===Mm||(Q.actual=Q.ma*Jt),Q.position=e.width,0!==Q.ma&&(e.width+=
Q.ma,e.width+=Q.vc()));h=a.rowCount;for(var rk=0;rk<h;rk++)void 0!==a.tb[rk]&&(Q=a.getRowDefinition(rk),isFinite(Q.height)?(bj+=Q.height,bj+=Q.vc()):Lm(Q)===Mm?(bj+=Q.ma,bj+=Q.vc()):0!==Q.ma&&(ob+=Q.ma,0!==Q.ma&&(ob+=Q.vc())));isFinite(nk.height)?Zg=Math.min(nk.height,fr.height):Zg=Wb!==nh&&isFinite(c)?c:ob;Zg=Math.max(Zg,a.minSize.height);Zg=Math.max(Zg-bj,0);for(var Kt=0===ob?1:Math.max(Zg/ob,1),sk=0;sk<h;sk++)void 0!==a.tb[sk]&&(Q=a.getRowDefinition(sk),isFinite(Q.height)||Lm(Q)===Mm||(Q.actual=
Q.ma*Kt),Q.position=e.height,0!==Q.ma&&(e.height+=Q.ma,0!==Q.ma&&(e.height+=Q.vc())));h=l.length;for(var Dn=0;Dn<h;Dn++){var ce=l[Dn],En=0,Fn=0;ce.type===W.TableRow?(En=e.width,Q=a.getRowDefinition(ce.row),Fn=Q.actual):(Q=a.getColumnDefinition(ce.column),En=Q.actual,Fn=e.height);ce.measuredBounds.h(0,0,En,Fn);yj(ce,!1);y[ce.row]||(y[ce.row]=[]);y[ce.row][ce.column]||(y[ce.row][ce.column]=[]);y[ce.row][ce.column].push(ce)}Ta(l);a.kp=y};
Km.prototype.arrange=function(a,b,c){var d=b.length,e=a.padding,f=e.left;e=e.top;for(var g=a.kp,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.tb[n]||0===a.tb[n].ma);)n++;n=Math.min(n,l-1);n=-a.tb[n].position;for(h=Math.min(a.leftIndex,m-1);h!==m&&(void 0===a.ob[h]||0===a.ob[h].ma);)h++;h=Math.min(h,m-1);for(var p=-a.ob[h].position,q=Zb.alloc(),r=0;r<l;r++)if(g[r]){m=g[r].length;var u=a.getRowDefinition(r);k=u.position+n+e;0!==u.ma&&
(k+=u.Tu());for(var x=0;x<m;x++)if(g[r][x]){var y=a.getColumnDefinition(x);h=y.position+p+f;0!==y.ma&&(h+=y.Tu());for(var A=g[r][x],C=A.length,G=0;G<C;G++){var I=A[G],O=I.measuredBounds,R=I instanceof W?I:null;if(null===R||R.type!==W.TableRow&&R.type!==W.TableColumn){q.h(0,0);for(var U=1;U<I.rowSpan&&!(r+U>=a.rowCount);U++)R=a.getRowDefinition(r+U),q.height+=R.total;for(U=1;U<I.columnSpan&&!(x+U>=a.columnCount);U++)R=a.getColumnDefinition(x+U),q.width+=R.total;var ea=y.ma+q.width,Z=u.ma+q.height;
U=h;R=k;var qa=ea,xa=Z,Q=h,aa=k,Ga=ea,yb=Z;h+ea>c.width&&(Ga=Math.max(c.width-h,0));k+Z>c.height&&(yb=Math.max(c.height-k,0));var Xa=I.alignment;if(Xa.Cb()){Xa=a.defaultAlignment;Xa.Za()||(Xa=qd);var Sa=Xa.x;var Ua=Xa.y;var hb=Xa.offsetX;Xa=Xa.offsetY;var kc=y.alignment,rb=u.alignment;kc.Za()&&(Sa=kc.x,hb=kc.offsetX);rb.Za()&&(Ua=rb.y,Xa=rb.offsetY)}else Sa=Xa.x,Ua=Xa.y,hb=Xa.offsetX,Xa=Xa.offsetY;if(isNaN(Sa)||isNaN(Ua))Ua=Sa=.5,Xa=hb=0;kc=O.width;rb=O.height;var mb=I.margin,cb=mb.left+mb.right,
ua=mb.top+mb.bottom,ta=Il(I,u,y,!1);!isNaN(I.desiredSize.width)||ta!==oe&&ta!==al||(kc=Math.max(ea-cb,0));!isNaN(I.desiredSize.height)||ta!==oe&&ta!==bl||(rb=Math.max(Z-ua,0));ea=I.maxSize;Z=I.minSize;kc=Math.min(ea.width,kc);rb=Math.min(ea.height,rb);kc=Math.max(Z.width,kc);rb=Math.max(Z.height,rb);ea=rb+ua;U+=qa*Sa-(kc+cb)*Sa+hb+mb.left;R+=xa*Ua-ea*Ua+Xa+mb.top;I.visible&&(Qc(Q,aa,Ga,yb,U,R,O.width,O.height)?I.arrange(U,R,kc,rb):I.arrange(U,R,kc,rb,new L(Q,aa,Ga,yb)))}else I.kl(),I.actualBounds.ja(),
qa=I.actualBounds,U=L.allocAt(qa.x,qa.y,qa.width,qa.height),qa.x=R.type===W.TableRow?f:h,qa.y=R.type===W.TableColumn?e:k,qa.width=O.width,qa.height=O.height,I.actualBounds.freeze(),ql(I,!1),Fc(U,qa)||(O=I.part,null!==O&&(O.Ah(),I.Ko(O))),L.free(U)}}}Zb.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 Nm(){this.name="Base";this.name="TableRow"}ma(Nm,Sl);Nm.prototype.measure=function(){};Nm.prototype.arrange=function(){};function Om(){this.name="Base";this.name="TableColumn"}ma(Om,Sl);Om.prototype.measure=function(){};Om.prototype.arrange=function(){};function Pm(){this.name="Base";this.name="Viewbox"}ma(Pm,Sl);
Pm.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.im();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===ph?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&&(yj(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)};Pm.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.Cb()&&(g=a.defaultAlignment);g.Za()||(g=qd);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 Qm(){this.name="Base";this.name="Grid"}ma(Qm,Sl);
Qm.prototype.measure=function(){};Qm.prototype.arrange=function(){};function Rm(){this.name="Base";this.name="Link"}ma(Rm,Sl);
Rm.prototype.measure=function(a,b,c,d,e){c=d.length;if(a instanceof Cf||a instanceof S){var f=null,g=null,h=null;a instanceof S&&(g=f=a);a instanceof Cf&&(h=a,f=h.adornedPart);if(f instanceof S){var k=f;if(0===c)Cc(a.naturalBounds,0,0),a.measuredBounds.h(0,0,0,0);else{var l=a instanceof Cf?null:f.path,m=f.routeBounds;b=a.kg;b.h(0,0,m.width,m.height);var n=k.points;f=f.pointsCount;null!==h?h.lk(!1):null!==g&&g.lk(!1);var p=m.width,q=m.height;a.location.h(m.x,m.y);a.l.length=0;null!==l&&(Sm(a,p,q,l),
h=l.measuredBounds,b.Lc(h),a.l.push(h));h=$b.alloc();for(var r=J.alloc(),u=J.alloc(),x=0;x<c;x++){var y=d[x];if(y!==l)if(y.isPanelMain&&y instanceof Hg){Sm(a,p,q,y);var A=y.measuredBounds;b.Lc(A);a.l.push(A)}else if(2>f)y.measure(Infinity,Infinity,0,0),A=y.measuredBounds,b.Lc(A),a.l.push(A);else{var C=y.segmentIndex;A=y.segmentFraction;var G=y.alignmentFocus;G.Nb()&&(G=qd);var I=y.segmentOrientation,O=y.segmentOffset;if(C<-f||C>=f){A=k.midPoint;var R=k.midAngle;if(I!==ch){var U=k.computeAngle(y,I,
R);y.Bc=U}U=A.x-m.x;var ea=A.y-m.y}else{U=0;if(0<=C){ea=n.O(C);var Z=C<f-1?n.O(C+1):ea}else U=f+C,ea=n.O(U),Z=0<U?n.O(U-1):ea;if(ea.Sa(Z)){0<=C?(R=0<C?n.O(C-1):ea,U=C<f-2?n.O(C+2):Z):(R=U<f-1?n.O(U+1):ea,U=1<U?n.O(U-2):Z);var qa=R.Ee(ea),xa=Z.Ee(U);R=qa>xa+10?0<=C?R.Xa(ea):ea.Xa(R):xa>qa+10?0<=C?Z.Xa(U):U.Xa(Z):0<=C?R.Xa(U):U.Xa(R)}else R=0<=C?ea.Xa(Z):Z.Xa(ea);I!==ch&&(U=k.computeAngle(y,I,R),y.Bc=U);U=ea.x+(Z.x-ea.x)*A-m.x;ea=ea.y+(Z.y-ea.y)*A-m.y}y.measure(Infinity,Infinity,0,0);A=y.measuredBounds;
Z=y.naturalBounds;var Q=0;y instanceof Hg&&(Q=y.strokeWidth);qa=Z.width+Q;xa=Z.height+Q;h.reset();h.translate(-A.x,-A.y);h.scale(y.scale,y.scale);h.rotate(I===ch?y.angle:R,qa/2,xa/2);I!==Tm&&I!==Um||h.rotate(90,qa/2,xa/2);I!==Vm&&I!==Wm||h.rotate(-90,qa/2,xa/2);I===Xm&&(45<R&&135>R||225<R&&315>R)&&h.rotate(-R,qa/2,xa/2);Z=new L(0,0,qa,xa);r.Yi(Z,G);h.va(r);G=-r.x+Q/2*y.scale;y=-r.y+Q/2*y.scale;u.assign(O);Q=isNaN(O.x);var aa=isNaN(O.y);if(Q||aa){qa=qa/2+3;xa=xa/2+3;var Ga=45<=R&&135>=R,yb=225<=R&&
315>=R;I===ch&&(Ga||yb)?(u.x=aa?qa:O.y,u.y=Q?xa:O.x,Ga?0<=C||!Q||(u.y=-xa):yb&&(0<=C&&Q&&(u.y=-xa),aa&&(u.x=-qa))):(Q&&(u.x=0<=C?qa:-qa),aa&&(u.y=-xa),u.rotate(R))}else u.rotate(R);U+=u.x;ea+=u.y;Z.set(A);Z.h(U+G,ea+y,A.width,A.height);a.l.push(Z);b.Lc(Z)}}if(null!==g)for(d=g.labelNodes;d.next();)d.value.measure(Infinity,Infinity);a.kg=b;a=a.location;a.h(a.x+b.x,a.y+b.y);Cc(e,b.width||0,b.height||0);$b.free(h);J.free(r);J.free(u)}}}};
Rm.prototype.arrange=function(a,b){var c=b.length;if(a instanceof Cf||a instanceof S){var d=null,e=null,f=null;a instanceof S&&(e=d=a);a instanceof Cf&&(f=a,d=f.adornedPart);var g=a instanceof Cf?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.kg.x,l.y-a.kg.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.kg.x,n.y-a.kg.y,n.width,n.height)}}}b=d.points;c=b.count;if(2<=c&&a instanceof S)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!==ch&&(n=n.computeAngle(g,q,m),g.angle=n);n=r.x;var u=r.y}else{var x=0;0<=h?(u=b.j[h],r=h<c-1?b.j[h+1]:u):(x=c+h,u=b.j[x],r=0<x?b.j[x-1]:u);if(u.Sa(r)){0<=h?(m=0<h?b.j[h-1]:u,x=h<c-2?b.j[h+2]:r):(m=x<c-1?b.j[x+1]:u,x=1<x?b.j[x-2]:r);var y=m.Ee(u),A=r.Ee(x);m=y>A+10?0<=h?m.Xa(u):u.Xa(m):A>y+10?0<=h?r.Xa(x):x.Xa(r):
0<=h?m.Xa(x):x.Xa(m)}else m=0<=h?u.Xa(r):r.Xa(u);q!==ch&&(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.kq()?g.location=new J(n,u):(l.Nb()&&(l=qd),r=$b.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.Yi(p,l),r.va(q),l=-q.x,x=-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.aw(p),l+=p.x,x+=p.y,h=J.allocAt(n+l,u+x),g.move(h),J.free(h),
J.free(q),L.free(p),$b.free(r))}null!==f?f.lk(!1):null!==e&&e.lk(!1)}};function Sm(a,b,c,d){if(!1!==Dj(d)){var e=d.strokeWidth;0===e&&a instanceof Cf&&a.type===W.Link&&a.adornedObject instanceof Hg&&(e=a.adornedObject.strokeWidth);e*=d.Da;a instanceof S&&null!==a.sa?(a=a.sa.bounds,ml(d,a.x-e/2,a.y-e/2,a.width+e,a.height+e)):a instanceof Cf&&null!==a.adornedPart.sa?(a=a.adornedPart.sa.bounds,ml(d,a.x-e/2,a.y-e/2,a.width+e,a.height+e)):ml(d,-(e/2),-(e/2),b+e,c+e);yj(d,!1)}}
function Ym(){this.name="Base";this.name="Graduated"}ma(Ym,Sl);
Ym.prototype.measure=function(a,b,c,d,e,f,g){var h=a.Bb();a.mj=[];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.mj.push(p);e.assign(p);for(var q=h.geometry,r=h.strokeWidth,u=q.flattenedSegments,x=q.flattenedLengths,y=q.flattenedTotalLength,A=u.length,C=0,G=0,I=Qa(),O=0;O<A;O++){var R=u[O],U=[];G=C=0;for(var ea=R.length,Z=0;Z<ea;Z+=2){var qa=R[Z],xa=R[Z+1];if(0!==Z){var Q=180*Math.atan2(xa-
G,qa-C)/Math.PI;0>Q&&(Q+=360);U.push(Q)}C=qa;G=xa}I.push(U)}if(null===a.Qg){for(var aa=[],Ga=a.Z.j,yb=Ga.length,Xa=0;Xa<yb;Xa++){var Sa=Ga[Xa],Ua=[];aa.push(Ua);if(Sa.visible)for(var hb=Sa.interval,kc=0;kc<yb;kc++){var rb=Ga[kc];if(rb.visible&&Sa!==rb&&!(Sa instanceof Hg&&!(rb instanceof Hg)||Sa instanceof Kh&&!(rb instanceof Kh))){var mb=rb.interval;mb>hb&&Ua.push(mb)}}}a.Qg=aa}var cb=a.Qg;var ua=a.Z.j,ta=ua.length,wb=0,zb=0,db=y;a.oj=[];for(var qe,Yd=0;Yd<ta;Yd++){var Lb=ua[Yd];qe=[];if(Lb.visible&&
Lb!==h){var Pf=Lb.interval,Wb=a.graduatedTickUnit;if(!(2>Wb*Pf*y/a.graduatedRange)){var De=x[0][0],id=0,lc=0;zb=y*Lb.graduatedStart-1E-4;db=y*Lb.graduatedEnd+1E-4;var Zd=Wb*Pf,Wc=a.graduatedTickBase;if(Wc<a.graduatedMin){var Ze=(a.graduatedMin-Wc)/Zd;Ze=0===Ze%1?Ze:Math.floor(Ze+1);Wc+=Ze*Zd}else Wc>a.graduatedMin+Zd&&(Wc-=Math.floor((Wc-a.graduatedMin)/Zd)*Zd);for(var $e=cb[Yd];Wc<=a.graduatedMax;){a:{for(var Qf=$e.length,wf=0;wf<Qf;wf++)if(K.da((Wc-a.graduatedTickBase)%($e[wf]*a.graduatedTickUnit),
0)){var Rf=!1;break a}Rf=!0}if(Rf&&(null===Lb.graduatedSkip||!Lb.graduatedSkip(Wc))&&(wb=(Wc-a.graduatedMin)*y/a.graduatedRange,wb>y&&(wb=y),zb<=wb&&wb<=db)){for(var mc=I[id][lc],ob=x[id][lc];id<x.length;){for(;wb>De&&lc<x[id].length-1;)lc++,mc=I[id][lc],ob=x[id][lc],De+=ob;if(wb<=De)break;id++;lc=0;mc=I[id][lc];ob=x[id][lc];De+=ob}var nb=u[id],Nc=nb[2*lc],Sf=nb[2*lc+1],zc=(wb-(De-ob))/ob,$d=new J(Nc+(nb[2*lc+2]-Nc)*zc+r/2-q.bounds.x,Sf+(nb[2*lc+3]-Sf)*zc+r/2-q.bounds.y);$d.scale(h.scale,h.scale);
var Ic=mc,ae=I[id];1E-4>zc?0<lc?Ic=ae[lc-1]:K.da(nb[0],nb[nb.length-2])&&K.da(nb[1],nb[nb.length-1])&&(Ic=ae[ae.length-1]):.9999<zc&&(lc+1<ae.length?Ic=ae[lc+1]:K.da(nb[0],nb[nb.length-2])&&K.da(nb[1],nb[nb.length-1])&&(Ic=ae[0]));mc!==Ic&&(180<Math.abs(mc-Ic)&&(mc<Ic?mc+=360:Ic+=360),mc=(mc+Ic)/2%360);if(Lb instanceof Kh){var nc="";null!==Lb.graduatedFunction?(nc=Lb.graduatedFunction(Wc),nc=null!==nc&&void 0!==nc?nc.toString():""):nc=(+Wc.toFixed(2)).toString();""!==nc&&qe.push([$d,mc,nc])}else qe.push([$d,
mc])}Wc+=Zd}}}a.oj.push(qe)}Ta(I);for(var Zh=a.oj,$h=d.length,af=0;af<$h;af++){var Fb=d[af],Tf=Zh[af];if(Fb.visible&&Fb!==h&&0!==Tf.length){if(Fb instanceof Hg){var bf=a,oc=e,cf=Fb.alignmentFocus;cf.Nb()&&(cf=gd);var ad=Fb.angle;Fb.Bc=0;Fb.measure(Infinity,Infinity,0,0);Fb.Bc=ad;var vb=Fb.measuredBounds,df=vb.width,Ib=vb.height,Jc=L.allocAt(0,0,df,Ib),Ab=J.alloc();Ab.Yi(Jc,cf);L.free(Jc);for(var jd=-Ab.x,kd=-Ab.y,Jd=new L,Vg=Tf.length,Uf=0;Uf<Vg;Uf++)for(var Vf=Tf[Uf],xf=Vf[0].x,xd=Vf[0].y,Kd=Vf[1],
bd=0;4>bd;bd++){switch(bd){case 0:Ab.h(jd,kd);break;case 1:Ab.h(jd+df,kd);break;case 2:Ab.h(jd,kd+Ib);break;case 3:Ab.h(jd+df,kd+Ib)}Ab.rotate(Kd+Fb.angle);Ab.offset(xf,xd);0===Uf&&0===bd?Jd.h(Ab.x,Ab.y,0,0):Jd.Le(Ab);Ab.offset(-xf,-xd);Ab.rotate(-Kd-Fb.angle)}J.free(Ab);bf.mj.push(Jd);Mc(oc,Jd.x,Jd.y,Jd.width,Jd.height)}else if(Fb instanceof Kh){var yd=a,Bb=e;null===yd.lh&&(yd.lh=new Kh);var pb=yd.lh;Zm(pb,Fb);var cd=Fb.alignmentFocus;cd.Nb()&&(cd=gd);for(var ld=Fb.segmentOrientation,zd=Fb.segmentOffset,
Oc=null,Pa=0,md=0,pc=0,re=0,ef=Tf.length,se=0;se<ef;se++){var Pc=Tf[se];Pa=Pc[0].x;md=Pc[0].y;pc=Pc[1];ld!==ch&&(re=S.computeAngle(ld,pc),pb.Bc=re);pb.text=Pc[2];pb.measure(Infinity,Infinity,0,0);var Ee=pb.measuredBounds,nd=pb.naturalBounds,Mb=nd.width,be=nd.height,bc=$b.alloc();bc.reset();bc.translate(-Ee.x,-Ee.y);bc.scale(pb.scale,pb.scale);bc.rotate(ld===ch?pb.angle:pc,Mb/2,be/2);ld!==Tm&&ld!==Um||bc.rotate(90,Mb/2,be/2);ld!==Vm&&ld!==Wm||bc.rotate(-90,Mb/2,be/2);ld===Xm&&(45<pc&&135>pc||225<pc&&
315>pc)&&bc.rotate(-pc,Mb/2,be/2);var Fe=L.allocAt(0,0,Mb,be),Ld=J.alloc();Ld.Yi(Fe,cd);bc.va(Ld);var te=-Ld.x,Wg=-Ld.y,od=J.alloc();od.assign(zd);isNaN(od.x)&&(od.x=Mb/2+3);isNaN(od.y)&&(od.y=-(be/2+3));od.rotate(pc);Pa+=od.x+te;md+=od.y+Wg;var ff=new L(Pa,md,Ee.width,Ee.height),Wf=new L(Ee.x,Ee.y,Ee.width,Ee.height),Xf=new L(nd.x,nd.y,nd.width,nd.height),gf=new $m;gf.$l(pb.metrics);Pc.push(re);Pc.push(pb.lineCount);Pc.push(gf);Pc.push(ff);Pc.push(Wf);Pc.push(Xf);0===se?Oc=ff.copy():Oc.Lc(ff);J.free(od);
J.free(Ld);L.free(Fe);$b.free(bc)}yd.mj.push(Oc);Mc(Bb,Oc.x,Oc.y,Oc.width,Oc.height)}yj(Fb,!1)}}};Ym.prototype.arrange=function(a,b,c){if(null!==a.mj){var d=a.Bb(),e=a.oj,f=a.mj,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.mj=null}};
function W(a){N.call(this);void 0===a?this.wa=W.Position:(w(a,Sl,W,"type"),this.wa=a);null===this.wa&&v("Panel type not specified or PanelLayout not loaded: "+a);this.Z=new F;this.gb=Zc;this.wa===W.Grid&&(this.isAtomic=!0);this.rn=Qd;this.Gf=$k;this.wa===W.Table&&an(this);this.Mp=ph;this.Pn=vc;this.Qn=gc;this.Mn=0;this.Ln=100;this.On=10;this.Nn=0;this.Th=this.kb=this.Qg=this.mj=this.oj=null;this.co=NaN;this.le=this.hi=null;this.ll="category";this.Gd=null;this.kg=new L(NaN,NaN,NaN,NaN);this.lh=this.kp=
this.xi=null;this.Bg=""}ma(W,N);function an(a){a.ij=Zc;a.Kg=1;a.Yh=null;a.Xh=null;a.Jg=1;a.Ig=null;a.Wh=null;a.tb=[];a.ob=[];a.Kj=bn;a.gj=bn;a.Ai=0;a.ji=0}
W.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.wa=this.wa;a.gb=this.gb.J();a.rn=this.rn.J();a.Gf=this.Gf;if(a.wa===W.Table){a.ij=this.ij.J();a.Kg=this.Kg;a.Yh=this.Yh;a.Xh=this.Xh;a.Jg=this.Jg;a.Ig=this.Ig;a.Wh=this.Wh;var b=[];if(0<this.tb.length)for(var c=this.tb,d=c.length,e=0;e<d;e++)if(void 0!==c[e]){var f=c[e].copy();f.Xi(a);b[e]=f}a.tb=b;b=[];if(0<this.ob.length)for(c=this.ob,d=c.length,e=0;e<d;e++)void 0!==c[e]&&(f=c[e].copy(),f.Xi(a),b[e]=f);a.ob=b;a.Kj=
this.Kj;a.gj=this.gj;a.Ai=this.Ai;a.ji=this.ji}a.Mp=this.Mp;a.Pn=this.Pn.J();a.Qn=this.Qn.J();a.Mn=this.Mn;a.Ln=this.Ln;a.On=this.On;a.Nn=this.Nn;a.oj=this.oj;a.Qg=this.Qg;a.kb=this.kb;a.Th=this.Th;a.co=this.co;a.hi=this.hi;a.le=this.le;a.ll=this.ll;a.kg.assign(this.kg);a.Bg=this.Bg;null!==this.kp&&(a.kp=this.kp)};W.prototype.qf=function(a){N.prototype.qf.call(this,a);a.Z=this.Z;for(var b=a.Z.j,c=b.length,d=0;d<c;d++)b[d].cg=a;a.xi=null};
W.prototype.copy=function(){var a=N.prototype.copy.call(this);if(null!==a){for(var b=this.Z.j,c=b.length,d=0;d<c;d++){var e=b[d].copy();e.Xi(a);e.Fj=null;var f=a.Z,g=f.count;f.Lb(g,e);f=a.part;if(null!==f){f.Aj=null;null!==e.portId&&f instanceof V&&(f.zh=!0);var h=a.diagram;null!==h&&h.undoManager.isUndoingRedoing||f.cb(qf,"elements",a,null,e,null,g)}}return a}return null};t=W.prototype;t.toString=function(){return"Panel("+this.type+")#"+Jb(this)};
t.Ko=function(a){N.prototype.Ko.call(this,a);for(var b=this.Z.j,c=b.length,d=0;d<c;d++)b[d].Ko(a)};
t.Hi=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.Z.j,q=p.length,r=0;r<q;r++){var u=p[r],x=[];n.push(x);if(u.visible){u=gk(u.figure);for(var y=r+1;y<q;y++){var A=p[y];A.visible&&gk(A.figure)===u&&(A=A.interval,2<=A&&x.push(A))}}}p=this.Z.j;q=p.length;
for(r=0;r<q;r++){var C=p[r];if(C.visible&&(x=C.interval,!(2>d*x*b))){u=C.opacity;y=1;if(1!==u){if(0===u)continue;y=a.globalAlpha;a.globalAlpha=y*u}A=n[r];var G=!1,I=C.strokeDashArray;null!==I&&(G=!0,a.Us(I,C.strokeDashOffset));if("LineV"===C.figure&&null!==C.stroke){a.lineWidth=C.strokeWidth;yi(this,a,C.stroke,!1,!1,e,f);a.beginPath();for(I=C=Math.floor(-m.x/d);I<=C+k;I++){var O=I*d+m.x;0<=O&&O<=g&&cn(I,x,A)&&(a.moveTo(O,0),a.lineTo(O,h))}a.stroke()}else if("LineH"===C.figure&&null!==C.stroke){a.lineWidth=
C.strokeWidth;yi(this,a,C.stroke,!1,!1,e,f);a.beginPath();for(I=C=Math.floor(-m.y/c);I<=C+l;I++)O=I*c+m.y,0<=O&&O<=h&&cn(I,x,A)&&(a.moveTo(0,O),a.lineTo(g,O));a.stroke()}else if("BarV"===C.figure&&null!==C.fill)for(yi(this,a,C.fill,!0,!1,e,f),C=C.width,isNaN(C)&&(C=d),O=I=Math.floor(-m.x/d);O<=I+k;O++){var R=O*d+m.x;0<=R&&R<=g&&cn(O,x,A)&&a.fillRect(R,0,C,h)}else if("BarH"===C.figure&&null!==C.fill)for(yi(this,a,C.fill,!0,!1,e,f),C=C.height,isNaN(C)&&(C=c),O=I=Math.floor(-m.y/c);O<=I+l;O++)R=O*c+
m.y,0<=R&&R<=h&&cn(O,x,A)&&a.fillRect(0,R,g,C);G&&a.Ss();1!==u&&(a.globalAlpha=y)}}a.restore();a.Uc(!1)}else if(this.wa===W.Graduated){d=b.rj;b.rj=!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.Bb();c.jc(a,b);e=this.Fe()*b.scale;0>=e&&(e=1);f=c.actualBounds;g=this.Z.j;h=this.oj;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 Hg){if(!(2>this.graduatedTickUnit*p.interval*e))for(q=p.measuredBounds,
r=p.strokeWidth*p.scale,x=p.alignmentFocus,x.Nb()&&(x=gd),u=0;u<n;u++)y=m[u][0],A=m[u][1],G=x,C=p.ub,C.reset(),C.translate(y.x+f.x,y.y+f.y),C.rotate(A+p.angle,0,0),C.translate(-q.width*G.x+G.offsetX+r/2,-q.height*G.y+G.offsetY+r/2),C.scale(p.scale,p.scale),Fl(p,!1),p.Gh.set(p.ub),p.Xk=p.scale,Gl(p,!1),p.jc(a,b),p.ub.reset()}else if(p instanceof Kh)for(null===this.lh&&(this.lh=new Kh),q=this.lh,Zm(q,p),p=0;p<n;p++)u=m[p],3<u.length&&(r=u[6],q.Rb=u[2],q.Bc=u[3],q.pc=u[4],q.pd=u[5],q.rc=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),x=u[7],u=u[8],y=q.ub,y.reset(),y.translate(r.x+f.x,r.y+f.y),y.translate(-x.x,-x.y),nl(q,y,u.x,u.y,u.width,u.height),Fl(q,!1),q.Gh.set(q.ub),q.Xk=q.scale,Gl(q,!1),q.jc(a,b));b.rj=d;a.restore();a.Uc(!0)}else{this.wa===W.Table&&(a.lineCap="butt",dn(this,a,!0,this.tb,!0),dn(this,a,!1,this.ob,!0),en(this,a,!0,this.tb),en(this,a,!1,this.ob),dn(this,a,!0,this.tb,!1),dn(this,a,!1,this.ob,!1));if(d=this.isClipping)a.save(),E&&this.type!==W.Spot&&
Ha("Warning: Panel.isClipping set on non-Spot Panel: "+this.toString());c=this.Bb();e=this.Z.j;f=e.length;for(g=0;g<f;g++)h=e[g],d&&h===c&&(a.clipInsteadOfFill=!0),h.jc(a,b),d&&h===c&&(a.clipInsteadOfFill=!1);d&&(a.restore(),a.Uc(!0))}};
function en(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.Kg:a.Jg);var n=l.separatorStroke;null===n&&(n=c?a.Yh:a.Ig);if(0!==m&&null!==n){yi(a,b,n,!1,!1,g,f);n=!1;var p=l.separatorDashArray;null===p&&(p=c?a.Xh:a.Wh);null!==p&&(n=!0,b.Us(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.gb;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.Ss()}}}}
function dn(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.vc(),p=l.separatorStrokeWidth;isNaN(p)&&(p=c?a.Kg:a.Jg);var q=l.separatorStroke;null===q&&(q=c?a.Yh:a.Ig);null===q&&(p=0);n-=p;p=l.position+p;n+=l.actual;p+n>m&&(n=m-p);0>=n||(m=a.gb,yi(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 cn(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 gk(a){return"LineV"===a||"BarV"===a}
t.gk=function(a,b,c,d,e){var f=this.ae(),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.Wc(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.Wc(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.Z.j;q=n.length;m=J.alloc();p=null;b=Infinity;var r=null;this.isClipping&&(r=J.alloc(),p=this.Bb(),(l=p.gk(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 x=n[u];x.visible&&x!==p&&x.gk(h,a,k,c,m)&&(l=!0,x=(h-m.x)*(h-m.x)+(a-m.y)*(a-m.y),x<d&&(d=x,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.Bb();for(var b=this.Z.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=pl(e,!1);(e instanceof lh||e instanceof W||e instanceof Kh||f!==nh)&&e.v(!0)}}};t.im=function(){if(!1===Dj(this)){yj(this,!0);ql(this,!0);for(var a=this.Z.j,b=a.length,c=0;c<b;c++)a[c].im()}};
t.kl=function(){if(0!==(this.I&2048)===!1){Fl(this,!0);Gl(this,!0);for(var a=this.Z.j,b=a.length,c=0;c<b;c++)a[c].qv()}};t.qv=function(){Gl(this,!0);for(var a=this.Z.j,b=a.length,c=0;c<b;c++)a[c].qv()};
t.mm=function(a,b,c,d){var e=this.kg;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.gb;a=Math.max(a-k.left-k.right,0);b=Math.max(b-k.top-k.bottom,0);var l=this.Z.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);Cc(e,a,k);Cc(this.naturalBounds,a,k);ml(this,0,0,a,k)};t.Bb=function(){if(null===this.xi){var a=this.Z.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.xi=d}this.xi=a[0]}return this.xi};function Dm(a){return null!==a.part?a.part.locationObject:null}
t.vh=function(a,b,c,d){var e=this.Z.j;this.actualBounds.h(a,b,c,d);if(0!==e.length){if(!this.desiredSize.o()){a=pl(this,!0);var f=this.measuredBounds;b=f.width;f=f.height;var g=this.Xg,h=g.left+g.right;g=g.top+g.bottom;b===c&&f===d&&(a=nh);switch(a){case nh:if(b>c||f>d)this.v(),this.measure(b>c?c:b,f>d?d:f,0,0);break;case oe:this.v(!0);this.measure(c+h,d+g,0,0);break;case al:this.v(!0);this.measure(c+h,f+g,0,0);break;case bl:this.v(!0),this.measure(b+h,d+g,0,0)}}this.wa.arrange(this,e,this.kg)}};
t.xh=function(a){var b=this.naturalBounds,c=Dm(this);if(Qc(0,0,b.width,b.height,a.x,a.y)){b=this.Z.j;for(var d=b.length,e=J.allocAt(0,0);d--;){var f=b[d];if(f.visible||f===c)if(ac(e.set(a),f.transform),f.ea(e))return J.free(e),!0}J.free(e);return null===this.jb&&null===this.fc?!1:!0}return!1};t.Vs=function(a){if(this.Ik===a)return this;for(var b=this.Z.j,c=b.length,d=0;d<c;d++){var e=b[d].Vs(a);if(null!==e)return e}return null};
t.xk=function(a,b){b(this,a);if(a instanceof W){a=a.Z.j;for(var c=a.length,d=0;d<c;d++)this.xk(a[d],b)}};function Qj(a,b){fn(a,a,b)}function fn(a,b,c){c(b);b=b.Z.j;for(var d=b.length,e=0;e<d;e++){var f=b[e];f instanceof W&&fn(a,f,c)}}function gn(a,b){hn(a,a,b)}function hn(a,b,c){c(b);if(b instanceof W){b=b.Z.j;for(var d=b.length,e=0;e<d;e++)hn(a,b[e],c)}}t.cm=function(a){return jn(this,this,a)};
function jn(a,b,c){if(c(b))return b;if(b instanceof W){b=b.Z.j;for(var d=b.length,e=0;e<d;e++){var f=jn(a,b[e],c);if(null!==f)return f}}return null}t.bb=function(a){if(this.name===a)return this;var b=this.Z.j,c=b.length;null===this.hi&&null===this.le||(c=kn(this));for(var d=0;d<c;d++){var e=b[d];if(e instanceof W){var f=e.bb(a);if(null!==f)return f}if(e.name===a)return e}return null};
function ln(a){a=a.Z.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,ln(e));else if(e instanceof Hg){a:{switch(e.Zk){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.jh/2*e.Oj*e.Fe()}c=Math.max(c,e)}}return c}t.ae=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(Ej(this))return null;var d=this.naturalBounds,e=1/this.Fe(),f=this.ae(),g=f?a:ac(J.allocAt(a.x,a.y),this.transform),h=this.diagram,k=10,l=5;null!==h&&(k=h.gm("extraTouchArea"),l=k/2);if(Qc(-(l*e),-(l*e),d.width+k*e,d.height+k*e,g.x,g.y)){if(!this.isAtomic){e=this.Z.j;var m=e.length;h=J.alloc();l=(k=this.isClipping)?this.Bb():null;if(k&&(l.ae()?ac(h.set(a),l.transform):h.set(a),!l.ea(h)))return J.free(h),
f||J.free(g),null;for(var n=Dm(this);m--;){var p=e[m];if(p.visible||p===n)if(p.ae()?ac(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.ea(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=Qc(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.Ki=function(a,b,c,d){if(!1===this.pickable)return!1;void 0===b&&(b=null);void 0===c&&(c=null);var e=this.naturalBounds,f=this.ae(),g=f?a:ac(J.allocAt(a.x,a.y),this.transform),h=this.type===W.TableRow||this.type===W.TableColumn;e=Qc(0,0,e.width,e.height,g.x,g.y);if(h||e){if(!this.isAtomic){h=this.Z.j;for(var k=h.length,l=J.alloc(),m=Dm(this);k--;){var n=h[k];if(n.visible||n===m){n.ae()?ac(l.set(a),n.transform):l.set(a);var p=n;n=n instanceof W?n:null;(null!==n?n.Ki(l,b,c,d):p.ea(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.pg=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=$b.alloc(),g.reset());g.multiply(this.transform);if(this.wh(a,g))return mn(this,b,c,e),void 0===f&&$b.free(g),!0;if(this.Kc(a,g)){if(!this.isAtomic)for(var h=Dm(this),k=this.Z.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=$b.alloc();p.set(g);
if(null!==m?m.pg(a,b,c,d,e,p):ol(n,a,d,p))null!==b&&(n=b(n)),null===n||null!==c&&!c(n)||e.add(n);$b.free(p)}}}void 0===f&&$b.free(g);return d}void 0===f&&$b.free(g);return!1};function mn(a,b,c,d){for(var e=a.Z.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&&mn(g,b,c,d),null!==b&&(g=b(g)),null===g||null!==c&&!c(g)||d.add(g))}}}
t.qg=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.ae(),k=h?a:ac(J.allocAt(a.x,a.y),this.transform),l=h?b:ac(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||cc(k.x,k.y,0,0,0,g.height)<=m||cc(k.x,k.y,0,g.height,g.width,g.height)<=m||cc(k.x,k.y,g.width,g.height,g.width,0)<=m||cc(k.x,k.y,g.width,0,0,0)<=m;g=k.ed(0,0)<=m&&k.ed(0,g.height)<=m&&k.ed(g.width,0)<=m&&k.ed(g.width,g.height)<=
m;h||(J.free(k),J.free(l));if(n){if(!this.isAtomic){k=J.alloc();l=J.alloc();m=Dm(this);for(var p=this.Z.j,q=p.length;q--;){var r=p[q];if(r.visible||r===m){var u=r.actualBounds,x=this.naturalBounds;if(!h||!(u.x>x.width||u.y>x.height||0>u.x+u.width||0>u.y+u.height))if(r.ae()?(u=r.transform,ac(k.set(a),u),ac(l.set(b),u)):(k.set(a),l.set(b)),u=r,r=r instanceof W?r:null,null!==r?r.qg(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 Im(a){var b=null;a instanceof Hg&&(b=a.spot1,b===Qd&&(b=null),a=a.geometry,null!==a&&null===b&&(b=a.spot1));null===b&&(b=fd);return b}function Jm(a){var b=null;a instanceof Hg&&(b=a.spot2,b===Qd&&(b=null),a=a.geometry,null!==a&&null===b&&(b=a.spot2));null===b&&(b=ud);return b}t.add=function(a){w(a,N,W,"add:element");this.Lb(this.Z.count,a)};t.O=function(a){return this.Z.O(a)};
t.Lb=function(a,b){b instanceof T&&v("Cannot add a Part to a Panel: "+b+"; use a Panel instead");if(this===b||this.tg(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 Hg||v("Can only add Shapes to a Grid Panel, not: "+b);this.wa!==W.Graduated||b instanceof Hg||b instanceof Kh||v("Can only add Shapes or TextBlocks to a Graduated Panel, not: "+b);b.Xi(this);b.Fj=null;if(null!==this.itemArray){var d=b.data;null!==d&&"object"===typeof d&&(null===this.Gd&&(this.Gd=new Ub),this.Gd.add(d,b))}var e=this.Z;d=-1;if(c===this){for(var f=-1,g=this.Z.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.nb(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.Lb(a,b);if(0===a||b.isPanelMain)this.xi=null;Dj(this)||this.v();b.v(!1);null!==b.portId?this.zh=!0:b instanceof W&&!0===b.zh&&(this.zh=!0);this.Qg=null;c=this.part;null!==c&&(c.Aj=null,c.Yg=NaN,this.zh&&c instanceof V&&(c.zh=!0),c.zh&&c instanceof V&&(c.tc=null),e=this.diagram,null!==e&&e.undoManager.isUndoingRedoing||(-1!==d&&c.cb(rf,"elements",this,b,null,d,null),c.cb(qf,
"elements",this,null,b,null,a),this.ug()||nn(this,b,!1)))};function on(a,b){a.I=b?a.I|16777216:a.I&-16777217}t.remove=function(a){w(a,N,W,"remove:element");for(var b=this.Z.j,c=b.length,d=-1,e=0;e<c;e++)if(b[e]===a){d=e;break}-1!==d&&this.zc(d,!0)};t.nb=function(a){E&&B(a,W,"removeAt:idx");0<=a&&this.zc(a,!0)};
t.zc=function(a,b){var c=this.Z,d=c.O(a);d.Fj=null;d.Xi(null);if(null!==this.Gd){var e=d.data;"object"===typeof e&&this.Gd.remove(e)}c.nb(a);yj(this,!1);this.v();this.xi===d&&(this.xi=null);this.Qg=null;var f=this.part;null!==f&&(f.Aj=null,f.Yg=NaN,f.Mb(),f instanceof V&&(d instanceof W?d.xk(d,function(a,c){Wl(f,c,b)}):Wl(f,d,b)),c=this.diagram,null!==c&&c.undoManager.isUndoingRedoing||f.cb(rf,"elements",this,d,null,a,null))};
W.prototype.getRowDefinition=function(a){E&&B(a,W,"getRowDefinition:idx");0>a&&Ca(a,">= 0",W,"getRowDefinition:idx");a=Math.round(a);var b=this.tb;if(void 0===b)return null;if(void 0===b[a]){var c=new ek;c.Xi(this);c.isRow=!0;c.index=a;b[a]=c}return b[a]};W.prototype.Hv=function(a){E&&B(a,W,"removeRowDefinition:idx");0>a&&Ca(a,">= 0",W,"removeRowDefinition:idx");a=Math.round(a);var b=this.tb;void 0!==b&&(this.cb(rf,"coldefs",this,b[a],null,a,null),b[a]&&delete b[a],this.v())};
W.prototype.getColumnDefinition=function(a){E&&B(a,W,"getColumnDefinition:idx");0>a&&Ca(a,">= 0",W,"getColumnDefinition:idx");a=Math.round(a);var b=this.ob;if(void 0===b)return null;if(void 0===b[a]){var c=new ek;c.Xi(this);c.isRow=!1;c.index=a;b[a]=c}return b[a]};t=W.prototype;t.Fv=function(a){E&&B(a,W,"removeColumnDefinition:idx");0>a&&Ca(a,">= 0",W,"removeColumnDefinition:idx");a=Math.round(a);var b=this.ob;void 0!==b&&(this.cb(rf,"coldefs",this,b[a],null,a,null),b[a]&&delete b[a],this.v())};
t.$y=function(a){if(0>a||this.type!==W.Table)return-1;for(var b=0,c=this.tb,d=c.length,e=this.Ai;e<d;e++){var f=c[e];if(void 0!==f&&(b+=f.total,a<b))break}return e};t.Sy=function(a){if(0>a||this.type!==W.Table)return-1;for(var b=0,c=this.ob,d=c.length,e=this.ji;e<d;e++){var f=c[e];if(void 0!==f&&(b+=f.total,a<b))break}return e};
t.rz=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.Bb();c.geometry.kv((a-this.graduatedMin)/this.graduatedRange,b);return c.transform.va(b)};t.sz=function(a){if(this.type!==W.Graduated)return NaN;var b=this.Bb();b.transform.Wd(a);return b.geometry.qx(a)*this.graduatedRange+this.graduatedMin};function Nl(a){a=a.Th;return null!==a&&a.u}
function mh(a){var b=a.Th;if(null===b)null!==a.data&&v("Template cannot have .data be non-null: "+a),a.Th=b=new F;else if(b.u)return;var c=new F;on(a,!1);a.xk(a,function(a,d){var e=d.eb;if(null!==e)for(Kl(d,!1),e=e.iterator;e.next();){var f=e.value;f.mode===pn&&Kl(d,!0);var g=f.sourceName;null!==g&&("/"===g&&on(a,!0),g=ll(f,a,d),null!==g&&(c.add(g),null===g.Kl&&(g.Kl=new F),g.Kl.add(f)));b.add(f)}if(d instanceof W&&d.type===W.Table){if(0<d.tb.length)for(a=d.tb,e=a.length,f=0;f<e;f++)if(g=a[f],void 0!==
g&&null!==g.eb)for(var h=g.eb.iterator;h.next();){var k=h.value;k.Sd=g;k.Dp=2;k.Sl=g.index;b.add(k)}if(0<d.ob.length)for(d=d.ob,a=d.length,e=0;e<a;e++)if(f=d[e],void 0!==f&&null!==f.eb)for(g=f.eb.iterator;g.next();)h=g.value,h.Sd=f,h.Dp=1,h.Sl=f.index,b.add(h)}});for(var d=c.iterator;d.next();){var e=d.value;if(null!==e.Kl){Kl(e,!0);for(var f=e.Kl.iterator;f.next();){var g=f.value;null===e.eb&&(e.eb=new F);e.eb.add(g)}}e.Kl=null}for(var h=b.iterator;h.next();)if(d=h.value,e=d.Sd,null!==e){d.Sd=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.bb(f),null!==k?(e=k,d.targetProperty=g):Ha('Warning: unable to find GraphObject named "'+f+'" for Binding: '+d.toString()));e instanceof ek?(f=Jb(e.panel),d.bj=void 0===f?-1:f,e.panel.Ik=d.bj):e instanceof N?(f=Jb(e),d.bj=void 0===f?-1:f,e.Ik=d.bj):v("Unknown type of binding target: "+e)}b.freeze();a instanceof T&&(a.dc()&&a.bc(),E&&!qn&&a.xk(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 T)){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||(Ha("Auto, Spot, or Graduated Panel should not have zero or one elements: "+c.toString()+" in "+a.toString()),qn=!0)}}))}t.Cy=function(){var a=this.copy();gn(a,function(a){a instanceof W&&(a.Th=null,a.kb=null);var b=a.eb;null!==b&&(a.eb=null,b.each(function(b){a.bind(b.copy())}))});return a};
t.Fa=function(a){var b=this.Th;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.bb(e);else{var f=this.diagram;null!==f&&c.isToModel&&(d=f.model.modelData)}if(null===d)E&&Ha("Binding error: missing GraphObject named "+e+" in "+this.toString());else{f=this;var g=c.bj;if(-1!==g){if(f=
this.Vs(g),null===f)continue}else null!==c.Sd&&(f=c.Sd);"/"===e?d=f.part:"."===e?d=f:".."===e&&(d=f.panel);e=c.Dp;if(0!==e){if(!(f instanceof W))continue;1===e?f=f.getColumnDefinition(c.Sl):2===e&&(f=f.getRowDefinition(c.Sl))}void 0!==f&&c.dw(f,d)}}}};
function rn(a,b){a=a.Z.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 kn(a){if(a.type===W.Spot||a.type===W.Auto)return Math.min(a.Z.length,1);if(a.type===W.Link){a=a.Z;for(var b=a.length,c=0;c<b;c++){var d=a.O(c);if(!(d instanceof Hg&&d.isPanelMain))break}return c}return a.type===W.Table&&0<a.Z.length&&(a=a.Z.O(0),a.isPanelMain&&a instanceof W&&(a.type===W.TableRow||a.type===W.TableColumn))?1:0}t.st=function(){for(var a=kn(this);this.Z.length>a;)this.zc(this.Z.length-1,!1);a=this.itemArray;if(null!==a)for(var b=a.length,c=0;c<b;c++)sn(this,a[c],c)};
t.mx=function(a){if(void 0===a||null===a||null===this.Gd)return null;z(a,"object",W,"findItemPanelForData");return this.Gd.K(a)};
function sn(a,b,c){if(!(void 0===b||null===b||0>c)){var d=tn(a,b),e=a.itemTemplateMap,f=null;null!==e&&(f=e.K(d));null===f&&(un||(un=!0,Ha('No item template Panel found for category "'+d+'" on '+a),Ha(" Using default item template."),d=new W,e=new Kh,e.bind(new Ti("text","",Wa)),d.add(e),vn=d),f=vn);d=f;null!==d&&(mh(d),d=d.copy(),0!==(d.I&16777216)&&(e=a.Li(),null!==e&&on(e,!0)),"object"===typeof b&&(null===a.Gd&&(a.Gd=new Ub),a.Gd.add(b,d)),e=c+kn(a),a.Lb(e,d),d.kb=b,wn(a,e,c),d.kb=null,d.data=
b)}}function wn(a,b,c){for(a=a.Z;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 tn(a,b){if(null===b)return"";a=a.ll;if("function"===typeof a)a=a(b);else if("string"===typeof a&&"object"===typeof b){if(""===a)return"";a=xn(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 nn(a,b,c){var d=b.enabledChanged;null!==d&&d(b,c);if(b instanceof W){b=b.Z.j;d=b.length;for(var e=0;e<d;e++){var f=b[e];c&&f instanceof W&&!f.isEnabled||nn(a,f,c)}}}function yn(a,b){Rl.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&&an(this),this.v(),this.g("type",b,a))}},elements:{configurable:!0,get:function(){return this.Z.iterator}},naturalBounds:{configurable:!0,get:function(){return this.rc}},padding:{configurable:!0,get:function(){return this.gb},set:function(a){"number"===
typeof a?(0>a&&Ca(a,">= 0",W,"padding"),a=new Hc(a)):(w(a,Hc,W,"padding"),0>a.left&&Ca(a.left,">= 0",W,"padding:value.left"),0>a.right&&Ca(a.right,">= 0",W,"padding:value.right"),0>a.top&&Ca(a.top,">= 0",W,"padding:value.top"),0>a.bottom&&Ca(a.bottom,">= 0",W,"padding:value.bottom"));var b=this.gb;b.A(a)||(this.gb=a=a.J(),this.v(),this.g("padding",b,a))}},defaultAlignment:{configurable:!0,get:function(){return this.rn},set:function(a){var b=this.rn;b.A(a)||(E&&w(a,M,W,"defaultAlignment"),
this.rn=a=a.J(),this.v(),this.g("defaultAlignment",b,a))}},defaultStretch:{configurable:!0,get:function(){return this.Gf},set:function(a){var b=this.Gf;b!==a&&(tb(a,N,W,"defaultStretch"),this.Gf=a,this.v(),this.g("defaultStretch",b,a))}},defaultSeparatorPadding:{configurable:!0,get:function(){return void 0===this.ij?Zc:this.ij},set:function(a){if(void 0!==this.ij){"number"===typeof a?a=new Hc(a):E&&w(a,Hc,W,"defaultSeparatorPadding");var b=this.ij;b.A(a)||(this.ij=a=a.J(),
this.v(),this.g("defaultSeparatorPadding",b,a))}}},defaultRowSeparatorStroke:{configurable:!0,get:function(){return void 0===this.Yh?null:this.Yh},set:function(a){var b=this.Yh;b!==a&&(null===a||"string"===typeof a||a instanceof yl)&&(a instanceof yl&&a.freeze(),this.Yh=a,this.S(),this.g("defaultRowSeparatorStroke",b,a))}},defaultRowSeparatorStrokeWidth:{configurable:!0,get:function(){return void 0===this.Kg?1:this.Kg},set:function(a){if(void 0!==this.Kg){var b=this.Kg;
b!==a&&isFinite(a)&&0<=a&&(this.Kg=a,this.v(),this.g("defaultRowSeparatorStrokeWidth",b,a))}}},defaultRowSeparatorDashArray:{configurable:!0,get:function(){return void 0===this.Xh?null:this.Xh},set:function(a){if(void 0!==this.Xh){var b=this.Xh;if(b!==a){null===a||Array.isArray(a)||Ba(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.Xh=a;this.S();this.g("defaultRowSeparatorDashArray",b,a)}}}},defaultColumnSeparatorStroke:{configurable:!0,get:function(){return void 0===this.Ig?null:this.Ig},set:function(a){if(void 0!==this.Ig){var b=this.Ig;b!==a&&(null===a||"string"===typeof a||a instanceof yl)&&(a instanceof yl&&a.freeze(),this.Ig=a,this.S(),this.g("defaultColumnSeparatorStroke",b,a))}}},defaultColumnSeparatorStrokeWidth:{configurable:!0,
enumerable:!0,get:function(){return void 0===this.Jg?1:this.Jg},set:function(a){if(void 0!==this.Jg){var b=this.Jg;b!==a&&isFinite(a)&&0<=a&&(this.Jg=a,this.v(),this.g("defaultColumnSeparatorStrokeWidth",b,a))}}},defaultColumnSeparatorDashArray:{configurable:!0,get:function(){return void 0===this.Wh?null:this.Wh},set:function(a){if(void 0!==this.Wh){var b=this.Wh;if(b!==a){null===a||Array.isArray(a)||Ba(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.Wh=a;this.S();this.g("defaultColumnSeparatorDashArray",b,a)}}}},viewboxStretch:{configurable:!0,get:function(){return this.Mp},set:function(a){var b=this.Mp;b!==a&&(tb(a,N,W,"viewboxStretch"),this.Mp=a,this.v(),this.g("viewboxStretch",b,a))}},gridCellSize:{configurable:!0,
enumerable:!0,get:function(){return this.Pn},set:function(a){var b=this.Pn;if(!b.A(a)){w(a,Zb,W,"gridCellSize");a.o()&&0!==a.width&&0!==a.height||v("Invalid Panel.gridCellSize: "+a);this.Pn=a.J();var c=this.diagram;null!==c&&this===c.grid&&zj(c);this.S();this.g("gridCellSize",b,a)}}},gridOrigin:{configurable:!0,get:function(){return this.Qn},set:function(a){var b=this.Qn;if(!b.A(a)){w(a,J,W,"gridOrigin");a.o()||v("Invalid Panel.gridOrigin: "+a);this.Qn=a.J();var c=this.diagram;null!==
c&&this===c.grid&&zj(c);this.S();this.g("gridOrigin",b,a)}}},graduatedMin:{configurable:!0,get:function(){return this.Mn},set:function(a){B(a,W,"graduatedMin");var b=this.Mn;b!==a&&(this.Mn=a,this.v(),this.g("graduatedMin",b,a),jl(this)&&(a=this.part,null!==a&&kl(this,a,"graduatedRange")))}},graduatedMax:{configurable:!0,get:function(){return this.Ln},set:function(a){B(a,W,"graduatedMax");var b=this.Ln;b!==a&&(this.Ln=a,this.v(),this.g("graduatedMax",b,a),jl(this)&&(a=
this.part,null!==a&&kl(this,a,"graduatedRange")))}},graduatedRange:{configurable:!0,get:function(){return this.graduatedMax-this.graduatedMin}},graduatedTickUnit:{configurable:!0,get:function(){return this.On},set:function(a){B(a,W,"graduatedTickUnit");var b=this.On;b!==a&&0<a&&(this.On=a,this.v(),this.g("graduatedTickUnit",b,a))}},graduatedTickBase:{configurable:!0,get:function(){return this.Nn},set:function(a){B(a,W,"graduatedTickBase");var b=this.Nn;b!==
a&&(this.Nn=a,this.v(),this.g("graduatedTickBase",b,a))}},zh:{configurable:!0,get:function(){return 0!==(this.I&8388608)},set:function(a){0!==(this.I&8388608)!==a&&(this.I^=8388608)}},rowCount:{configurable:!0,get:function(){return void 0===this.tb?0:this.tb.length}},columnCount:{configurable:!0,get:function(){return void 0===this.ob?0:this.ob.length}},rowSizing:{configurable:!0,get:function(){return void 0===this.Kj?bn:this.Kj},set:function(a){if(void 0!==
this.Kj){var b=this.Kj;b!==a&&(E&&a!==bn&&a!==Mm&&v("Panel.rowSizing must be RowColumnDefinition.ProportionalExtra or RowColumnDefinition.None, not: "+a),this.Kj=a,this.v(),this.g("rowSizing",b,a))}}},columnSizing:{configurable:!0,get:function(){return void 0===this.gj?bn:this.gj},set:function(a){if(void 0!==this.gj){var b=this.gj;b!==a&&(E&&a!==bn&&a!==Mm&&v("Panel.columnSizing must be RowColumnDefinition.ProportionalExtra or RowColumnDefinition.None, not: "+a),this.gj=a,this.v(),this.g("columnSizing",
b,a))}}},topIndex:{configurable:!0,get:function(){return void 0===this.Ai?0:this.Ai},set:function(a){if(void 0!==this.Ai){var b=this.Ai;b!==a&&((!isFinite(a)||0>a)&&v("Panel.topIndex must be greater than zero and a real number, not: "+a),this.Ai=a,this.v(),this.g("topIndex",b,a))}}},leftIndex:{configurable:!0,get:function(){return void 0===this.ji?0:this.ji},set:function(a){if(void 0!==this.ji){var b=this.ji;b!==a&&((!isFinite(a)||0>a)&&v("Panel.leftIndex must be greater than zero and a real number, not: "+
a),this.ji=a,this.v(),this.g("leftIndex",b,a))}}},data:{configurable:!0,get:function(){return this.kb},set:function(a){var b=this.kb;if(b!==a){var c=this instanceof T&&!(this instanceof Cf);c&&z(a,"object",W,"data");mh(this);this.kb=a;var d=this.diagram;null!==d&&(c?(c=d.partManager,this instanceof S?(null!==b&&c.Hg.remove(b),null!==a&&c.Hg.add(a,this)):this instanceof T&&(null!==b&&c.Oe.remove(b),null!==a&&c.Oe.add(a,this))):(c=this.panel,null!==c&&null!==c.Gd&&(null!==b&&c.Gd.remove(b),
null!==a&&c.Gd.add(a,this))));this.g("data",b,a);null!==d&&d.undoManager.isUndoingRedoing||null!==a&&this.Fa()}}},itemIndex:{configurable:!0,get:function(){return this.co},set:function(a){var b=this.co;b!==a&&(this.co=a,this.g("itemIndex",b,a))}},itemArray:{configurable:!0,get:function(){return this.hi},set:function(a){var b=this.hi;if(b!==a||null!==a&&rn(this,a)){E&&null!==a&&!Ka(a)&&v("Panel.itemArray must be an Array-like object or null, not: "+a);var c=this.diagram;
b!==a&&(null!==c&&null!==b&&Vj(c.partManager,this,c),this.hi=a,null!==c&&null!==a&&Sj(c.partManager,this));this.g("itemArray",b,a);null!==c&&c.undoManager.isUndoingRedoing||this.st()}}},itemTemplate:{configurable:!0,get:function(){return null===this.le?null:this.le.K("")},set:function(a){if(null===this.le){if(null===a)return;this.le=new Ub}var b=this.le.K("");b!==a&&(w(a,W,W,"itemTemplate"),(a instanceof T||a.isPanelMain)&&v("Panel.itemTemplate must not be a Part or be Panel.isPanelMain: "+
a),this.le.add("",a),this.g("itemTemplate",b,a),a=this.diagram,null!==a&&a.undoManager.isUndoingRedoing||this.st())}},itemTemplateMap:{configurable:!0,get:function(){return this.le},set:function(a){var b=this.le;if(b!==a){w(a,Ub,W,"itemTemplateMap");for(var c=a.iterator;c.next();){var d=c.value;E&&(d instanceof T||d.isPanelMain)&&v("Template in Panel.itemTemplateMap must not be a Part or be Panel.isPanelMain: "+d)}this.le=a;this.g("itemTemplateMap",b,a);a=this.diagram;null!==a&&a.undoManager.isUndoingRedoing||
this.st()}}},itemCategoryProperty:{configurable:!0,get:function(){return this.ll},set:function(a){var b=this.ll;b!==a&&("string"!==typeof a&&"function"!==typeof a&&Ba(a,"string or function",W,"itemCategoryProperty"),this.ll=a,this.g("itemCategoryProperty",b,a))}},isAtomic:{configurable:!0,get:function(){return 0!==(this.I&1048576)},set:function(a){var b=0!==(this.I&1048576);b!==a&&(z(a,"boolean",W,"isAtomic"),this.I^=1048576,this.g("isAtomic",b,a))}},isClipping:{configurable:!0,
enumerable:!0,get:function(){return 0!==(this.I&2097152)},set:function(a){var b=0!==(this.I&2097152);b!==a&&(z(a,"boolean",W,"isClipping"),this.I^=2097152,this.v(),this.g("isClipping",b,a))}},isOpposite:{configurable:!0,get:function(){return 0!==(this.I&33554432)},set:function(a){var b=0!==(this.I&33554432);b!==a&&(z(a,"boolean",W,"isOpposite"),this.I^=33554432,this.v(),this.g("isOpposite",b,a))}},isEnabled:{configurable:!0,get:function(){return 0!==(this.I&4194304)},set:function(a){var b=
0!==(this.I&4194304);if(b!==a){z(a,"boolean",W,"isEnabled");var c=null===this.panel||this.panel.ug();this.I^=4194304;this.g("isEnabled",b,a);b=this.diagram;null!==b&&b.undoManager.isUndoingRedoing||c&&nn(this,this,a)}}},alignmentFocusName:{configurable:!0,get:function(){return this.Bg},set:function(a){var b=this.Bg;b!==a&&(E&&z(a,"string",W,"alignmentFocusName"),this.Bg=a,this.v(),this.g("alignmentFocusName",b,a))}}});
na.Object.defineProperties(W,{Position:{configurable:!0,get:function(){return Rl.K("Position")}},Horizontal:{configurable:!0,get:function(){return Rl.K("Horizontal")}},Vertical:{configurable:!0,get:function(){return Rl.K("Vertical")}},Spot:{configurable:!0,get:function(){return Rl.K("Spot")}},Auto:{configurable:!0,get:function(){return Rl.K("Auto")}},Table:{configurable:!0,get:function(){return Rl.K("Table")}},Viewbox:{configurable:!0,
enumerable:!0,get:function(){return Rl.K("Viewbox")}},TableRow:{configurable:!0,get:function(){return Rl.K("TableRow")}},TableColumn:{configurable:!0,get:function(){return Rl.K("TableColumn")}},Link:{configurable:!0,get:function(){return Rl.K("Link")}},Grid:{configurable:!0,get:function(){return Rl.K("Grid")}},Graduated:{configurable:!0,get:function(){return Rl.K("Graduated")}}});W.prototype.findItemPanelForData=W.prototype.mx;
W.prototype.rebuildItemElements=W.prototype.st;W.prototype.updateTargetBindings=W.prototype.Fa;W.prototype.copyTemplate=W.prototype.Cy;W.prototype.graduatedValueForPoint=W.prototype.sz;W.prototype.graduatedPointForValue=W.prototype.rz;W.prototype.findColumnForLocalX=W.prototype.Sy;W.prototype.findRowForLocalY=W.prototype.$y;W.prototype.removeColumnDefinition=W.prototype.Fv;W.prototype.removeRowDefinition=W.prototype.Hv;W.prototype.removeAt=W.prototype.nb;W.prototype.remove=W.prototype.remove;
W.prototype.insertAt=W.prototype.Lb;W.prototype.elt=W.prototype.O;W.prototype.add=W.prototype.add;W.prototype.findObject=W.prototype.bb;W.prototype.findInVisualTree=W.prototype.cm;W.prototype.walkVisualTreeFrom=W.prototype.xk;W.prototype.findMainElement=W.prototype.Bb;var qn=!1,un=!1,vn=null,Rl=new Ub;W.className="Panel";W.definePanelLayout=yn;yn("Position",new Cm);yn("Vertical",new Fm);yn("Auto",new Hm);yn("Link",new Rm);yn("Grid",new Qm);
function ek(){qb(this);this.cg=null;this.Lr=!0;this.Ua=0;this.Sc=NaN;this.$g=0;this.Zg=Infinity;this.xb=Qd;this.ua=this.ma=0;this.eb=null;this.wp=zn;this.ye=$k;this.rp=this.gg=null;this.sp=NaN;this.jb=this.Mj=null;this.mn=!1}
ek.prototype.copy=function(){var a=new ek;a.Lr=this.Lr;a.Ua=this.Ua;a.Sc=this.Sc;a.$g=this.$g;a.Zg=this.Zg;a.xb=this.xb;a.ma=this.ma;a.ua=this.ua;a.ye=this.ye;a.wp=this.wp;null===this.gg?a.gg=null:a.gg=this.gg.J();a.rp=this.rp;a.sp=this.sp;a.Mj=null;null!==this.Mj&&(a.separatorDashArray=Ma(this.separatorDashArray));a.jb=this.jb;a.mn=this.mn;a.eb=this.eb;return a};t=ek.prototype;
t.$l=function(a){w(a,ek,ek,"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.gg=null===a.separatorPadding?null:a.separatorPadding.J();this.separatorStroke=a.separatorStroke;this.separatorStrokeWidth=a.separatorStrokeWidth;this.Mj=null;a.separatorDashArray&&(this.Mj=Ma(a.separatorDashArray));this.background=a.background;this.coversSeparators=a.coversSeparators;this.eb=
a.eb};t.hb=function(a){a.classType===ek?this.sizing=a:Fa(this,a)};t.toString=function(){return"RowColumnDefinition "+(this.isRow?"(Row ":"(Column ")+this.index+") #"+Jb(this)};t.Xi=function(a){this.cg=a};
t.Tu=function(){var a=0,b=0,c=this.cg,d=this.isRow;if(null!==c&&c.type===W.Table)for(var e=d?c.tb.length:c.ob.length,f=0;f<e;f++){var g=d?c.tb[f]:c.ob[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.gg;if(null===b)if(null!==c)b=
c.defaultSeparatorPadding;else return a;return a+(this.isRow?b.top:b.left)};
t.vc=function(){var a=0,b=this.cg,c=0,d=this.isRow;if(null!==b&&b.type===W.Table)for(var e=d?b.tb.length:b.ob.length,f=0;f<e;f++){var g=d?b.tb[f]:b.ob[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.gg;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.zb=function(a,b,c){var d=this.cg;if(null!==d&&(d.cb(of,a,this,b,c,void 0,void 0),null!==this.eb&&(b=d.diagram,null!==b&&!b.skipsModelSourceBindings&&(d=d.Li(),null!==d&&(b=d.data,null!==b)))))for(c=this.eb.iterator;c.next();)c.value.Eq(this,b,a,d)};function Lm(a){if(a.sizing===zn){var b=a.cg;return a.isRow?b.rowSizing:b.columnSizing}return a.sizing}
t.bind=function(a){a.Sd=this;var b=this.panel;if(null!==b){var c=b.Li();null!==c&&Nl(c)&&v("Cannot add a Binding to a RowColumnDefinition that is already frozen: "+a+" on "+b)}null===this.eb&&(this.eb=new F);this.eb.add(a)};
na.Object.defineProperties(ek.prototype,{panel:{configurable:!0,get:function(){return this.cg}},isRow:{configurable:!0,get:function(){return this.Lr},set:function(a){this.Lr=a}},index:{configurable:!0,get:function(){return this.Ua},set:function(a){this.Ua=a}},height:{configurable:!0,get:function(){return this.Sc},set:function(a){var b=this.Sc;b!==a&&(E&&z(a,"number",ek,"height"),0>a&&Ca(a,">= 0",ek,"height"),this.Sc=a,this.actual=this.ma,null!==
this.panel&&this.panel.v(),this.zb("height",b,a))}},width:{configurable:!0,get:function(){return this.Sc},set:function(a){var b=this.Sc;b!==a&&(E&&z(a,"number",ek,"width"),0>a&&Ca(a,">= 0",ek,"width"),this.Sc=a,this.actual=this.ma,null!==this.panel&&this.panel.v(),this.zb("width",b,a))}},minimum:{configurable:!0,get:function(){return this.$g},set:function(a){var b=this.$g;b!==a&&(E&&z(a,"number",ek,"minimum"),(0>a||!isFinite(a))&&Ca(a,">= 0",ek,"minimum"),this.$g=a,this.actual=
this.ma,null!==this.panel&&this.panel.v(),this.zb("minimum",b,a))}},maximum:{configurable:!0,get:function(){return this.Zg},set:function(a){var b=this.Zg;b!==a&&(E&&z(a,"number",ek,"maximum"),0>a&&Ca(a,">= 0",ek,"maximum"),this.Zg=a,this.actual=this.ma,null!==this.panel&&this.panel.v(),this.zb("maximum",b,a))}},alignment:{configurable:!0,get:function(){return this.xb},set:function(a){var b=this.xb;b.A(a)||(E&&w(a,M,ek,"alignment"),this.xb=a.J(),null!==this.panel&&this.panel.v(),
this.zb("alignment",b,a))}},stretch:{configurable:!0,get:function(){return this.ye},set:function(a){var b=this.ye;b!==a&&(E&&tb(a,N,ek,"stretch"),this.ye=a,null!==this.panel&&this.panel.v(),this.zb("stretch",b,a))}},separatorPadding:{configurable:!0,get:function(){return this.gg},set:function(a){"number"===typeof a?a=new Hc(a):null!==a&&E&&w(a,Hc,ek,"separatorPadding");var b=this.gg;null!==a&&null!==b&&b.A(a)||(null!==a&&(a=a.J()),this.gg=a,null!==this.panel&&this.panel.v(),
this.zb("separatorPadding",b,a))}},separatorStroke:{configurable:!0,get:function(){return this.rp},set:function(a){var b=this.rp;b!==a&&(null!==a&&Vl(a,"RowColumnDefinition.separatorStroke"),a instanceof yl&&a.freeze(),this.rp=a,null!==this.panel&&this.panel.v(),this.zb("separatorStroke",b,a))}},separatorStrokeWidth:{configurable:!0,get:function(){return this.sp},set:function(a){var b=this.sp;b!==a&&(this.sp=a,null!==this.panel&&this.panel.v(),this.zb("separatorStrokeWidth",
b,a))}},separatorDashArray:{configurable:!0,get:function(){return this.Mj},set:function(a){var b=this.Mj;if(b!==a){null===a||Array.isArray(a)||Ba(a,"Array",ek,"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.Mj=a;null!==this.panel&&this.panel.S();this.zb("separatorDashArray",
b,a)}}},background:{configurable:!0,get:function(){return this.jb},set:function(a){var b=this.jb;b!==a&&(null!==a&&Vl(a,"RowColumnDefinition.background"),a instanceof yl&&a.freeze(),this.jb=a,null!==this.panel&&this.panel.S(),this.zb("background",b,a))}},coversSeparators:{configurable:!0,get:function(){return this.mn},set:function(a){var b=this.mn;b!==a&&(z(a,"boolean",ek,"coversSeparators"),this.mn=a,null!==this.panel&&this.panel.S(),this.zb("coversSeparators",b,a))}},
sizing:{configurable:!0,get:function(){return this.wp},set:function(a){var b=this.wp;b!==a&&(E&&tb(a,ek,ek,"sizing"),this.wp=a,null!==this.panel&&this.panel.v(),this.zb("sizing",b,a))}},actual:{configurable:!0,get:function(){return this.ma},set:function(a){this.ma=isNaN(this.Sc)?Math.max(Math.min(this.Zg,a),this.$g):Math.max(Math.min(this.Zg,this.Sc),this.$g)}},total:{configurable:!0,get:function(){return this.ma+this.vc()},set:function(a){this.ma=isNaN(this.Sc)?
Math.max(Math.min(this.Zg,a),this.$g):Math.max(Math.min(this.Zg,this.Sc),this.$g);this.ma=Math.max(0,this.ma-this.vc())}},position:{configurable:!0,get:function(){return this.ua},set:function(a){this.ua=a}}});ek.prototype.bind=ek.prototype.bind;ek.prototype.computeEffectiveSpacing=ek.prototype.vc;ek.prototype.computeEffectiveSpacingTop=ek.prototype.Tu;var zn=new D(ek,"Default",0),Mm=new D(ek,"None",1),bn=new D(ek,"ProportionalExtra",2);ek.className="RowColumnDefinition";ek.Default=zn;
ek.None=Mm;ek.ProportionalExtra=bn;function Hg(){N.call(this);this.Rd=this.sa=null;this.Zk="None";this.Kn=$k;this.Ic=this.$k="black";this.jh=1;this.Nl="butt";this.Ol="miter";this.Oj=10;this.hh=null;this.ih=0;this.ff=this.ef=Qd;this.So=this.Ro=NaN;this.Vn=!1;this.Uo=null;this.cl=this.Ul="None";this.Ed=1;this.Dd=0;this.Bd=1;this.Cd=null}ma(Hg,N);
Hg.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.sa=this.sa;a.Zk=this.Zk;a.Kn=this.Kn;a.Rd=this.Rd;a.$k=this.$k;a.Ic=this.Ic;a.jh=this.jh;a.Nl=this.Nl;a.Ol=this.Ol;a.Oj=this.Oj;null!==this.hh&&(a.hh=Ma(this.hh));a.ih=this.ih;a.ef=this.ef.J();a.ff=this.ff.J();a.Ro=this.Ro;a.So=this.So;a.Vn=this.Vn;a.Uo=this.Uo;a.Ul=this.Ul;a.cl=this.cl;a.Ed=this.Ed;a.Dd=this.Dd;a.Bd=this.Bd;a.Cd=this.Cd};t=Hg.prototype;
t.hb=function(a){a===nh||a===ph||a===cl||a===$k?this.geometryStretch=a:N.prototype.hb.call(this,a)};t.toString=function(){return"Shape("+("None"!==this.figure?this.figure:"None"!==this.toArrow?this.toArrow:this.fromArrow)+")#"+Jb(this)};
function An(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,x=Qa(),y=2;y<e;y+=2)l=c[y],m=c[y+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),x.push([n,q,p,r]),u+=r,h=l,k=m;h=c[0];k=c[1];n=d.measuredBounds.width;d instanceof Hg&&(n-=d.strokeWidth);1>n&&(n=1);e=c=n;l=g/2;m=0===l?!1:!0;y=0;r=x[y];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){Ta(x);return}e>r?(A=e-r,e=r):A=0;var C=Math.sqrt(e*e/(1+p*p));0>n&&(C=-C);h+=C;k+=p*C;a.translate(h,k);a.rotate(q);a.translate(-(g/2),-(f/2));0===A&&d.Hi(a,b);a.translate(g/2,f/2);a.rotate(-q);a.translate(-h,-k);u-=e;r-=e;if(0!==A){y++;if(y===x.length){Ta(x);return}r=x[y];n=r[0];q=r[1];p=r[2];r=r[3];e=A}}Ta(x)}}
t.Hi=function(a,b){var c=this.Ic,d=this.$k;if(null!==c||null!==d){var e=this.actualBounds,f=this.naturalBounds;null!==d&&yi(this,a,d,!0,!1,f,e);null!==c&&yi(this,a,c,!1,!1,f,e);e=this.part;f=this.jh;0===f&&null!==e&&(f=e instanceof Cf&&e.type===W.Link&&"Selection"===e.category&&e.adornedObject instanceof Hg&&e.adornedPart.Bb()===e.adornedObject?e.adornedObject.strokeWidth:0);a.lineWidth=f;a.lineJoin=this.Ol;a.lineCap=this.Nl;a.miterLimit=this.Oj;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.Us(k,this.ih));var l=this.sa;if(null!==l){if(l.type===pe)a.beginPath(),a.moveTo(l.startX,l.startY),a.lineTo(l.endX,l.endY),null!==d&&a.Vd(d),0!==f&&null!==c&&a.aj();else if(l.type===xe){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);a.beginPath();a.rect(k,l,m,n);null!==d&&a.Vd(d);if(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);if(0!==f){if(0===m||0===n)a.beginPath(),a.rect(k,l,Math.max(m,.1),Math.max(n,.1));a.aj()}h&&g&&(a.shadowOffsetX=c,a.shadowOffsetY=d,a.shadowBlur=p)}}else if(l.type===ye)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.Ag*l,k-m,n+l,k-K.Ag*m,n+l,k),a.bezierCurveTo(n+l,k+K.Ag*m,n+K.Ag*l,k+m,n,k+m),a.bezierCurveTo(n-K.Ag*l,k+m,n-l,k+K.Ag*
m,n-l,k),a.bezierCurveTo(n-l,k-K.Ag*m,n-K.Ag*l,k-m,n,k-m),a.closePath(),null!==d&&a.Vd(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.aj(),a.shadowOffsetX=f,a.shadowOffsetY=g,a.shadowBlur=c):a.aj());else if(l.type===ne)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 x=p[u];switch(x.type){case Ne:a.moveTo(x.endX,x.endY);
break;case ve:a.lineTo(x.endX,x.endY);break;case Oe:a.bezierCurveTo(x.point1X,x.point1Y,x.point2X,x.point2Y,x.endX,x.endY);break;case Pe:a.quadraticCurveTo(x.point1X,x.point1Y,x.endX,x.endY);break;case Qe:if(x.radiusX===x.radiusY){var y=Math.PI/180;a.arc(x.point1X,x.point1Y,x.radiusX,x.startAngle*y,(x.startAngle+x.sweepAngle)*y,0>x.sweepAngle,null!==r?r.endX:n.startX,null!==r?r.endY:n.startY)}else if(r=Se(x,n),y=r.length,0===y)a.lineTo(x.centerX,x.centerY);else for(var A=0;A<y;A++){var C=r[A];0===
A&&a.lineTo(C[0],C[1]);a.bezierCurveTo(C[2],C[3],C[4],C[5],C[6],C[7])}break;case Re:A=y=0;if(null!==r&&r.type===Qe){r=Se(r,n);C=r.length;if(0===C){a.lineTo(x.centerX,x.centerY);break}r=r[C-1]||null;null!==r&&(y=r[6],A=r[7])}else y=null!==r?r.endX:n.startX,A=null!==r?r.endY:n.startY;r=Te(x,n,y,A);y=r.length;if(0===y){a.lineTo(x.centerX,x.centerY);break}for(A=0;A<y;A++)C=r[A],a.bezierCurveTo(C[2],C[3],C[4],C[5],C[6],C[7]);break;default:v("Segment not of valid type: "+x.type)}x.isClosed&&a.closePath();
r=x}g?(u=q=p=0,n.isShadowed?(!0===n.isFilled&&null!==d?(a.Vd(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.aj(),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.Vd(d),0!==f&&null!==c&&a.aj(),h&&(a.shadowOffsetX=p,a.shadowOffsetY=q,a.shadowBlur=u))):(!0===n.isFilled&&
null!==d&&a.Vd(d),0!==f&&null!==c&&a.aj())}e&&a.Ss();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=Qa();if(g.type===pe)f.push(g.startX),f.push(g.startY),f.push(g.endX),f.push(g.endY),An(a,b,f,e);else if(g.type===ne)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 Ne:An(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 ve:f.push(q.endX);f.push(q.endY);d=q.endX;h=q.endY;break;case Oe: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 Pe:K.tq(d,h,q.point1X,q.point1Y,q.endX,q.endY,.5,f);d=q.endX;h=q.endY;break;case Qe:u=Se(q,c);x=u.length;if(0===x){f.push(q.centerX);f.push(q.centerY);d=q.centerX;h=q.centerY;break}for(r=0;r<x;r++)y=u[r],K.Ce(d,h,y[2],y[3],
y[4],y[5],y[6],y[7],.5,f),d=y[6],h=y[7];break;case Re:u=Te(q,c,d,h);x=u.length;if(0===x){f.push(q.centerX);f.push(q.centerY);d=q.centerX;h=q.centerY;break}for(r=0;r<x;r++)y=u[r],K.Ce(d,h,y[2],y[3],y[4],y[5],y[6],y[7],.5,f),d=y[6],h=y[7];break;default:v("Segment not of valid type: "+q.type)}q.isClosed&&(f.push(k),f.push(l),An(a,b,f,e))}An(a,b,f,e)}else if(g.type===xe)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),An(a,b,f,e);else if(g.type===ye){h=new Xe;h.startX=g.endX;h.startY=(g.startY+g.endY)/2;d=new Ye(Qe);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=Se(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];An(a,b,f,e)}Ta(f);a.restore();a.Uc(!1)}}}};
t.oa=function(a,b){void 0===b&&(b=new J);if(a instanceof M){a.Nb()&&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.td.va(b);return b};
t.eq=function(a){void 0===a&&(a=new L);var b=this.naturalBounds,c=this.td;b=L.allocAt(b.x,b.y,b.width,b.height);var d=this.strokeWidth;b.Xc(d/2,d/2);d=J.allocAt(b.x,b.y).transform(c);a.h(d.x,d.y,0,0);d.h(b.right,b.y).transform(c);Mc(a,d.x,d.y,0,0);d.h(b.right,b.bottom).transform(c);Mc(a,d.x,d.y,0,0);d.h(b.x,b.bottom).transform(c);Mc(a,d.x,d.y,0,0);L.free(b);J.free(d);return a};
t.xh=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!==pe||b||(e+=2);var f=L.alloc();f.assign(d);f.Xc(e+2,e+2);if(!f.ea(a))return L.free(f),!1;d=e+1E-4;if(c.type===pe){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.Vb(c.startX,c.startY,c.endX,c.endY,e,a.x,a.y)}if(c.type===
xe){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.Xc(-d,-d);if(f.ea(a))return L.free(f),!1;f.Xc(d,d)}null!==this.stroke&&f.Xc(e,e);a=f.ea(a);L.free(f);return a}if(c.type===ye){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===ne)return L.free(f),null===this.fill?Ve(c,a.x,a.y,e):c.ea(a,e,1<this.strokeWidth,b);v("Unknown Geometry type: "+c.type);return!1};
t.mm=function(a,b,c,d){var e=this.desiredSize,f=this.jh;a=Math.max(a,0);b=Math.max(b,0);if(null!==this.Rd)var g=this.geometry.bounds;else{var h=this.figure,k=Bn[h];if(void 0===k){var l=K.be[h];"string"===typeof l&&(l=K.be[l]);"function"===typeof l?(k=l(null,100,100),Bn[h]=k):v("Unsupported Figure: "+h)}g=k.bounds}h=g.width;k=g.height;l=g.width;var m=g.height;switch(pl(this,!0)){case nh:d=c=0;break;case oe:l=Math.max(a-f,0);m=Math.max(b-f,0);break;case al:l=Math.max(a-f,0);d=0;break;case bl: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=oh(this);switch(c){case nh:break;case oe:h=l;k=m;break;case ph: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.Rd?(h=Math.max(h,.01),k=Math.max(k,
.01),g=null!==this.Rd?this.Rd:this.sa,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.sa=c):null!==this.sa&&K.da(this.sa.jl,a-f)&&K.da(this.sa.hl,b-f)||(this.sa=Hg.makeGeometry(this,h,k));g=this.sa.bounds;Infinity===a||Infinity===b?ml(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):ml(this,-(f/2),-(f/2),l+f,m+f)};
function oh(a){var b=a.geometryStretch;return null!==a.Rd?b===$k?oe:b:b===$k?Bn[a.figure].defaultStretch:b}t.vh=function(a,b,c,d){rl(this,a,b,c,d)};t.Wc=function(a,b,c){return this.gk(a.x,a.y,b.x,b.y,c)};
t.gk=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.jh/2;l=this.sa;null===l&&(this.measure(Infinity,Infinity),l=this.sa);p=l.bounds;m=!1;if(l.type===pe)if(1.5>=this.strokeWidth)m=K.Ie(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=Qa();a=new J;K.Ie(l.startX+d,l.startY+m,l.endX+d,l.endY+m,f,g,h,k,a)&&b.push(a);a=new J;K.Ie(l.startX-d,l.startY-m,l.endX-d,l.endY-m,f,g,h,k,a)&&b.push(a);a=new J;K.Ie(l.startX+d,l.startY+m,l.startX-d,l.startY-m,f,g,h,k,a)&&b.push(a);a=new J;K.Ie(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 Ta(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);Ta(b)}else if(l.type===xe)m=K.Wc(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===ye){b=L.allocAt(p.x,p.y,p.width,p.height).Xc(n,n);a:if(0===b.width)m=K.Ie(b.x,b.y,b.x,b.y+b.height,f,g,h,k,e);else if(0===b.height)m=K.Ie(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===ne){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 x=0;x<l.figures.count;x++){var y=l.figures.j[x],A=y.segments;q=y.startX;r=y.startY;for(var C=q,G=r,I=0;I<A.count;I++){var O=
A.j[I],R=O.type;var U=O.endX;var ea=O.endY;var Z=!1;switch(R){case Ne:C=U;G=ea;break;case ve:Z=Gn(q,r,U,ea,f,g,h,k,p);break;case Oe:Z=K.Tp(q,r,O.point1X,O.point1Y,O.point2X,O.point2Y,U,ea,f,g,h,k,.6,p);break;case Pe:Z=K.Tp(q,r,(q+2*O.point1X)/3,(r+2*O.point1Y)/3,(2*O.point1X+U)/3,(2*O.point1X+U)/3,U,ea,f,g,h,k,.6,p);break;case Qe:case Re:R=O.type===Qe?Se(O,y):Te(O,y,q,r);var qa=R.length;if(0===qa){Z=Gn(q,r,O.centerX,O.centerY,f,g,h,k,p);break}ea=null;for(U=0;U<qa;U++){ea=R[U];if(0===U&&Gn(q,r,ea[0],
ea[1],f,g,h,k,p)){var xa=Hn(f,g,p,u,e);xa<u&&(u=xa,m=!0)}K.Tp(ea[0],ea[1],ea[2],ea[3],ea[4],ea[5],ea[6],ea[7],f,g,h,k,.6,p)&&(xa=Hn(f,g,p,u,e),xa<u&&(u=xa,m=!0))}U=ea[6];ea=ea[7];break;default:v("Unknown Segment type: "+R)}q=U;r=ea;Z&&(Z=Hn(f,g,p,u,e),Z<u&&(u=Z,m=!0));O.isClosed&&(U=C,ea=G,Gn(q,r,U,ea,f,g,h,k,p)&&(O=Hn(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 Hn(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 Gn(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.da(k.y,a))&&(k.y<b||K.da(k.y,b))&&(l=!0)):(b=a<c?a:c,a=a<c?c:a,(k.x>b||K.da(k.x,b))&&(k.x<a||K.da(k.x,a))&&(l=!0));return l}
t.wh=function(a,b){if(void 0===b)return a.pf(this.actualBounds);var c=this.sa;null===c&&(this.measure(Infinity,Infinity),c=this.sa);c=c.bounds;var d=this.strokeWidth/2,e=!1,f=J.alloc();f.h(c.x-d,c.y-d);a.ea(b.va(f))&&(f.h(c.x-d,c.bottom+d),a.ea(b.va(f))&&(f.h(c.right+d,c.bottom+d),a.ea(b.va(f))&&(f.h(c.right+d,c.y-d),a.ea(b.va(f))&&(e=!0))));J.free(f);return e};
t.Kc=function(a,b){if(this.wh(a,b)||void 0===b&&(b=this.transform,a.pf(this.actualBounds)))return!0;var c=$b.alloc();c.set(b);c.gt();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.xh(g,!0))return J.free(g),!0;g.h(e,f);c.va(g);if(this.xh(g,!0))return J.free(g),!0;g.h(d,a);c.va(g);if(this.xh(g,!0))return J.free(g),!0;g.h(e,a);c.va(g);if(this.xh(g,!0))return J.free(g),!0;var h=J.alloc(),k=J.alloc();c.set(b);c.uv(this.transform);c.gt();h.x=e;h.y=f;h.transform(c);g.x=
d;g.y=f;g.transform(c);b=!1;In(this,g,h,k)?b=!0:(g.x=e,g.y=a,g.transform(c),In(this,g,h,k)?b=!0:(h.x=d,h.y=a,h.transform(c),In(this,g,h,k)?b=!0:(g.x=d,g.y=f,g.transform(c),In(this,g,h,k)&&(b=!0))));J.free(g);$b.free(c);J.free(h);J.free(k);return b};function In(a,b,c,d){if(!a.Wc(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.ed(a[d],a[d+1])>e)return!0;return!1}if(c&&null!==this.fill&&this.xh(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.sa;if(null===b&&(this.measure(Infinity,Infinity),b=this.sa,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(dc(a.x,a.y,h,k)<=e&&dc(a.x,a.y,l,k)<=e&&dc(a.x,a.y,h,g)<=e&&dc(a.x,a.y,l,g)<=e)return!0}h=b.startX;k=b.startY;l=
b.endX;g=b.endY;if(b.type===pe){if(c=cc(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===xe)return b=!1,c&&(b=cc(a.x,a.y,h,k,h,g)<=e||cc(a.x,a.y,h,k,l,k)<=e||cc(a.x,a.y,l,k,l,g)<=e||cc(a.x,a.y,h,g,l,g)<=e),b;if(b.type===ye){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 cc(a.x,a.y,h,k,l,g)<=e?!0:!1;if(c){if(a=K.Iy(m,n,b,f),a*a<=e)return!0}else return dc(b,f,-m,0)>=e||dc(b,f,0,-n)>=e||
dc(b,f,0,n)>=e||dc(b,f,m,0)>=e?!1:!0}else if(b.type===ne){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&&cc(a.x,a.y,f,h,f,l)>e&&cc(a.x,a.y,f,h,k,h)>e&&cc(a.x,a.y,k,l,f,l)>e&&cc(a.x,a.y,k,l,k,h)>e)return!1;f=Math.sqrt(e);if(c){if(null===this.fill?Ve(b,a.x,a.y,f):b.ea(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.ed(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 Ne:case ve:g=n.endX;
m=n.endY;if(a.ed(g,m)>e)return!1;break;case Oe:var p=Qa();K.Ce(g,m,n.point1X,n.point1Y,n.point2X,n.point2Y,n.endX,n.endY,.8,p);g=d(p,a);Ta(p);if(g)return!1;g=n.endX;m=n.endY;if(a.ed(g,m)>e)return!1;break;case Pe:p=Qa();K.tq(g,m,n.point1X,n.point1Y,n.endX,n.endY,.8,p);g=d(p,a);Ta(p);if(g)return!1;g=n.endX;m=n.endY;if(a.ed(g,m)>e)return!1;break;case Qe:case Re:p=n.type===Qe?Se(n,f):Te(n,f,g,m);var q=p.length;if(0===q){g=n.centerX;m=n.centerY;if(a.ed(g,m)>e)return!1;break}n=null;for(var r=Qa(),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 Ta(r),!1;Ta(r);null!==n&&(g=n[6],m=n[7]);break;default:v("Unknown Segment type: "+n.type)}}return!0}}}return!1};t.cc=function(){this.sa=null};function Jn(a){var b=a.diagram;null!==b&&b.undoManager.isUndoingRedoing||(a.segmentOrientation=Kn,"None"!==a.Ul?(a.segmentIndex=-1,a.alignmentFocus=Xd):"None"!==a.cl&&(a.segmentIndex=0,a.alignmentFocus=new M(1-Xd.x,Xd.y)))}
Hg.makeGeometry=function(a,b,c){if("None"!==a.toArrow)var d=Ln[a.toArrow];else"None"!==a.fromArrow?d=Ln[a.fromArrow]:(d=K.be[a.figure],"string"===typeof d&&(d=K.be[d]),void 0===d&&v("Unknown Shape.figure: "+a.figure),d=d(a,b,c),d.jl=b,d.hl=c);if(null===d){var e=K.be.Rectangle;"function"===typeof e&&(d=e(a,b,c))}E&&(d.bounds.width>b+1E-5||d.bounds.height>c+1E-5)&&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 Mn(a){var b=Ln[a];if(void 0===b){var c=a.toLowerCase();if("none"===c)return"None";b=Ln[c];if(void 0===b){var d=null,e;for(e in K.Gm)if(e.toLowerCase()===c){d=e;break}if(null!==d)return a=ze(K.Gm[d],!1),Ln[d]=a,c!==d&&(Ln[c]=d),d}}return"string"===typeof b?b:b instanceof me?a:null}
na.Object.defineProperties(Hg.prototype,{geometry:{configurable:!0,get:function(){return null!==this.sa?this.sa:this.Rd},set:function(a){var b=this.sa;if(b!==a){null!==a?(E&&w(a,me,Hg,"geometry"),this.Rd=this.sa=a.freeze()):this.Rd=this.sa=null;var c=this.part;null!==c&&(c.Yg=NaN);this.v();this.g("geometry",b,a);jl(this)&&(a=this.part,null!==a&&kl(this,a,"geometryString"))}}},geometryString:{configurable:!0,get:function(){return null===this.geometry?"":this.geometry.toString()},
set:function(a){a=ze(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.Vn},set:function(a){E&&z(a,"boolean",Hg,"isGeometryPositioned");var b=this.Vn;b!==a&&(this.Vn=a,this.v(),this.g("isGeometryPositioned",b,a))}},fill:{configurable:!0,get:function(){return this.$k},set:function(a){var b=this.$k;b!==a&&(null!==a&&Vl(a,"Shape.fill"),a instanceof yl&&a.freeze(),this.$k=
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&&(null!==a&&Vl(a,"Shape.stroke"),a instanceof yl&&a.freeze(),this.Ic=a,this.S(),this.g("stroke",b,a))}},strokeWidth:{configurable:!0,get:function(){return this.jh},set:function(a){var b=this.jh;if(b!==a)if(E&&B(a,Hg,"strokeWidth"),0<=a){this.jh=a;this.v();var c=this.part;null!==c&&(c.Yg=NaN);this.g("strokeWidth",b,a)}else Ca(a,"value >= 0",Hg,"strokeWidth:value")}},
strokeCap:{configurable:!0,get:function(){return this.Nl},set:function(a){var b=this.Nl;b!==a&&("string"!==typeof a||"butt"!==a&&"round"!==a&&"square"!==a?Ca(a,'"butt", "round", or "square"',Hg,"strokeCap"):(this.Nl=a,this.S(),this.g("strokeCap",b,a)))}},strokeJoin:{configurable:!0,get:function(){return this.Ol},set:function(a){var b=this.Ol;b!==a&&("string"!==typeof a||"miter"!==a&&"bevel"!==a&&"round"!==a?Ca(a,'"miter", "bevel", or "round"',Hg,"strokeJoin"):(this.Ol=
a,this.S(),this.g("strokeJoin",b,a)))}},strokeMiterLimit:{configurable:!0,get:function(){return this.Oj},set:function(a){var b=this.Oj;if(b!==a)if(E&&B(a,Hg,"strokeMiterLimit"),1<=a){this.Oj=a;this.S();var c=this.part;null!==c&&(c.Yg=NaN);this.g("strokeMiterLimit",b,a)}else E&&Ca(a,"value >= 1",Hg,"strokeWidth:value")}},strokeDashArray:{configurable:!0,get:function(){return this.hh},set:function(a){var b=this.hh;if(b!==a){null===a||Array.isArray(a)||Ba(a,"Array",Hg,"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.hh=a;this.S();this.g("strokeDashArray",b,a)}}},strokeDashOffset:{configurable:!0,get:function(){return this.ih},set:function(a){var b=this.ih;b!==a&&(E&&B(a,Hg,"strokeDashOffset"),0<=a&&(this.ih=a,this.S(),this.g("strokeDashOffset",b,a)))}},figure:{configurable:!0,
enumerable:!0,get:function(){return this.Zk},set:function(a){var b=this.Zk;if(b!==a){E&&z(a,"string",Hg,"figure");var c=K.be[a];"function"===typeof c?c=a:(c=K.be[a.toLowerCase()])||v("Unknown Shape.figure: "+a);b!==c&&(a=this.part,null!==a&&(a.Yg=NaN),this.Zk=c,this.Rd=null,this.cc(),this.v(),this.g("figure",b,c))}}},toArrow:{configurable:!0,get:function(){return this.Ul},set:function(a){var b=this.Ul;!0===a?a="Standard":!1===a&&(a="");if(b!==a){E&&z(a,"string",Hg,"toArrow");var c=Mn(a);
null===c?v("Unknown Shape.toArrow: "+a):b!==c&&(this.Ul=c,this.Rd=null,this.cc(),this.v(),Jn(this),this.g("toArrow",b,c))}}},fromArrow:{configurable:!0,get:function(){return this.cl},set:function(a){var b=this.cl;!0===a?a="Standard":!1===a&&(a="");if(b!==a){E&&z(a,"string",Hg,"fromArrow");var c=Mn(a);null===c?v("Unknown Shape.fromArrow: "+a):b!==c&&(this.cl=c,this.Rd=null,this.cc(),this.v(),Jn(this),this.g("fromArrow",b,c))}}},spot1:{configurable:!0,get:function(){return this.ef},
set:function(a){w(a,M,Hg,"spot1");var b=this.ef;b.A(a)||(this.ef=a=a.J(),this.v(),this.g("spot1",b,a))}},spot2:{configurable:!0,get:function(){return this.ff},set:function(a){w(a,M,Hg,"spot2");var b=this.ff;b.A(a)||(this.ff=a=a.J(),this.v(),this.g("spot2",b,a))}},parameter1:{configurable:!0,get:function(){return this.Ro},set:function(a){var b=this.Ro;b!==a&&(this.Ro=a,this.cc(),this.v(),this.g("parameter1",b,a))}},parameter2:{configurable:!0,get:function(){return this.So},
set:function(a){var b=this.So;b!==a&&(this.So=a,this.cc(),this.v(),this.g("parameter2",b,a))}},naturalBounds:{configurable:!0,get:function(){if(null!==this.sa)return this.rc.assign(this.sa.bounds),this.rc;var a=this.desiredSize;return new L(0,0,a.width,a.height)}},pathPattern:{configurable:!0,get:function(){return this.Uo},set:function(a){var b=this.Uo;b!==a&&(E&&null!==a&&w(a,N,Hg,"pathPattern"),this.Uo=a,this.S(),this.g("pathPattern",b,a))}},geometryStretch:{configurable:!0,
enumerable:!0,get:function(){return this.Kn},set:function(a){var b=this.Kn;b!==a&&(tb(a,N,Hg,"geometryStretch"),this.Kn=a,this.g("geometryStretch",b,a))}},interval:{configurable:!0,get:function(){return this.Ed},set:function(a){var b=this.Ed;E&&B(a,Hg,"interval");a=Math.floor(a);if(b!==a&&0<=a){this.Ed=a;var c=this.diagram;null!==c&&this.panel===c.grid&&zj(c);this.v();c=this.panel;null!==c&&(c.Qg=null);this.g("interval",b,a)}}},graduatedStart:{configurable:!0,get:function(){return this.Dd},
set:function(a){var b=this.Dd;E&&B(a,Hg,"graduatedStart");b!==a&&(0>a?a=0:1<a&&(a=1),this.Dd=a,this.v(),this.g("graduatedStart",b,a))}},graduatedEnd:{configurable:!0,get:function(){return this.Bd},set:function(a){var b=this.Bd;E&&B(a,Hg,"graduatedEnd");b!==a&&(0>a?a=0:1<a&&(a=1),this.Bd=a,this.v(),this.g("graduatedEnd",b,a))}},graduatedSkip:{configurable:!0,get:function(){return this.Cd},set:function(a){var b=this.Cd;b!==a&&(null!==a&&z(a,"function",Hg,"graduatedSkip"),
this.Cd=a,this.v(),this.g("graduatedSkip",b,a))}}});Hg.prototype.intersectsRect=Hg.prototype.Kc;Hg.prototype.containedInRect=Hg.prototype.wh;Hg.prototype.getNearestIntersectionPoint=Hg.prototype.Wc;Hg.prototype.getDocumentBounds=Hg.prototype.eq;Hg.prototype.getDocumentPoint=Hg.prototype.oa;var Ln=new xb,Bn=new xb;Hg.className="Shape";Hg.getFigureGenerators=function(){var a=new Ub,b;for(b in K.be)b!==b.toLowerCase()&&a.add(b,K.be[b]);a.freeze();return a};
Hg.defineFigureGenerator=function(a,b){z(a,"string",Hg,"defineFigureGenerator:name");"string"===typeof b?!E||""!==b&&K.be[b]||v("Shape.defineFigureGenerator synonym must not be empty or None or not a defined figure name: "+b):z(b,"function",Hg,"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.be;d[a]=b;d[c]=a};
Hg.getArrowheadGeometries=function(){var a=new Ub;for(d in K.Gm)if(void 0===Ln[d]){var b=ze(K.Gm[d],!1);Ln[d]=b;b=d.toLowerCase();b!==d&&(Ln[b]=d)}for(var c in Ln)if(c!==c.toLowerCase()){var d=Ln[c];d instanceof me&&a.add(c,d)}a.freeze();return a};
Hg.defineArrowheadGeometry=function(a,b){z(a,"string",Hg,"defineArrowheadGeometry:name");"string"===typeof b?(z(b,"string",Hg,"defineArrowheadGeometry:pathstr"),b=ze(b,!1)):w(b,me,Hg,"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=Ln;d[a]=b;d[c]=a};
function Kh(){N.call(this);Nn||(On(),Nn=!0);this.Rb="";this.Ic="black";this.he="13px sans-serif";this.yi="start";this.Ad=nh;this.Di=Td;this.sj=!0;this.fi=this.gi=!1;this.ag=Pn;this.mg=Qn;this.Wr=this.pc=0;this.mu=this.nu=null;this.pd=new $m;this.En=!1;this.Ec=this.an=this.Ep=this.zi=this.Fp=null;this.df=this.cf=0;this.pe=Infinity;this.ol=0;this.Ed=1;this.Dd=0;this.Bd=1;this.Cd=this.nj=null}ma(Kh,N);
Kh.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.Rb=this.Rb;a.Ic=this.Ic;a.he=this.he;a.yi=this.yi;a.Ad=this.Ad;a.Di=this.Di;a.sj=this.sj;a.gi=this.gi;a.fi=this.fi;a.ag=this.ag;a.mg=this.mg;a.pc=this.pc;a.Wr=this.Wr;a.nu=this.nu;a.mu=this.mu;a.pd.$l(this.pd);a.En=this.En;a.Fp=this.Fp;a.zi=this.zi;a.Ep=this.Ep;a.an=this.an;a.Ec=this.Ec;a.cf=this.cf;a.df=this.df;a.pe=this.pe;a.ol=this.ol;a.Ed=this.Ed;a.Dd=this.Dd;a.Bd=this.Bd;a.nj=this.nj;a.Cd=this.Cd};
function Zm(a,b){a.I=b.I|6144;a.mb=b.opacity;a.jb=b.background;a.fc=b.areaBackground;a.Qc=b.desiredSize.J();a.Sf=b.minSize.J();a.Rf=b.maxSize.J();a.Qf=b.Qf.copy();a.Da=b.scale;a.Bc=b.angle;a.ye=b.stretch;a.Xg=b.margin.J();a.xb=b.alignment.J();a.Ck=b.alignmentFocus.J();a.Dl=b.segmentFraction;a.El=b.segmentOffset.J();a.Fl=b.segmentOrientation;null!==b.md&&(a.md=b.md.copy());a.Hl=b.shadowVisible;b instanceof Kh&&(a.Rb=b.Rb,a.Ic=b.Ic,a.he=b.he,a.yi=b.yi,a.Ad=b.Ad,a.Di=b.Di,a.sj=b.sj,a.gi=b.gi,a.fi=b.fi,
a.ag=b.ag,a.mg=b.mg,a.pd.Kf=null,a.cf=b.cf,a.df=b.df,a.pe=b.pe,a.ol=b.ol,a.Ed=b.Ed,a.Dd=b.Dd,a.Bd=b.Bd,a.nj=b.nj,a.Cd=b.Cd)}t=Kh.prototype;t.hb=function(a){a.classType===Kh?this.wrap=a:N.prototype.hb.call(this,a)};t.toString=function(){return 22<this.Rb.length?'TextBlock("'+this.Rb.substring(0,20)+'"...)':'TextBlock("'+this.Rb+'")'};t.v=function(){N.prototype.v.call(this);this.mu=this.nu=null};
function Rn(a){Nn||(On(),Nn=!0);if(null===Sn)return!0;var b=Sn.font;if(a===b||"10px sans-serif"===a)return!0;Sn.font="10px sans-serif";Sn.font=a;var c=Sn.font;if("10px sans-serif"!==c)return Sn.font=b,!0;Sn.font="19px serif";var d=Sn.font;Sn.font=a;c=Sn.font;Sn.font=b;return c!==d}
t.Hi=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=Tn(this),h=a.textAlign=this.yi,k=b.Xn;"start"===h?h=k?"right":"left":"end"===h&&(h=k?"left":"right");k=this.gi;var l=this.fi;yi(this,a,this.Ic,!0,!1,c,d);(k||l)&&yi(this,a,this.Ic,!1,!1,c,d);d=0;c=!1;var m=J.allocAt(0,0);this.td.va(m);var n=J.allocAt(0,g);this.td.va(n);var p=m.Ee(n);J.free(m);J.free(n);m=b.scale;8>p*m*m&&(c=!0);b.$c!==a&&(c=!1);!1===b.Ge("textGreeking")&&
(c=!1);b=this.cf;p=this.df;switch(this.flip){case el:a.translate(e,0);a.scale(-1,1);break;case dl:a.translate(0,f);a.scale(1,-1);break;case fl:a.translate(e,f),a.scale(-1,-1)}m=this.pc;n=(b+g+p)*m;f>n&&(d=this.Di,d=d.y*f-d.y*n+d.offsetY);n=this.pd;for(var q=0;q<m;q++){var r=n.Yc[q];r>e&&(r=e);d+=b;var u=n.Cc[q],x=a,y=d,A=h,C=0;if(c)"left"===A?C=0:"right"===A?C=e-r:"center"===A&&(C=(e-r)/2),x.fillRect(0+C,y+.25*g,r,1);else{"left"===A?C=0:"right"===A?C=e:"center"===A&&(C=e/2);var G=null!==Un?Un(this,
g):.75*g;x.fillText(u,0+C,y+G);u=g/20|0;0===u&&(u=1);"right"===A?C-=r:"center"===A&&(C-=r/2);k&&(A=null!==Vn?Vn(this,g):.8*g,x.beginPath(),x.lineWidth=u,x.moveTo(0+C,y+A),x.lineTo(0+C+r,y+A),x.stroke());l&&(x.beginPath(),x.lineWidth=u,y=y+g-g/2.2|0,0!==u%2&&(y+=.5),x.moveTo(0+C,y),x.lineTo(0+C+r,y),x.stroke())}d+=g+p}switch(this.flip){case el:a.scale(-1,1);a.translate(-e,0);break;case dl:a.scale(1,-1);a.translate(0,-f);break;case fl:a.scale(-1,-1),a.translate(-e,-f)}}};
t.mm=function(a,b,c,d){this.ol=a;var e=this.he;null!==Sn&&Wn!==e&&(Wn=Sn.font=e);e=this.pd;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,Xn(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=Xn(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=Yn(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.Cc.length&&this.ag===Zn&&(b=this.he,b=this.ag===Zn?$n(b):0,k=this.cf+this.df,k=Math.max(0,Tn(this)+k),h=Math.min(this.maxLines-1,Math.max(Math.floor(h/k+.01)-1,0)),!(h+1>=e.Cc.length))){k=e.Cc[h];for(b=Math.max(1,a-b);Xn(k)>b&&1<k.length;)k=k.substr(0,k.length-1);k+=ao;b=Xn(k);e.Cc[h]=k;e.Cc=e.Cc.slice(0,h+1);e.Yc[h]=b;e.Yc=
e.Yc.slice(0,h+1);e.lg=e.Cc.length;e.Gc=Math.max(e.Gc,b);this.pc=e.lg}if(this.wrap===bo||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);Cc(this.rc,g,f);ml(this,0,0,g,f)};t.vh=function(a,b,c,d){rl(this,a,b,c,d)};
function co(a,b,c,d,e){b=b.trim();var f=0;var g=a.he;var h=a.cf+a.df;h=Math.max(0,Tn(a)+h);var k=a.ag===Zn?$n(g):0;if(a.pc>=a.pe)null!==e&&e.h(0,h);else{var l=b;if(a.mg===eo)if(c.lg=1,g=Xn(b),0===k||g<=d)c.Gc=Math.max(c.Gc,g),c.Yc.push(c.Gc),c.Cc.push(b),null!==e&&e.h(g,h);else{f=fo(a,l);l=l.substr(f.length);b=fo(a,l);for(g=Xn(f+b);0<b.length&&g<=d;)f+=b,l=l.substr(b.length),b=fo(a,l),g=Xn((f+b).trim());f+=b.trim();for(d=Math.max(1,d-k);Xn(f)>d&&1<f.length;)f=f.substr(0,f.length-1);f+=ao;b=Xn(f);
c.Yc.push(b);c.Gc=b;c.Cc.push(f);null!==e&&e.h(b,h)}else{k=0;0===l.length&&(k=1,c.Yc.push(0),c.Cc.push(l));for(;0<l.length;){var m=fo(a,l);for(l=l.substr(m.length);Xn(m)>d;){var n=1;g=Xn(m.substr(0,n));for(b=0;g<=d;)n++,b=g,g=Xn(m.substr(0,n));1===n?(c.Yc[a.pc+k]=g,f=Math.max(f,g)):(c.Yc[a.pc+k]=b,f=Math.max(f,b));n--;1>n&&(n=1);c.Cc[a.pc+k]=m.substr(0,n);k++;m=m.substr(n);if(a.pc+k>a.pe)break}b=fo(a,l);for(g=Xn(m+b);0<b.length&&g<=d;)m+=b,l=l.substr(b.length),b=fo(a,l),g=Xn((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.Yc.push(g),f=Math.max(f,g)):(b=Xn(m),c.Yc.push(b),f=Math.max(f,b)),c.Cc.push(m),k++,a.pc+k>a.pe))break}c.lg=Math.min(a.pe,k);c.Gc=Math.max(c.Gc,f);null!==e&&e.h(c.Gc,h*c.lg)}}}function fo(a,b){if(a.mg===go)return b.substr(0,1);a=b.length;for(var c=0,d=ho;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 Xn(a){return null===Sn?8*a.length:Sn.measureText(a).width}function Tn(a){if(null!==a.pd.Kf)return a.pd.Kf;var b=a.he;if(null===Sn){var c=16;return a.pd.Kf=c}void 0!==io[b]&&5E3>jo?c=io[b]:(c=1.3*Sn.measureText("M").width,io[b]=c,jo++);return a.pd.Kf=c}function $n(a){if(null===Sn)return 6;if(void 0!==ko[a]&&5E3>lo)var b=ko[a];else b=Sn.measureText(ao).width,ko[a]=b,lo++;return b}
function Yn(a,b,c){var d=a.Rb.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),e=a.cf+a.df;e=Math.max(0,Tn(a)+e);if(0===d.length)return c.Gc=0,a.pc=1,e;if(!a.isMultiline){var f=d.indexOf("\n",0);0<=f&&(d=d.substr(0,f))}f=0;for(var g=a.pc=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.mg!==eo){c.lg=0;var l=Zb.alloc();co(a,g,c,b,l);f+=l.height;Zb.free(l);a.pc+=c.lg}else co(a,g,c,b,null),f+=e,a.pc++;a.pc===a.pe&&(k=!0)}g=h+1}return a.Wr=f}
function On(){ho=/[ \u200b\u00ad]/;io=new xb;ko=new xb;Sn=Ih?(new Ik(null)).context:null}
na.Object.defineProperties(Kh.prototype,{font:{configurable:!0,get:function(){return this.he},set:function(a){var b=this.he;b!==a&&(E&&(z(a,"string",Kh,"font"),Rn(a)||v('Not a valid font: "'+a+'"')),this.he=a,this.pd.Kf=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.yi},
set:function(a){var b=this.yi;b!==a&&(E&&z(a,"string",Kh,"textAlign"),"start"===a||"end"===a||"left"===a||"right"===a||"center"===a?(this.yi=a,this.S(),this.g("textAlign",b,a)):E&&Ca(a,'"start", "end", "left", "right", or "center"',Kh,"textAlign"))}},flip:{configurable:!0,get:function(){return this.Ad},set:function(a){var b=this.Ad;b!==a&&(tb(a,N,Kh,"flip"),this.Ad=a,this.S(),this.g("flip",b,a))}},verticalAlignment:{configurable:!0,get:function(){return this.Di},set:function(a){var b=
this.Di;b.A(a)||(E&&(w(a,M,Kh,"verticalAlignment"),a.Nb()&&v("TextBlock.verticalAlignment for "+this+" must be a real Spot, not:"+a)),this.Di=a=a.J(),Hl(this),this.g("verticalAlignment",b,a))}},naturalBounds:{configurable:!0,get:function(){if(!this.rc.o()){var a=Zb.alloc();co(this,this.Rb,this.pd,999999,a);var b=a.width;Zb.free(a);a=Yn(this,b,this.pd);var c=this.desiredSize;isNaN(c.width)||(b=c.width);isNaN(c.height)||(a=c.height);Cc(this.rc,b,a)}return this.rc}},isMultiline:{configurable:!0,
enumerable:!0,get:function(){return this.sj},set:function(a){var b=this.sj;b!==a&&(E&&z(a,"boolean",Kh,"isMultiline"),this.sj=a,this.v(),this.g("isMultiline",b,a))}},isUnderline:{configurable:!0,get:function(){return this.gi},set:function(a){var b=this.gi;b!==a&&(E&&z(a,"boolean",Kh,"isUnderline"),this.gi=a,this.S(),this.g("isUnderline",b,a))}},isStrikethrough:{configurable:!0,get:function(){return this.fi},set:function(a){var b=this.fi;b!==a&&(E&&z(a,"boolean",Kh,"isStrikethrough"),
this.fi=a,this.S(),this.g("isStrikethrough",b,a))}},wrap:{configurable:!0,get:function(){return this.mg},set:function(a){var b=this.mg;b!==a&&(E&&tb(a,Kh,Kh,"wrap"),this.mg=a,this.v(),this.g("wrap",b,a))}},overflow:{configurable:!0,get:function(){return this.ag},set:function(a){var b=this.ag;b!==a&&(E&&tb(a,Kh,Kh,"overflow"),this.ag=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&&(null!==a&&Vl(a,"TextBlock.stroke"),a instanceof yl&&a.freeze(),this.Ic=a,this.S(),this.g("stroke",b,a))}},lineCount:{configurable:!0,get:function(){return this.pc}},editable:{configurable:!0,get:function(){return this.En},set:function(a){var b=this.En;b!==a&&(E&&z(a,"boolean",Kh,"editable"),this.En=a,this.g("editable",b,a))}},textEditor:{configurable:!0,get:function(){return this.Fp},set:function(a){var b=this.Fp;b!==a&&(!E||a instanceof Hf||v("TextBlock.textEditor must be an HTMLInfo."),
this.Fp=a,this.g("textEditor",b,a))}},errorFunction:{configurable:!0,get:function(){return this.Ec},set:function(a){var b=this.Ec;b!==a&&(null!==a&&z(a,"function",Kh,"errorFunction"),this.Ec=a,this.g("errorFunction",b,a))}},interval:{configurable:!0,get:function(){return this.Ed},set:function(a){var b=this.Ed;E&&B(a,Kh,"interval");a=Math.floor(a);if(b!==a&&0<=a){this.Ed=a;this.v();var c=this.panel;null!==c&&(c.Qg=null);this.g("interval",b,a)}}},graduatedStart:{configurable:!0,
enumerable:!0,get:function(){return this.Dd},set:function(a){var b=this.Dd;E&&B(a,Kh,"graduatedStart");b!==a&&(0>a?a=0:1<a&&(a=1),this.Dd=a,this.v(),this.g("graduatedStart",b,a))}},graduatedEnd:{configurable:!0,get:function(){return this.Bd},set:function(a){var b=this.Bd;E&&B(a,Kh,"graduatedEnd");b!==a&&(0>a?a=0:1<a&&(a=1),this.Bd=a,this.v(),this.g("graduatedEnd",b,a))}},graduatedFunction:{configurable:!0,get:function(){return this.nj},set:function(a){var b=this.nj;b!==
a&&(null!==a&&z(a,"function",Kh,"graduatedFunction"),this.nj=a,this.v(),this.g("graduatedFunction",b,a))}},graduatedSkip:{configurable:!0,get:function(){return this.Cd},set:function(a){var b=this.Cd;b!==a&&(null!==a&&z(a,"function",Kh,"graduatedSkip"),this.Cd=a,this.v(),this.g("graduatedSkip",b,a))}},textValidation:{configurable:!0,get:function(){return this.zi},set:function(a){var b=this.zi;b!==a&&(null!==a&&z(a,"function",Kh,"textValidation"),this.zi=a,this.g("textValidation",
b,a))}},textEdited:{configurable:!0,get:function(){return this.Ep},set:function(a){var b=this.Ep;b!==a&&(null!==a&&z(a,"function",Kh,"textEdited"),this.Ep=a,this.g("textEdited",b,a))}},spacingAbove:{configurable:!0,get:function(){return this.cf},set:function(a){var b=this.cf;b!==a&&(E&&z(a,"number",Kh,"spacingAbove"),this.cf=a,this.g("spacingAbove",b,a))}},spacingBelow:{configurable:!0,get:function(){return this.df},set:function(a){var b=this.df;b!==a&&(E&&
z(a,"number",Kh,"spacingBelow"),this.df=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",Kh,"maxLines"),a=Math.floor(a),0>=a&&Ca(a,"> 0",Kh,"maxLines"),this.pe=a,this.g("maxLines",b,a),this.v())}},metrics:{configurable:!0,get:function(){return this.pd}},choices:{configurable:!0,get:function(){return this.an},set:function(a){var b=this.an;b!==a&&(E&&null!==a&&!Array.isArray(a)&&
Ba(a,"Array",Kh,"choices:value"),this.an=a,this.g("choices",b,a))}}});var Un=null,Vn=null,eo=new D(Kh,"None",0),bo=new D(Kh,"WrapFit",1),Qn=new D(Kh,"WrapDesiredSize",2),go=new D(Kh,"WrapBreakAll",3),Pn=new D(Kh,"OverflowClip",0),Zn=new D(Kh,"OverflowEllipsis",1),ho=null,io=null,jo=0,ko=null,lo=0,ao="...",Wn="",Sn=null,Nn=!1;Kh.className="TextBlock";Kh.getEllipsis=function(){return ao};Kh.setEllipsis=function(a){ao=a;ko=new xb;lo=0};Kh.getBaseline=function(){return Un};
Kh.setBaseline=function(a){Un=a;a=ab();for(var b=a.length,c=0;c<b;c++)a[c].vf()};Kh.getUnderline=function(){return Vn};Kh.setUnderline=function(a){Vn=a;a=ab();for(var b=a.length,c=0;c<b;c++)a[c].vf()};Kh.isValidFont=Rn;Kh.None=eo;Kh.WrapFit=bo;Kh.WrapDesiredSize=Qn;Kh.WrapBreakAll=go;Kh.OverflowClip=Pn;Kh.OverflowEllipsis=Zn;function $m(){this.Gc=this.lg=0;this.Yc=[];this.Cc=[];this.Kf=null}$m.prototype.reset=function(){this.Gc=this.lg=0;this.Kf=null;this.Yc=[];this.Cc=[]};
$m.prototype.$l=function(a){this.lg=a.lg;this.Kf=a.Kf;this.Gc=a.Gc;this.Yc=Ma(a.Yc);this.Cc=Ma(a.Cc)};na.Object.defineProperties($m.prototype,{arrSize:{configurable:!0,get:function(){return this.Yc}},arrText:{configurable:!0,get:function(){return this.Cc}},maxLineWidth:{configurable:!0,get:function(){return this.Gc}},fontHeight:{configurable:!0,get:function(){return this.Kf}}});$m.className="TextBlockMetrics";
function kk(){N.call(this);this.Mg=null;this.yp="";this.gh=Uc;this.fl=oe;this.gf=this.Ec=null;this.el=qd;this.Ad=nh;this.Ql=null;this.gu=!1;this.al=!0;this.sl=!1;this.Il=null}ma(kk,N);kk.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.element=this.Mg;a.yp=this.yp;a.gh=this.gh.J();a.fl=this.fl;a.Ad=this.Ad;a.Ec=this.Ec;a.gf=this.gf;a.el=this.el.J();a.al=this.al;a.Il=this.Il};t=kk.prototype;
t.hb=function(a){a===nh||a===ph||a===cl?this.imageStretch=a:N.prototype.hb.call(this,a)};t.toString=function(){return"Picture("+this.source+")#"+Jb(this)};function pk(a){void 0===a&&(a="");z(a,"string",kk,"clearCache:url");""!==a?mo[a]&&(delete mo[a],no--):(mo=new xb,no=0)}function oo(a,b){a.Jr=!0;a.dl=!1;for(var c,d=ab(),e=d.length,f=0;f<e;f++){var g=d[f],h=g.Hj.K(a.src);if(null!==h)for(var k=h.length,l=0;l<k;l++)c=h[l],g.ru.add(c),g.ec(),void 0===a.xu&&(a.xu=b,null!==c.gf&&c.gf(c,b))}}
function po(a,b){a.dl=b;for(var c,d=ab(),e=d.length,f=0;f<e;f++)if(c=d[f].Hj.K(a.src),null!==c){for(var g=c.length,h=Qa(),k=0;k<g;k++)h.push(c[k]);for(k=0;k<g;k++)c=h[k],null!==c.Ec&&c.Ec(c,b);Ta(h)}}t.Uz=function(){if(""!==this.source){pk(this.source);var a=this.source;this.source="";this.source=a}};t.vf=function(){this.S()};
t.Hi=function(a,b){var c=this.Mg;if(null!==c){var d=c.src;null!==d&&""!==d||v('Element has no source ("src") attribute: '+c);if(!(c.dl instanceof Event)){d=this.naturalBounds;var e=0,f=0,g=this.gu,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.gh.x,f=this.gh.y,h=this.gh.width,g=this.gh.height);var m=h,n=g,p=this.fl,
q=this.el;switch(p){case nh: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 oe:m=d.width;n=d.height;break;case ph:case cl:p===ph?(p=Math.min(d.height/n,d.width/m),m*=p,n*=p):p===cl&&(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=c.__goCache;p=null;var x=qo;if(c.Jr&&void 0!==u&&r>x*x)for(null===u.Fi&&(ro(u,4,k,l,c),ro(u,16,k,l,c)),k=u.Fi,l=k.length,p=k[0],x=0;x<l;x++)if(k[x].ratio*k[x].ratio<r)p=k[x];else break;if(!b.Bn){if(null===this.Ql)if(null===this.Mg)this.Ql=!1;else{k=(new Ik(null)).context;k.drawImage(this.Mg,0,0);try{k.getImageData(0,0,1,1).data[3]&&(this.Ql=!1),this.Ql=!1}catch(y){this.Ql=!0}}if(this.Ql)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 el:a.translate(Math.min(d.width,m),0);a.scale(-1,1);break;case dl:a.translate(0,Math.min(d.height,n));a.scale(1,-1);break;case fl:a.translate(Math.min(d.width,m),Math.min(d.height,n)),a.scale(-1,-1)}if(b.Ge("pictureRatioOptimization")&&!b.rj&&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(y){E&&this.al&&Ha(y.toString()),this.al=!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(y){E&&this.al&&Ha(y.toString()),this.al=!1}switch(this.flip){case el:a.scale(-1,1);a.translate(-Math.min(d.width,m),0);break;case dl:a.scale(1,-1);a.translate(0,-Math.min(d.height,n));break;case fl:a.scale(-1,-1),a.translate(-Math.min(d.width,m),-Math.min(d.height,n))}}}}};
t.mm=function(a,b,c,d){var e=this.desiredSize,f=pl(this,!0),g=this.Mg,h=this.gu;if(h||!this.sl&&g&&g.complete)this.sl=!0;null===g&&(isFinite(e.width)||(a=0),isFinite(e.height)||(b=0));isFinite(e.width)||f===oe||f===al?(isFinite(a)||(a=this.sourceRect.o()?this.sourceRect.width:h?+g.width:g.naturalWidth),c=0):null!==g&&!1!==this.sl&&(a=this.sourceRect.o()?this.sourceRect.width:h?+g.width:g.naturalWidth);isFinite(e.height)||f===oe||f===bl?(isFinite(b)||(b=this.sourceRect.o()?this.sourceRect.height:h?
+g.height:g.naturalHeight),d=0):null!==g&&!1!==this.sl&&(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));Cc(this.rc,a,b);ml(this,0,0,a,b)};t.vh=function(a,b,c,d){rl(this,a,b,c,d)};
na.Object.defineProperties(kk.prototype,{element:{configurable:!0,get:function(){return this.Mg},set:function(a){var b=this.Mg;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.gu=a instanceof HTMLCanvasElement;this.Mg=a;if(null!==a)if(a instanceof HTMLCanvasElement||!0===a.complete)a.dl instanceof Event&&null!==this.Ec&&this.Ec(this,a.dl),
!0===a.Jr&&null!==this.gf&&this.gf(this,a.xu),a.Jr=!0,this.desiredSize.o()||(yj(this,!1),this.v());else{var c=this;a.Dw||(a.addEventListener("load",function(b){oo(a,b);c.desiredSize.o()||(yj(c,!1),c.v())}),a.addEventListener("error",function(b){po(a,b)}),a.Dw=!0)}this.g("element",b,a);this.S()}}},source:{configurable:!0,get:function(){return this.yp},set:function(a){var b=this.yp;if(b!==a){z(a,"string",kk,"source");this.yp=a;var c=mo,d=this.diagram,e=null;if(void 0!==c[a])e=c[a];else{30<
no&&(pk(),c=mo);e=ya("img");var f=this;e.addEventListener("load",function(a){oo(e,a);f.desiredSize.o()||(yj(f,!1),f.v())});e.addEventListener("error",function(a){po(e,a)});e.Dw=!0;var g=this.Il;null!==g&&(e.crossOrigin=g(this));e.src=a;c[a]=e;no++}null!==d&&lk(d,this);this.element=e;null!==d&&jk(d,this);void 0===e.__goCache&&(e.__goCache=new so);this.v();this.S();this.g("source",b,a)}}},sourceCrossOrigin:{configurable:!0,get:function(){return this.Il},set:function(a){if(this.Il!==a&&
(null!==a&&z(a,"function",kk,"sourceCrossOrigin"),this.Il=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.gh},set:function(a){var b=this.gh;b.A(a)||(w(a,L,kk,"sourceRect"),this.gh=a=a.J(),this.S(),this.g("sourceRect",b,a))}},imageStretch:{configurable:!0,get:function(){return this.fl},set:function(a){var b=
this.fl;b!==a&&(tb(a,N,kk,"imageStretch"),this.fl=a,this.S(),this.g("imageStretch",b,a))}},flip:{configurable:!0,get:function(){return this.Ad},set:function(a){var b=this.Ad;b!==a&&(tb(a,N,kk,"flip"),this.Ad=a,this.S(),this.g("flip",b,a))}},imageAlignment:{configurable:!0,get:function(){return this.el},set:function(a){w(a,M,kk,"imageAlignment");var b=this.el;b.A(a)||(this.el=a=a.J(),this.v(),this.g("imageAlignment",b,a))}},errorFunction:{configurable:!0,get:function(){return this.Ec},
set:function(a){var b=this.Ec;b!==a&&(null!==a&&z(a,"function",kk,"errorFunction"),this.Ec=a,this.g("errorFunction",b,a))}},successFunction:{configurable:!0,get:function(){return this.gf},set:function(a){var b=this.gf;b!==a&&(null!==a&&z(a,"function",kk,"successFunction"),this.gf=a,this.g("successFunction",b,a))}},naturalBounds:{configurable:!0,get:function(){return this.rc}}});kk.prototype.redraw=kk.prototype.vf;kk.prototype.reloadSource=kk.prototype.Uz;
var mo=null,no=0,qo=4;kk.className="Picture";mo=new xb;kk.clearCache=pk;function so(){this.Fi=null}function ro(a,b,c,d,e){null===a.Fi&&(a.Fi=[]);var f=new Ik(null),g=f.context,h=1/b;f.width=c/b;f.height=d/b;b=new to(f.Ha,b);c=1;0<a.Fi.length&&(c=a.Fi[a.Fi.length-1],e=c.source,c=c.ratio);g.setTransform(h*c,0,0,h*c,0,0);g.drawImage(e,0,0);a.Fi.push(b)}so.className="PictureCacheArray";function to(a,b){this.source=a;this.ratio=b}to.className="PictureCacheInstance";
function uo(){this.Zs=new me;this.gc=null}t=uo.prototype;t.reset=function(a){null!==a?(a.ja(),this.Zs=a,a.figures.clear()):this.Zs=new me;this.gc=null};function Be(a,b,c,d,e){a.gc=new Xe;a.gc.startX=b;a.gc.startY=c;a.gc.isFilled=d;a.Zs.figures.add(a.gc);void 0!==e&&(a.gc.isShadowed=e)}function Je(a){var b=a.gc.segments.length;0<b&&a.gc.segments.O(b-1).close()}t.Aq=function(a){this.gc.isShadowed=a};t.moveTo=function(a,b,c){void 0===c&&(c=!1);var d=new Ye(Ne);d.endX=a;d.endY=b;c&&d.close();this.gc.segments.add(d)};
t.lineTo=function(a,b,c){void 0===c&&(c=!1);var d=new Ye(ve);d.endX=a;d.endY=b;c&&d.close();this.gc.segments.add(d)};function Ce(a,b,c,d,e,f,g){var h;void 0===h&&(h=!1);var k=new Ye(Oe);k.point1X=b;k.point1Y=c;k.point2X=d;k.point2Y=e;k.endX=f;k.endY=g;h&&k.close();a.gc.segments.add(k)}function He(a,b,c,d,e){var f;void 0===f&&(f=!1);var g=new Ye(Pe);g.point1X=b;g.point1Y=c;g.endX=d;g.endY=e;f&&g.close();a.gc.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 Ye(Qe);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.gc.segments.add(h)};function Ie(a,b,c,d,e,f,g,h){var k;void 0===k&&(k=!1);b=new Ye(Re,g,h,b,c,d,e,f);k&&b.close();a.gc.segments.add(b)}function Ae(a){var b=Ke;if(null!==b)return Ke=null,b.reset(a),b;b=new uo;b.reset(a);return b}var Ke=null;uo.className="StreamGeometryContext";
function vo(a,b){var c=a.toLowerCase(),d=K.be;d[a]=b;d[c]=a}vo("Rectangle",function(a,b,c){a=new me(xe);a.startX=0;a.startY=0;a.endX=b;a.endY=c;return a});vo("Square",function(a,b,c){a=new me(xe);a.startX=0;a.startY=0;a.endX=b;a.endY=c;a.defaultStretch=ph;return a});
vo("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.Ag;b=(new me).add((new Xe(d,0,!0)).add(new Ye(ve,b-d,0)).add(new Ye(Oe,b,d,b-a,0,b,a)).add(new Ye(ve,b,c-d)).add(new Ye(Oe,b-d,c,b,c-a,b-a,c)).add(new Ye(ve,d,c)).add(new Ye(Oe,0,c-d,a,c,0,c-a)).add(new Ye(ve,0,d)).add((new Ye(Oe,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});vo("Border","RoundedRectangle");
vo("Ellipse",function(a,b,c){a=new me(ye);a.startX=0;a.startY=0;a.endX=b;a.endY=c;a.spot1=ee;a.spot2=fe;return a});vo("Circle",function(a,b,c){a=new me(ye);a.startX=0;a.startY=0;a.endX=b;a.endY=c;a.spot1=ee;a.spot2=fe;a.defaultStretch=ph;return a});vo("TriangleRight",function(a,b,c){return(new me).add((new Xe(0,0)).add(new Ye(ve,b,.5*c)).add((new Ye(ve,0,c)).close())).Dm(0,.25,.5,.75)});
vo("TriangleDown",function(a,b,c){return(new me).add((new Xe(0,0)).add(new Ye(ve,b,0)).add((new Ye(ve,.5*b,c)).close())).Dm(.25,0,.75,.5)});vo("TriangleLeft",function(a,b,c){return(new me).add((new Xe(b,c)).add(new Ye(ve,0,.5*c)).add((new Ye(ve,b,0)).close())).Dm(.5,.25,1,.75)});vo("TriangleUp",function(a,b,c){return(new me).add((new Xe(b,c)).add(new Ye(ve,0,c)).add((new Ye(ve,.5*b,0)).close())).Dm(.25,.5,.75,1)});vo("Triangle","TriangleUp");
vo("Diamond",function(a,b,c){return(new me).add((new Xe(.5*b,0)).add(new Ye(ve,0,.5*c)).add(new Ye(ve,.5*b,c)).add((new Ye(ve,b,.5*c)).close())).Dm(.25,.25,.75,.75)});vo("LineH",function(a,b,c){a=new me(pe);a.startX=0;a.startY=c/2;a.endX=b;a.endY=c/2;return a});vo("LineV",function(a,b,c){a=new me(pe);a.startX=b/2;a.startY=0;a.endX=b/2;a.endY=c;return a});vo("None","Rectangle");vo("BarH","Rectangle");vo("BarV","Rectangle");vo("MinusLine","LineH");
vo("PlusLine",function(a,b,c){return(new me).add((new Xe(0,c/2,!1)).add(new Ye(ve,b,c/2)).add(new Ye(Ne,b/2,0)).add(new Ye(ve,b/2,c)))});vo("XLine",function(a,b,c){return(new me).add((new Xe(0,c,!1)).add(new Ye(ve,b,0)).add(new Ye(Ne,0,0)).add(new Ye(ve,b,c)))});
K.Gm={"":"",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 T(a){W.call(this,a);this.F=2408959;this.Vg=this.Bf="";this.cp=this.$o=this.op=this.fo=null;this.qp="";this.zf=this.Rn=this.pp=this.eh=null;this.bp="";this.ap=xc;this.Rb=this.ep="";this.ii=this.dn=this.Uh=null;this.oe=(new J(NaN,NaN)).freeze();this.mo="";this.Ye=null;this.no=fd;this.fp=Qd;this.vo=hc;this.oo=ic;this.An=null;this.ho=127;this.wi=jc;this.Nj="gray";this.Qd=4;this.Gw=-1;this.Pp=NaN;this.Zx=new L;this.Aj=null;this.Yg=NaN}ma(T,W);
T.prototype.cloneProtected=function(a){W.prototype.cloneProtected.call(this,a);a.F=this.F&-4097|49152;a.Bf=this.Bf;a.Vg=this.Vg;a.fo=this.fo;a.op=this.op;a.$o=this.$o;a.cp=this.cp;a.qp=this.qp;a.pp=this.pp;a.Rn=this.Rn;a.zf=null;a.bp=this.bp;a.ap=this.ap.J();a.ep=this.ep;a.fp=this.fp.J();a.Rb=this.Rb;a.dn=this.dn;a.oe.assign(this.oe);a.mo=this.mo;a.no=this.no.J();a.vo=this.vo.J();a.oo=this.oo.J();a.An=this.An;a.ho=this.ho;a.wi=this.wi.J();a.Nj=this.Nj;a.Qd=this.Qd;a.Pp=this.Pp};
T.prototype.qf=function(a){W.prototype.qf.call(this,a);a.Ah();a.eh=null;a.Ye=null;a.Aj=null};T.prototype.toString=function(){var a=Va(this.constructor)+"#"+Jb(this);null!==this.data&&(a+="("+Wa(this.data)+")");return a};T.prototype.tk=function(a,b,c,d,e,f,g){var h=this.diagram;null!==h&&(a===qf&&"elements"===b?e instanceof W?Qj(e,function(a){Sj(h.partManager,a);Rj(h,a)}):jk(h,e):a===rf&&"elements"===b&&(e instanceof W?Qj(e,function(a){Vj(h.partManager,a,h)}):lk(h,e)),h.cb(a,b,c,d,e,f,g))};
T.prototype.Fa=function(a){W.prototype.Fa.call(this,a);if(null!==this.data){a=this.Z.j;for(var b=a.length,c=0;c<b;c++){var d=a[c];d instanceof W&&Qj(d,function(a){null!==a.data&&a.Fa()})}}};T.prototype.updateRelationshipsFromData=function(){null!==this.data&&this.diagram.partManager.updateRelationshipsFromData(this)};T.prototype.ek=function(a){E&&z(a,"string",T,"findAdornment:category");var b=this.zf;return null===b?null:b.K(a)};
T.prototype.rh=function(a,b){if(null!==b){E&&(z(a,"string",T,"addAdornment:category"),w(b,Cf,T,"addAdornment:ad"));var c=null,d=this.zf;null!==d&&(c=d.K(a));if(c!==b){if(null!==c){var e=c.diagram;null!==e&&e.remove(c)}null===d&&(this.zf=d=new Ub);b.Bf!==a&&(b.category=a);d.add(a,b);a=this.diagram;null!==a&&(a.add(b),a=b.adornedObject,null!==a&&(a=a.Li(),null!==a&&(b.data=a.data)))}}};
T.prototype.wf=function(a){E&&z(a,"string",T,"removeAdornment:category");var b=this.zf;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.zf=null)}};T.prototype.Xj=function(){var a=this.zf;if(null!==a){var b=Qa();for(a=a.iterator;a.next();)b.push(a.key);a=b.length;for(var c=0;c<a;c++)this.wf(b[c]);Ta(b)}};
T.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.uf()&&b.actualBounds.o())){c=this.ek("Selection");if(null===c){c=this.selectionAdornmentTemplate;null===c&&(c=this.Bh()?a.linkSelectionAdornmentTemplate:this instanceof xg?a.groupSelectionAdornmentTemplate:a.nodeSelectionAdornmentTemplate);
if(!(c instanceof Cf))break a;mh(c);c=c.copy();null!==c&&(this.Bh()&&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 Hg&&(e=b.strokeWidth);var f=Zb.alloc();f.h((b.naturalBounds.width+e)*d,(b.naturalBounds.height+e)*d);Zb.free(f)}c.type===W.Link?c.v():(b=J.alloc(),J.free(b));this.rh("Selection",c);break a}}this.wf("Selection")}wo(this,a);for(b=this.adornments;b.next();)b.value.Fa()}};
T.prototype.Mb=function(){var a=this.diagram;null!==a&&(dj(a),0!==(this.F&16384)!==!0&&(wi(this,!0),a.ec()))};function vi(a){0!==(a.F&16384)!==!1&&(a.updateAdornments(),wi(a,!1))}function wo(a,b){b.toolManager.mouseDownTools.each(function(b){b.isEnabled&&b.updateAdornments(a)});b.toolManager.updateAdornments(a)}function xo(a){if(!1===Fj(a)){yo(a,!0);a.kl();var b=a.diagram;null!==b&&(b.Fd.add(a),b.ec())}}
function zo(a){a.F|=2097152;if(!1!==Fj(a)){var b=a.position,c=a.location;c.o()&&b.o()||Ao(a,b,c);c=a.wb;var d=L.alloc().assign(c);c.ja();c.x=b.x;c.y=b.y;c.freeze();a.qt(d,c);L.free(d);yo(a,!1)}}T.prototype.move=function(a,b){!0===b?this.location=a:this.position=a};T.prototype.moveTo=function(a,b,c){a=J.allocAt(a,b);this.move(a,c);J.free(a)};
T.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&&li(a.animationManager,this))return!0;a=this.containingGroup;return null===a||a.isSubGraphExpanded&&a.isVisible()?!0:!1};t=T.prototype;t.Ob=function(a){var b=this.diagram;a?(this.C(4),this.Mb(),null!==b&&b.Fd.add(this)):(this.C(8),this.Xj());this.Ah();null!==b&&(b.Ya(),b.S())};
t.bb=function(a){if(this.name===a)return this;var b=this.Aj;null===b&&(this.Aj=b=new Ub);if(null!==b.K(a))return b.K(a);var c=W.prototype.bb.call(this,a);if(null!==c)return b.set(a,c),c;b.set(a,null);return null};t.rf=function(a,b,c){void 0===c&&(c=new J);b=b.Nb()?qd: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.Qf.va(c);c.offset(-this.qc.x,-this.qc.y);return c};
t.eq=function(a){void 0===a&&(a=new L);return a.assign(this.actualBounds)};t.bc=function(){!0===Dj(this)&&(this instanceof xg&&this.memberParts.each(function(a){a.bc()}),this.measure(Infinity,Infinity));this.arrange()};
function Oj(a,b){var c=a.Zx;isNaN(a.Yg)&&(a.Yg=ln(a));var d=a.Yg;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}
T.prototype.arrange=function(){if(!1===Ej(this))zo(this);else{var a=this.wb,b=L.alloc();b.assign(a);a.ja();var c=Dg(this);this.vh(0,0,this.qc.width,this.qc.height);var d=this.position;Ao(this,d,this.location);a.x=d.x;a.y=d.y;a.freeze();this.qt(b,a);ql(this,!1);b.A(a)?this.kd(c):!this.dc()||K.B(b.width,a.width)&&K.B(b.height,a.height)||0<=this.Gw&&this.C(16);L.free(b);yo(this,!1)}};t=T.prototype;
t.qt=function(a,b){var c=this.diagram;if(null!==c){var d=!1;if(!1===c.Sg&&a.o()){var e=L.alloc();e.assign(c.documentBounds);e.Vv(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.F&65536)!==!0&&a.A(b)||Tj(this,d,c);c.S();Fc(a,b)||(this instanceof V&&!c.undoManager.isUndoingRedoing&&this.gd(),this.Ah())}};
t.Rv=function(a,b){if(this.Bh()||!a.o())return!1;var c=this.diagram;if(null!==c&&(Bo(this,c,a,b),!0===c.undoManager.isUndoingRedoing))return!0;this.ua=a;this.F&=-2097153;c=this.oe;c.o()&&(this.oe=new J(c.x+(a.x-b.x),c.y+(a.y-b.y)),this.g("location",c,this.oe));!1===Fj(this)&&!1===Ej(this)&&(xo(this),zo(this));return!0};function Bo(a,b,c,d){null===b||a instanceof Cf||(b=b.animationManager,b.pi&&b.th(a,"position",d.copy(),c.copy(),!1))}
t.Bt=function(a,b){var c=this.oe,d=this.ua;Fj(this)||Ej(this)?c.h(NaN,NaN):c.h(c.x+a-d.x,c.y+b-d.y);d.h(a,b);xo(this)};t.Sv=function(){this.F&=-2097153;xo(this)};
function Ao(a,b,c){var d=J.alloc(),e=a.locationSpot,f=a.locationObject;e.Nb()&&v("determineOffset: Part's locationSpot must be real: "+e.toString());var g=f.naturalBounds,h=f instanceof Hg?f.strokeWidth:0;d.vk(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.Qf.va(d);d.offset(-a.qc.x,-a.qc.y);e=a.diagram;f=c.o();g=b.o();f&&g?0!==(a.F&2097152)?Co(a,b,c,e,d):Do(a,b,c,e,d):f?Co(a,b,c,e,d):g&&Do(a,b,c,e,d);a.F|=2097152;
J.free(d);a.kl()}function Co(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.pi||a instanceof Cf||c.th(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 Do(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 Tj(a,b,c){sl(a,!1);a instanceof V&&Dk(c,a);a.layer.isTemporary||b||c.Ya();b=a.wb;var d=c.viewportBounds;d.o()?Dg(a)?(Lc(b,d,10)||a.kd(!1),a.updateAdornments()):b.Kc(d)?(a.kd(!0),a.updateAdornments()):a.Mb():c.ei=!0}t.Vi=function(){return!0};t.dc=function(){return!0};t.Bh=function(){return!1};t.vg=function(){return!0};
function Eo(a,b,c,d){b.constructor===a.constructor||Fo||(Fo=!0,Ha('Should not change the class of the Part when changing category from "'+c+'" to "'+d+'"'),Ha(" Old class: "+Va(a.constructor)+", new class: "+Va(b.constructor)+", part: "+a.toString()));a.Xj();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.qf(a);b.cloneProtected(a);a.Bf=d;a.v();a.S();b=a.diagram;d=!0;null!==b&&(d=b.skipsUndoManager,
b.skipsUndoManager=!0);a.kb=e;a.F=f?a.F|4096:a.F&-4097;a.F=g?a.F|524288:a.F&-524289;a instanceof V&&(a.T=h?a.T|4:a.T&-5,a.T=k?a.T|1:a.T&-2,a.T=l?a.T|2:a.T&-3);null!==e&&a.Fa();e=a.layerName;e!==c&&(a.Vg=c,a.layerName=e);null!==b&&(b.skipsUndoManager=d);a.dc()&&a.C(64)}T.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};
T.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};T.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};
T.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};T.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};
T.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};T.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};
T.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};T.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 wi(a,b){a.F=b?a.F|16384:a.F&-16385}function Fj(a){return 0!==(a.F&32768)}function yo(a,b){a.F=b?a.F|32768:a.F&-32769}
function sl(a,b){a.F=b?a.F|65536:a.F&-65537}function Dg(a){return 0!==(a.F&131072)}t=T.prototype;t.kd=function(a){this.F=a?this.F|131072:this.F&-131073};function Go(a,b){a.F=b?a.F|1048576:a.F&-1048577}t.Ah=function(){var a=this.containingGroup;null!==a&&(a.v(),null!==a.placeholder&&a.placeholder.v(),a.gd())};t.S=function(){var a=this.diagram;null!==a&&!Ej(this)&&!Fj(this)&&this.isVisible()&&this.wb.o()&&a.S(Oj(this,this.wb))};
t.v=function(){W.prototype.v.call(this);var a=this.diagram;null!==a&&(a.Fd.add(this),this instanceof V&&null!==this.labeledLink&&Hl(this.labeledLink),a.ec(!0))};t.hq=function(a){a||(a=this.Uh,null!==a&&Ho(a,this))};t.iq=function(a){a||(a=this.Uh,null!==a&&Io(a,this))};t.ck=function(){var a=this.data;if(null!==a){var b=this.diagram;null!==b&&(b=b.model,null!==b&&b.um(a))}};t.az=function(){return Jo(this,this)};
function Jo(a,b){var c=b.containingGroup;return null!==c?1+Jo(a,c):b instanceof V&&(b=b.labeledLink,null!==b)?Jo(a,b):0}t.dz=function(){return Ko(this,this)};function Ko(a,b){var c=b.containingGroup;return null!==c||b instanceof V&&(c=b.labeledLink,null!==c)?Ko(a,c):b}t.Xd=function(a){return a instanceof xg?Lo(this,this,a):!1};function Lo(a,b,c){if(b===c||null===c)return!1;var d=b.containingGroup;return null===d||d!==c&&!Lo(a,d,c)?b instanceof V&&(b=b.labeledLink,null!==b)?Lo(a,b,c):!1:!0}
t.lx=function(a){if(null===a)return null;E&&w(a,T,T,"findCommonContainingGroup:other");if(this===a)return this.containingGroup;for(var b=this;null!==b;){b instanceof xg&&Go(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.F&1048576)){c=b;break}b instanceof V&&(a=b.labeledLink,null!==a&&(b=a));b=b.containingGroup}for(b=this;null!==b;)b instanceof xg&&Go(b,!1),b instanceof V&&(a=b.labeledLink,null!==a&&(b=a)),b=b.containingGroup;return c};
T.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};
T.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.Uh,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 Uj(a){if(!a.isVisible())return!1;a=a.layer;return null!==a&&a.isTemporary?!1:!0}
function Xk(a,b,c,d,e,f){void 0===f&&(f=null);if(!(a.contains(b)||null!==f&&!f(b)||b instanceof Cf))if(a.add(b),b instanceof V){if(c&&b instanceof xg)for(var g=b.memberParts;g.next();)Xk(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)&&Xk(a,h,c,d,e,f)}}if(1<d)for(b=b.hv();b.next();)Xk(a,b.value,c,d-1,e,f)}else if(b instanceof S)for(b=b.labelNodes;b.next();)Xk(a,
b.value,c,d,e,f)}
na.Object.defineProperties(T.prototype,{key:{configurable:!0,get:function(){var a=this.diagram;if(null!==a)return a.model.ra(this.data)}},adornments:{configurable:!0,get:function(){return null===this.zf?Db:this.zf.iteratorValues}},layer:{configurable:!0,get:function(){return this.ii}},diagram:{configurable:!0,get:function(){var a=this.ii;return null!==a?a.diagram:null}},layerName:{configurable:!0,get:function(){return this.Vg},set:function(a){var b=
this.Vg;if(b!==a){z(a,"string",T,"layerName");var c=this.diagram;if(null===c||null!==c.dm(a)&&!c.partManager.addsToTemporaryLayer)if(this.Vg=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.dm(a),null!==a&&a!==b))){var d=b.zc(-1,this,!0);0<=d&&c.cb(rf,"parts",b,this,null,d,!0);d=a.Si(99999999,this,!0);b.visible!==a.visible&&this.Ob(a.visible);0<=d&&c.cb(qf,"parts",a,null,this,!0,d);d=this.layerChanged;if(null!==d){var e=c.fa;c.fa=!0;d(this,
b,a);c.fa=e}}}}},layerChanged:{configurable:!0,get:function(){return this.fo},set:function(a){var b=this.fo;b!==a&&(null!==a&&z(a,"function",T,"layerChanged"),this.fo=a,this.g("layerChanged",b,a))}},zOrder:{configurable:!0,get:function(){return this.Pp},set:function(a){var b=this.Pp;if(b!==a){z(a,"number",T,"zOrder");this.Pp=a;var c=this.layer;null!==c&&zi(c,-1,this);this.g("zOrder",b,a);a=this.diagram;null!==a&&a.S()}}},locationObject:{configurable:!0,get:function(){if(null===
this.Ye){var a=this.locationObjectName;""!==a?(a=this.bb(a),null!==a?this.Ye=a:this.Ye=this):this instanceof Cf?this.type!==W.Link&&null!==this.placeholder?this.Ye=this.placeholder:this.Ye=this:this.Ye=this}return this.Ye.visible?this.Ye:this}},minLocation:{configurable:!0,get:function(){return this.vo},set:function(a){var b=this.vo;b.A(a)||(E&&w(a,J,T,"minLocation"),this.vo=a=a.J(),this.g("minLocation",b,a))}},maxLocation:{configurable:!0,get:function(){return this.oo},
set:function(a){var b=this.oo;b.A(a)||(E&&w(a,J,T,"maxLocation"),this.oo=a=a.J(),this.g("maxLocation",b,a))}},locationObjectName:{configurable:!0,get:function(){return this.mo},set:function(a){var b=this.mo;b!==a&&(E&&z(a,"string",T,"locationObjectName"),this.mo=a,this.Ye=null,this.v(),this.g("locationObjectName",b,a))}},locationSpot:{configurable:!0,get:function(){return this.no},set:function(a){var b=this.no;b.A(a)||(E&&(w(a,M,T,"locationSpot"),a.Za()||v("Part.locationSpot must be a specific Spot value, not: "+
a)),this.no=a=a.J(),this.v(),this.g("locationSpot",b,a))}},location:{configurable:!0,get:function(){return this.oe},set:function(a){E&&w(a,J,T,"location");var b=a.x,c=a.y,d=this.oe,e=d.x,f=d.y;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))||(a=a.J(),b=a,this.Bh()?b=!1:(this.oe=b,this.F|=2097152,!1===Ej(this)&&(xo(this),c=this.ua,c.o()&&(e=c.copy(),c.h(c.x+(b.x-d.x),c.y+(b.y-d.y)),Bo(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.Bf},set:function(a){var b=this.Bf;if(b!==a){z(a,"string",T,"category");var c=this.diagram,d=this.data,e=null;if(null!==c&&null!==d&&!(this instanceof Cf)){var f=c.model.undoManager;f.isEnabled&&!f.isUndoingRedoing&&(e=this.clone(),e.Z.addAll(this.Z))}this.Bf=a;this.g("category",b,a);null===c||null===d||this instanceof Cf?this instanceof Cf&&(e=this.adornedPart,null!==e&&(a=e.zf,null!==a&&a.remove(b),e.rh(this.category,this))):(f=c.model,f.undoManager.isUndoingRedoing||
(this.Bh()?(c.partManager.setLinkCategoryForData(d,a),c=c.partManager.findLinkTemplateForCategory(a),null!==c&&(mh(c),c=c.copy(),null!==c&&Eo(this,c,b,a))):(null!==f&&f.zq(d,a),c=Mo(c.partManager,d,a),null!==c&&(mh(c),c=c.copy(),null===c||c instanceof S||(d=this.location.copy(),Eo(this,c,b,a),this.location.o()||(this.location=d)))),null!==e&&(b=this.clone(),b.Z.addAll(this.Z),this.g("self",e,b))))}}},self:{configurable:!0,get:function(){return this},set:function(a){Eo(this,a,this.category,
a.category)}},copyable:{configurable:!0,get:function(){return 0!==(this.F&1)},set:function(a){var b=0!==(this.F&1);b!==a&&(E&&z(a,"boolean",T,"copyable"),this.F^=1,this.g("copyable",b,a))}},deletable:{configurable:!0,get:function(){return 0!==(this.F&2)},set:function(a){var b=0!==(this.F&2);b!==a&&(E&&z(a,"boolean",T,"deletable"),this.F^=2,this.g("deletable",b,a))}},textEditable:{configurable:!0,get:function(){return 0!==(this.F&4)},set:function(a){var b=
0!==(this.F&4);b!==a&&(E&&z(a,"boolean",T,"textEditable"),this.F^=4,this.g("textEditable",b,a),this.Mb())}},groupable:{configurable:!0,get:function(){return 0!==(this.F&8)},set:function(a){var b=0!==(this.F&8);b!==a&&(E&&z(a,"boolean",T,"groupable"),this.F^=8,this.g("groupable",b,a))}},movable:{configurable:!0,get:function(){return 0!==(this.F&16)},set:function(a){var b=0!==(this.F&16);b!==a&&(E&&z(a,"boolean",T,"movable"),this.F^=16,this.g("movable",b,a))}},selectionAdorned:{configurable:!0,
enumerable:!0,get:function(){return 0!==(this.F&32)},set:function(a){var b=0!==(this.F&32);b!==a&&(E&&z(a,"boolean",T,"selectionAdorned"),this.F^=32,this.g("selectionAdorned",b,a),this.Mb())}},isInDocumentBounds:{configurable:!0,get:function(){return 0!==(this.F&64)},set:function(a){var b=0!==(this.F&64);if(b!==a){E&&z(a,"boolean",T,"isInDocumentBounds");this.F^=64;var c=this.diagram;null!==c&&c.Ya();this.g("isInDocumentBounds",b,a)}}},isLayoutPositioned:{configurable:!0,
get:function(){return 0!==(this.F&128)},set:function(a){var b=0!==(this.F&128);b!==a&&(E&&z(a,"boolean",T,"isLayoutPositioned"),this.F^=128,this.g("isLayoutPositioned",b,a),this.C(a?4:8))}},selectable:{configurable:!0,get:function(){return 0!==(this.F&256)},set:function(a){var b=0!==(this.F&256);b!==a&&(E&&z(a,"boolean",T,"selectable"),this.F^=256,this.g("selectable",b,a),this.Mb())}},reshapable:{configurable:!0,get:function(){return 0!==(this.F&512)},set:function(a){var b=
0!==(this.F&512);b!==a&&(E&&z(a,"boolean",T,"reshapable"),this.F^=512,this.g("reshapable",b,a),this.Mb())}},resizable:{configurable:!0,get:function(){return 0!==(this.F&1024)},set:function(a){var b=0!==(this.F&1024);b!==a&&(E&&z(a,"boolean",T,"resizable"),this.F^=1024,this.g("resizable",b,a),this.Mb())}},rotatable:{configurable:!0,get:function(){return 0!==(this.F&2048)},set:function(a){var b=0!==(this.F&2048);b!==a&&(E&&z(a,"boolean",T,"rotatable"),this.F^=2048,this.g("rotatable",
b,a),this.Mb())}},isSelected:{configurable:!0,get:function(){return 0!==(this.F&4096)},set:function(a){var b=0!==(this.F&4096);if(b!==a){E&&z(a,"boolean",T,"isSelected");var c=this.diagram;if(!a||this.canSelect()&&!(null!==c&&c.selection.count>=c.maxSelectionCount)){this.F^=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.Mb();a=this.selectionChanged;null!==a&&a(this);
null!==c&&(c.ec(),c.skipsUndoManager=d)}}}},isHighlighted:{configurable:!0,get:function(){return 0!==(this.F&524288)},set:function(a){var b=0!==(this.F&524288);if(b!==a){E&&z(a,"boolean",T,"isHighlighted");this.F^=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.F&8192)},set:function(a){var b=
0!==(this.F&8192);b!==a&&(E&&z(a,"boolean",T,"isShadowed"),this.F^=8192,this.g("isShadowed",b,a),this.S())}},isAnimated:{configurable:!0,get:function(){return 0!==(this.F&262144)},set:function(a){var b=0!==(this.F&262144);b!==a&&(E&&z(a,"boolean",T,"isAnimated"),this.F^=262144,this.g("isAnimated",b,a))}},highlightedChanged:{configurable:!0,get:function(){return this.Rn},set:function(a){var b=this.Rn;b!==a&&(null!==a&&z(a,"function",T,"highlightedChanged"),this.Rn=a,this.g("highlightedChanged",
b,a))}},selectionObjectName:{configurable:!0,get:function(){return this.qp},set:function(a){var b=this.qp;b!==a&&(E&&z(a,"string",T,"selectionObjectName"),this.qp=a,this.eh=null,this.g("selectionObjectName",b,a))}},selectionAdornmentTemplate:{configurable:!0,get:function(){return this.op},set:function(a){var b=this.op;b!==a&&(E&&w(a,Cf,T,"selectionAdornmentTemplate"),this.op=a,this.g("selectionAdornmentTemplate",b,a))}},selectionObject:{configurable:!0,get:function(){if(null===
this.eh){var a=this.selectionObjectName;null!==a&&""!==a?(a=this.bb(a),null!==a?this.eh=a:this.eh=this):this instanceof S?(a=this.path,null!==a?this.eh=a:this.eh=this):this.eh=this}return this.eh}},selectionChanged:{configurable:!0,get:function(){return this.pp},set:function(a){var b=this.pp;b!==a&&(null!==a&&z(a,"function",T,"selectionChanged"),this.pp=a,this.g("selectionChanged",b,a))}},resizeAdornmentTemplate:{configurable:!0,get:function(){return this.$o},set:function(a){var b=
this.$o;b!==a&&(E&&w(a,Cf,T,"resizeAdornmentTemplate"),this.$o=a,this.g("resizeAdornmentTemplate",b,a))}},resizeObjectName:{configurable:!0,get:function(){return this.bp},set:function(a){var b=this.bp;b!==a&&(E&&z(a,"string",T,"resizeObjectName"),this.bp=a,this.g("resizeObjectName",b,a))}},resizeObject:{configurable:!0,get:function(){var a=this.resizeObjectName;return""!==a&&(a=this.bb(a),null!==a)?a:this}},resizeCellSize:{configurable:!0,get:function(){return this.ap},
set:function(a){var b=this.ap;b.A(a)||(E&&w(a,Zb,T,"resizeCellSize"),this.ap=a=a.J(),this.g("resizeCellSize",b,a))}},rotateAdornmentTemplate:{configurable:!0,get:function(){return this.cp},set:function(a){var b=this.cp;b!==a&&(E&&w(a,Cf,T,"rotateAdornmentTemplate"),this.cp=a,this.g("rotateAdornmentTemplate",b,a))}},rotateObjectName:{configurable:!0,get:function(){return this.ep},set:function(a){var b=this.ep;b!==a&&(E&&z(a,"string",T,"rotateObjectName"),this.ep=a,this.g("rotateObjectName",
b,a))}},rotateObject:{configurable:!0,get:function(){var a=this.rotateObjectName;return""!==a&&(a=this.bb(a),null!==a)?a:this}},rotationSpot:{configurable:!0,get:function(){return this.fp},set:function(a){var b=this.fp;b.A(a)||(E&&(w(a,M,T,"rotationSpot"),a===Qd||a.Za()||v("Part.rotationSpot must be a specific Spot value or Spot.Default, not: "+a)),this.fp=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",T,"text"),this.Rb=a,this.g("text",b,a))}},containingGroup:{configurable:!0,get:function(){return this.Uh},set:function(a){if(this.dc()){var b=this.Uh;if(b!==a){E&&null!==a&&w(a,xg,T,"containingGroup");null===a||this!==a&&!a.Xd(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?Io(b,this):
this instanceof xg&&null!==c&&c.Bi.remove(this);this.Uh=a;null!==a?Ho(a,this):this instanceof xg&&null!==c&&c.Bi.add(this);this.C(1);if(null!==c){var d=this.data,e=c.model;if(null!==d&&e.Ti()){var f=e.ra(null!==a?a.data:null);e.zt(d,f)}}d=this.containingGroupChanged;null!==d&&(e=!0,null!==c&&(e=c.fa,c.fa=!0),d(this,b,a),null!==c&&(c.fa=e));if(this instanceof xg)for(c=new H,Xk(c,this,!0,0,!0),c=c.iterator;c.next();)if(d=c.value,d instanceof V)for(d=d.linksConnected;d.next();)No(d.value);if(this instanceof
V){for(c=this.linksConnected;c.next();)No(c.value);c=this.labeledLink;null!==c&&No(c)}this.g("containingGroup",b,a);null!==a&&(b=a.layer,null!==b&&zi(b,-1,a))}}else v("cannot set the Part.containingGroup of a Link or Adornment")}},containingGroupChanged:{configurable:!0,get:function(){return this.dn},set:function(a){var b=this.dn;b!==a&&(null!==a&&z(a,"function",T,"containingGroupChanged"),this.dn=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.ho},set:function(a){var b=this.ho;b!==a&&(E&&z(a,"number",T,"layoutConditions"),this.ho=a,this.g("layoutConditions",b,a))}},dragComputation:{configurable:!0,get:function(){return this.An},set:function(a){var b=this.An;b!==a&&(null!==a&&z(a,"function",T,"dragComputation"),this.An=a,this.g("dragComputation",b,a))}},shadowOffset:{configurable:!0,
enumerable:!0,get:function(){return this.wi},set:function(a){var b=this.wi;b.A(a)||(E&&w(a,J,T,"shadowOffset"),this.wi=a=a.J(),this.S(),this.g("shadowOffset",b,a))}},shadowColor:{configurable:!0,get:function(){return this.Nj},set:function(a){var b=this.Nj;b!==a&&(E&&z(a,"string",T,"shadowColor"),this.Nj=a,this.S(),this.g("shadowColor",b,a))}},shadowBlur:{configurable:!0,get:function(){return this.Qd},set:function(a){var b=this.Qd;b!==a&&(E&&z(a,"number",T,"shadowBlur"),
this.Qd=a,this.S(),this.g("shadowBlur",b,a))}}});T.prototype.invalidateLayout=T.prototype.C;T.prototype.findCommonContainingGroup=T.prototype.lx;T.prototype.isMemberOf=T.prototype.Xd;T.prototype.findTopLevelPart=T.prototype.dz;T.prototype.findSubGraphLevel=T.prototype.az;T.prototype.ensureBounds=T.prototype.bc;T.prototype.getDocumentBounds=T.prototype.eq;T.prototype.getRelativePoint=T.prototype.rf;T.prototype.findObject=T.prototype.bb;T.prototype.moveTo=T.prototype.moveTo;
T.prototype.invalidateAdornments=T.prototype.Mb;T.prototype.clearAdornments=T.prototype.Xj;T.prototype.removeAdornment=T.prototype.wf;T.prototype.addAdornment=T.prototype.rh;T.prototype.findAdornment=T.prototype.ek;T.prototype.updateTargetBindings=T.prototype.Fa;var Fo=!1;T.className="Part";T.LayoutNone=0;T.LayoutAdded=1;T.LayoutRemoved=2;T.LayoutShown=4;T.LayoutHidden=8;T.LayoutNodeSized=16;T.LayoutGroupLayout=32;T.LayoutNodeReplaced=64;T.LayoutStandard=127;T.LayoutAll=16777215;
function Cf(a){T.call(this,a);this.F&=-257;this.Vg="Adornment";this.ce=null;this.Jw=0;this.Uw=!1;this.l=[];this.Pa=null}ma(Cf,T);Cf.prototype.toString=function(){var a=this.adornedPart;return"Adornment("+this.category+")"+(null!==a?a.toString():"")};Cf.prototype.updateRelationshipsFromData=function(){};
Cf.prototype.lk=function(a){var b=this.adornedObject.part;if(b instanceof S&&this.adornedObject instanceof Hg){var c=b.path;b.lk(a);a=c.geometry;b=this.Z.j;c=b.length;for(var d=0;d<c;d++){var e=b[d];e.isPanelMain&&e instanceof Hg&&(e.sa=a)}}};Cf.prototype.Vi=function(){var a=this.ce;if(null===a)return!0;a=a.part;return null===a||!Ej(a)};Cf.prototype.dc=function(){return!1};
Cf.prototype.tk=function(a,b,c,d,e,f,g){if(a===qf&&"elements"===b)if(e instanceof lh)null===this.Pa?this.Pa=e:E&&this.Pa!==e&&v("Cannot insert a second Placeholder into the visual tree of an Adornment.");else{if(e instanceof W){var h=e.cm(function(a){return a instanceof lh});h instanceof lh&&(null===this.Pa?this.Pa=h:E&&this.Pa!==h&&v("Cannot insert a second Placeholder into the visual tree of an Adornment."))}}else a===rf&&"elements"===b&&null!==this.Pa&&(d===this.Pa?this.Pa=null:d instanceof W&&
this.Pa.tg(d)&&(this.Pa=null));T.prototype.tk.call(this,a,b,c,d,e,f,g)};Cf.prototype.updateAdornments=function(){};Cf.prototype.ck=function(){};
na.Object.defineProperties(Cf.prototype,{placeholder:{configurable:!0,get:function(){return this.Pa}},adornedObject:{configurable:!0,get:function(){return this.ce},set:function(a){E&&null!==a&&w(a,N,T,"adornedObject:value");var b=this.adornedPart,c=null;null!==a&&(c=a.part);null===b||null!==a&&b===c||b.wf(this.category);this.ce=a;null!==c&&c.rh(this.category,this)}},adornedPart:{configurable:!0,get:function(){var a=this.ce;return null!==a?a.part:null}},containingGroup:{configurable:!0,
enumerable:!0,get:function(){return null}}});Cf.className="Adornment";function V(a){T.call(this,a);this.T=13;this.$a=new F;this.Jp=this.ml=this.li=this.jo=this.io=null;this.Hk=$c;this.tc=this.Ne=null;this.Xo=Oo;this.ph=!1}ma(V,T);V.prototype.cloneProtected=function(a){T.prototype.cloneProtected.call(this,a);a.T=this.T;a.T=this.T&-17;a.io=this.io;a.jo=this.jo;a.li=this.li;a.Jp=this.Jp;a.Hk=this.Hk.J();a.Xo=this.Xo};t=V.prototype;
t.qf=function(a){T.prototype.qf.call(this,a);a.gd();a.Ne=this.Ne;a.tc=null};function Po(a,b){null!==b&&(null===a.Ne&&(a.Ne=new H),a.Ne.add(b))}function Qo(a,b,c,d){if(null===b||null===a.Ne)return null;for(var e=a.Ne.iterator;e.next();){var f=e.value;if(f.ot===a&&f.vv===b&&f.Cx===c&&f.Ex===d||f.ot===b&&f.vv===a&&f.Cx===d&&f.Ex===c)return f}return null}t.Az=function(a,b,c){if(void 0===b||null===b)b="";if(void 0===c||null===c)c="";a=Qo(this,a,b,c);null!==a&&a.hm()};
t.tk=function(a,b,c,d,e,f,g){a===qf&&"elements"===b?this.tc=null:a===rf&&"elements"===b&&(this.tc=null);T.prototype.tk.call(this,a,b,c,d,e,f,g)};t.gd=function(a){void 0===a&&(a=null);for(var b=this.linksConnected;b.next();){var c=b.value;null!==a&&a.contains(c)||(Ro(this,c.fromPort),Ro(this,c.toPort),c.Ta())}};function tl(a,b){for(var c=a.linksConnected;c.next();){var d=c.value;if(d.fromPort===b||d.toPort===b)Ro(a,d.fromPort),Ro(a,d.toPort),d.Ta()}}
function Ro(a,b){null!==b&&(b=b.Wo,null!==b&&b.hm(),a=a.containingGroup,null===a||a.isSubGraphExpanded||Ro(a,a.port))}t.Vi=function(){return!0};V.prototype.getAvoidableRect=function(a){a.set(this.actualBounds);a.Sp(this.Hk);return a};V.prototype.findVisibleNode=function(){for(var a=this;null!==a&&!a.isVisible();)a=a.containingGroup;return a};
V.prototype.isVisible=function(){if(!T.prototype.isVisible.call(this))return!1;var a=!0,b=Gi,c=this.diagram;if(null!==c){if(li(c.animationManager,this))return!0;a=c.isTreePathToChildren;b=c.treeCollapsePolicy}if(b===Gi){if(a=this.rg(),null!==a&&!a.isTreeExpanded)return!1}else if(b===Lk){if(a=a?this.fv():this.gv(),0<a.count&&a.all(function(a){return!a.isTreeExpanded}))return!1}else if(b===Mk&&(a=a?this.fv():this.gv(),0<a.count&&a.any(function(a){return!a.isTreeExpanded})))return!1;a=this.labeledLink;
return null!==a?a.isVisible():!0};t=V.prototype;t.Ob=function(a){T.prototype.Ob.call(this,a);for(var b=this.linksConnected;b.next();)b.value.Ob(a)};t.dv=function(a){void 0===a&&(a=null);if(null===a)return this.$a.iterator;E&&z(a,"string",V,"findLinksConnected:pid");var b=new Gb(this.$a),c=this;b.predicate=function(b){return b.fromNode===c&&b.fromPortId===a||b.toNode===c&&b.toPortId===a};return b};
t.aq=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findLinksOutOf:pid");var b=new Gb(this.$a),c=this;b.predicate=function(b){return b.fromNode!==c?!1:null===a?!0:b.fromPortId===a};return b};t.ud=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findLinksInto:pid");var b=new Gb(this.$a),c=this;b.predicate=function(b){return b.toNode!==c?!1:null===a?!0:b.toPortId===a};return b};
t.ev=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findNodesConnected:pid");for(var b=null,c=null,d=this.$a.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 Eb(c):Db};
t.gv=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findNodesOutOf:pid");for(var b=null,c=null,d=this.$a.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 Eb(c):Db};
t.fv=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findNodesInto:pid");for(var b=null,c=null,d=this.$a.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 Eb(c):Db};
t.Wy=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 Gb(this.$a),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.Xy=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 Gb(this.$a),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 So(a,b,c){Ro(a,c);var d=a.$a.contains(b);d||a.$a.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.fa,g.fa=!0);e(a,b,c);null!==g&&(g.fa=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.ph||(e.ph=f),!f.isTreeLeaf||null!==a&&a.undoManager.isUndoingRedoing||(d?c===f&&(f.isTreeLeaf=!1):b===f&&(f.isTreeLeaf=!1))))}
function To(a,b,c){Ro(a,c);var d=a.$a.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.fa,e.fa=!0);f(a,b,c);null!==e&&(e.fa=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.ph=!1),null===b||b.isTreeLeaf||(0===b.$a.count?(b.ph=null,null!==e&&e.undoManager.isUndoingRedoing||(b.isTreeLeaf=!0)):Kk(b)))}
function Kk(a){a.ph=!1;if(0!==a.$a.count){var b=!0,c=a.diagram;if(null===c||!c.undoManager.isUndoingRedoing){null!==c&&(b=c.isTreePathToChildren);for(c=a.$a.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.hq=function(a){T.prototype.hq.call(this,a);a||(Kk(this),a=this.ml,null!==a&&Uo(a,this))};t.iq=function(a){T.prototype.iq.call(this,a);a||(a=this.ml,null!==a&&null!==a.bd&&(a.bd.remove(this),a.v()))};
t.ck=function(){if(0<this.$a.count){var a=this.diagram;if(null!==a)for(var b=null!==a.commandHandler?a.commandHandler.deletesConnectedLinks:!0,c=this.$a.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;T.prototype.ck.call(this)};
t.Ys=function(a){E&&z(a,"string",V,"findPort:pid");if(null===this.tc){if(""===a&&!1===this.zh)return this;Vo(this)}var b=this.tc.K(a);return null!==b||""!==a&&(b=this.tc.K(""),null!==b)?b:this};function Vo(a){null===a.tc?a.tc=new Ub:a.tc.clear();a.xk(a,function(a,c){Xl(a,c)});0===a.tc.count&&a.tc.add("",a)}function Xl(a,b){var c=b.portId;null!==c&&null!==a.tc&&a.tc.add(c,b)}
function Wl(a,b,c){var d=b.portId;if(null!==d&&(null!==a.tc&&a.tc.remove(d),b=a.diagram,null!==b&&c)){c=null;for(a=a.dv(d);a.next();)d=a.value,null===c&&(c=Qa()),c.push(d);if(null!==c){for(a=0;a<c.length;a++)b.remove(c[a]);Ta(c)}}}
t.Cz=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.$a.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.$a.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.hz=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=this;if(a)for(;;){a=null;for(var c=b.$a.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.$a.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.Ty=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;)Go(b,!0),b=b.rg();var c=null;for(b=a;null!==b;){if(0!==(b.F&1048576)){c=b;break}b=b.rg()}for(b=this;null!==b;)Go(b,!1),b=b.rg();return c};
t.Mi=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=this.$a.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.rg=function(){var a=this.ph;if(null===a)return null;if(a instanceof V)return a;var b=!0;a=this.diagram;null!==a&&(b=a.isTreePathToChildren);a=this.$a.iterator;if(b)for(;a.next();){if(b=a.value,b.isTreeLink&&(b=b.fromNode,b!==this))return this.ph=b}else for(;a.next();)if(b=a.value,b.isTreeLink&&(b=b.toNode,b!==this))return this.ph=b;return this.ph=null};t.fz=function(){function a(b,d){if(null!==b){d.add(b);var c=b.Mi();null!==c&&(d.add(c),a(b.rg(),d))}}var b=new H;a(this,b);return b};
t.ez=function(){return Wo(this,this)};function Wo(a,b){b=b.rg();return null===b?0:1+Wo(a,b)}t.cq=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=new Gb(this.$a);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.hv=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);var c=b=null,d=this.$a.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 F,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 F,b.add(c),b.add(a)):c=a);return null!==b?b.iterator:null!==c?new Eb(c):Db};
t.gz=function(a){void 0===a&&(a=Infinity);z(a,"number",V,"findTreeParts:level");var b=new H;Xk(b,this,!1,a,!0);return b};V.prototype.collapseTree=function(a){void 0===a&&(a=1);B(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);Xo(this,c,b.isTreePathToChildren,a,b,this,b.treeCollapsePolicy===Gi);b.He=!1}};
function Xo(a,b,c,d,e,f,g){if(1<d)for(var h=c?a.aq():a.ud();h.next();){var k=h.value;k.isTreeLink&&(k=k.bt(a),null===k||k===a||b.contains(k)||(b.add(k),Xo(k,b,c,d-1,e,f,g)))}else Yo(a,b,c,e,f,g)}
function Yo(a,b,c,d,e,f){for(var g=e===a?!0:a.isTreeExpanded,h=c?a.aq():a.ud();h.next();){var k=h.value;if(k.isTreeLink&&(k=k.bt(a),null!==k&&k!==a)){var l=b.contains(k);l||b.add(k);g&&(f&&d.Qp(k,e),k.Ah(),k.Ob(!1));k.isTreeExpanded&&(k.wasTreeExpanded=k.isTreeExpanded,l||Yo(k,b,c,d,e,f))}}a.isTreeExpanded=!1}
V.prototype.expandTree=function(a){void 0===a&&(a=2);B(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);Zo(this,c,b.isTreePathToChildren,a,b,this,b.treeCollapsePolicy===Gi);b.He=!1}};
function Zo(a,b,c,d,e,f,g){for(var h=f===a?!1:a.isTreeExpanded,k=c?a.aq():a.ud();k.next();){var l=k.value;l.isTreeLink&&(h||l.Mc||l.Ta(),l=l.bt(a),null!==l&&l!==a&&!b.contains(l)&&(b.add(l),h||(l.Ob(!0),l.Ah(),g&&e.Rp(l,f)),2<d||l.wasTreeExpanded))&&(l.wasTreeExpanded=!1,Zo(l,b,c,d-1,e,f,g))}a.isTreeExpanded=!0}
na.Object.defineProperties(V.prototype,{portSpreading:{configurable:!0,get:function(){return this.Xo},set:function(a){var b=this.Xo;b!==a&&(E&&tb(a,V,V,"portSpreading"),this.Xo=a,this.g("portSpreading",b,a),a=this.diagram,null!==a&&a.undoManager.isUndoingRedoing||this.gd())}},avoidable:{configurable:!0,get:function(){return 0!==(this.T&8)},set:function(a){var b=0!==(this.T&8);if(b!==a){E&&z(a,"boolean",V,"avoidable");this.T^=8;var c=this.diagram;null!==c&&Dk(c,this);this.g("avoidable",
b,a)}}},avoidableMargin:{configurable:!0,get:function(){return this.Hk},set:function(a){"number"===typeof a?a=new Hc(a):w(a,Hc,V,"avoidableMargin");var b=this.Hk;if(!b.A(a)){this.Hk=a=a.J();var c=this.diagram;null!==c&&Dk(c,this);this.g("avoidableMargin",b,a)}}},linksConnected:{configurable:!0,get:function(){return this.$a.iterator}},linkConnected:{configurable:!0,get:function(){return this.io},set:function(a){var b=this.io;b!==a&&(null!==a&&z(a,"function",
V,"linkConnected"),this.io=a,this.g("linkConnected",b,a))}},linkDisconnected:{configurable:!0,get:function(){return this.jo},set:function(a){var b=this.jo;b!==a&&(null!==a&&z(a,"function",V,"linkDisconnected"),this.jo=a,this.g("linkDisconnected",b,a))}},linkValidation:{configurable:!0,get:function(){return this.li},set:function(a){var b=this.li;b!==a&&(null!==a&&z(a,"function",V,"linkValidation"),this.li=a,this.g("linkValidation",b,a))}},isLinkLabel:{configurable:!0,
get:function(){return null!==this.ml}},labeledLink:{configurable:!0,get:function(){return this.ml},set:function(a){var b=this.ml;if(b!==a){E&&null!==a&&w(a,S,V,"labeledLink");var c=this.diagram,d=this.data;if(null!==b){null!==b.bd&&(b.bd.remove(this),b.v());if(null!==c&&null!==d&&!c.undoManager.isUndoingRedoing){var e=b.data,f=c.model;if(null!==e&&f.jm()){var g=f.ra(d);void 0!==g&&f.Fx(e,g)}}this.containingGroup=null}this.ml=a;null!==a&&(Uo(a,this),null===c||null===d||c.undoManager.isUndoingRedoing||
(e=a.data,c=c.model,null!==e&&c.jm()&&(d=c.ra(d),void 0!==d&&c.Lu(e,d))),this.containingGroup=a.containingGroup);Hl(this);this.g("labeledLink",b,a)}}},port:{configurable:!0,get:function(){return this.Ys("")}},ports:{configurable:!0,get:function(){null===this.tc&&Vo(this);return this.tc.iteratorValues}},isTreeExpanded:{configurable:!0,get:function(){return 0!==(this.T&1)},set:function(a){var b=0!==(this.T&1);if(b!==a){E&&z(a,"boolean",V,"isTreeExpanded");this.T^=
1;var c=this.diagram;this.g("isTreeExpanded",b,a);b=this.treeExpandedChanged;if(null!==b){var d=!0;null!==c&&(d=c.fa,c.fa=!0);b(this);null!==c&&(c.fa=d)}null!==c&&c.undoManager.isUndoingRedoing?this.Ob(a):a?this.expandTree():this.collapseTree()}}},wasTreeExpanded:{configurable:!0,get:function(){return 0!==(this.T&2)},set:function(a){var b=0!==(this.T&2);b!==a&&(E&&z(a,"boolean",V,"wasTreeExpanded"),this.T^=2,this.g("wasTreeExpanded",b,a))}},treeExpandedChanged:{configurable:!0,
get:function(){return this.Jp},set:function(a){var b=this.Jp;b!==a&&(null!==a&&z(a,"function",V,"treeExpandedChanged"),this.Jp=a,this.g("treeExpandedChanged",b,a))}},isTreeLeaf:{configurable:!0,get:function(){return 0!==(this.T&4)},set:function(a){var b=0!==(this.T&4);b!==a&&(E&&z(a,"boolean",V,"isTreeLeaf"),this.T^=4,this.g("isTreeLeaf",b,a))}}});V.prototype.expandTree=V.prototype.expandTree;V.prototype.collapseTree=V.prototype.collapseTree;V.prototype.findTreeParts=V.prototype.gz;
V.prototype.findTreeChildrenNodes=V.prototype.hv;V.prototype.findTreeChildrenLinks=V.prototype.cq;V.prototype.findTreeLevel=V.prototype.ez;V.prototype.findTreeParentChain=V.prototype.fz;V.prototype.findTreeParentNode=V.prototype.rg;V.prototype.findTreeParentLink=V.prototype.Mi;V.prototype.findCommonTreeParent=V.prototype.Ty;V.prototype.findTreeRoot=V.prototype.hz;V.prototype.isInTreeOf=V.prototype.Cz;V.prototype.findPort=V.prototype.Ys;V.prototype.findLinksTo=V.prototype.Xy;
V.prototype.findLinksBetween=V.prototype.Wy;V.prototype.findNodesInto=V.prototype.fv;V.prototype.findNodesOutOf=V.prototype.gv;V.prototype.findNodesConnected=V.prototype.ev;V.prototype.findLinksInto=V.prototype.ud;V.prototype.findLinksOutOf=V.prototype.aq;V.prototype.findLinksConnected=V.prototype.dv;V.prototype.invalidateConnectedLinks=V.prototype.gd;V.prototype.invalidateLinkBundle=V.prototype.Az;var $o=new D(V,"SpreadingNone",10),Oo=new D(V,"SpreadingEvenly",11),ap=new D(V,"SpreadingPacked",12);
V.className="Node";V.SpreadingNone=$o;V.SpreadingEvenly=Oo;V.SpreadingPacked=ap;function xg(a){V.call(this,a);this.T|=4608;this.so=new H;this.wl=new H;this.Pa=this.Bp=this.mi=this.to=this.ro=null;this.ic=new Ni;this.ic.group=this}ma(xg,V);
xg.prototype.cloneProtected=function(a){V.prototype.cloneProtected.call(this,a);this.T=this.T&-32769;a.ro=this.ro;a.to=this.to;a.mi=this.mi;a.Bp=this.Bp;var b=a.cm(function(a){return a instanceof lh});b instanceof lh?a.Pa=b:a.Pa=null;null!==this.ic?(a.ic=this.ic.copy(),a.ic.group=a):(null!==a.ic&&(a.ic.group=null),a.ic=null)};t=xg.prototype;
t.qf=function(a){V.prototype.qf.call(this,a);var b=a.fk();for(a=a.memberParts;a.next();){var c=a.value;c.v();c.C(8);c.Xj();if(c instanceof V)c.gd(b);else if(c instanceof S)for(c=c.labelNodes;c.next();)c.value.gd(b)}};
t.tk=function(a,b,c,d,e,f,g){if(a===qf&&"elements"===b)if(e instanceof lh)null===this.Pa?this.Pa=e:this.Pa!==e&&v("Cannot insert a second Placeholder into the visual tree of a Group.");else{if(e instanceof W){var h=e.cm(function(a){return a instanceof lh});h instanceof lh&&(null===this.Pa?this.Pa=h:this.Pa!==h&&v("Cannot insert a second Placeholder into the visual tree of a Group."))}}else a===rf&&"elements"===b&&null!==this.Pa&&(d===this.Pa?this.Pa=null:d instanceof W&&this.Pa.tg(d)&&(this.Pa=null));
V.prototype.tk.call(this,a,b,c,d,e,f,g)};t.vh=function(a,b,c,d){this.Ye=this.Pa;V.prototype.vh.call(this,a,b,c,d)};t.Vi=function(){if(!V.prototype.Vi.call(this))return!1;for(var a=this.memberParts;a.next();){var b=a.value;if(b instanceof V){if(b.isVisible()&&Ej(b))return!1}else if(b instanceof S&&b.isVisible()&&Ej(b)&&b.fromNode!==this&&b.toNode!==this)return!1}return!0};
function Ho(a,b){if(a.so.add(b)){b instanceof xg&&a.wl.add(b);var c=a.memberAdded;if(null!==c){var d=!0,e=a.diagram;null!==e&&(d=e.fa,e.fa=!0);c(a,b);null!==e&&(e.fa=d)}a.isVisible()&&a.isSubGraphExpanded||b.Ob(!1)}b instanceof S&&!a.computesBoundsIncludingLinks||(b=a.Pa,null===b&&(b=a),b.v())}
function Io(a,b){if(a.so.remove(b)){b instanceof xg&&a.wl.remove(b);var c=a.memberRemoved;if(null!==c){var d=!0,e=a.diagram;null!==e&&(d=e.fa,e.fa=!0);c(a,b);null!==e&&(e.fa=d)}a.isVisible()&&a.isSubGraphExpanded||b.Ob(!0)}b instanceof S&&!a.computesBoundsIncludingLinks||(b=a.Pa,null===b&&(b=a),b.v())}t.ck=function(){if(0<this.so.count){var a=this.diagram;if(null!==a)for(var b=this.so.copy().iterator;b.next();)a.remove(b.value)}V.prototype.ck.call(this)};
xg.prototype.canAddMembers=function(a){var b=this.diagram;if(null===b)return!1;b=b.commandHandler;for(a=Zk(a).iterator;a.next();)if(!b.isValidMember(this,a.value))return!1;return!0};xg.prototype.addMembers=function(a,b){var c=this.diagram;if(null===c)return!1;c=c.commandHandler;var d=!0;for(a=Zk(a).iterator;a.next();){var e=a.value;!b||c.isValidMember(this,e)?e.containingGroup=this:d=!1}return d};
xg.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=xg.prototype;
t.gd=function(a){void 0===a&&(a=null);var b=0!==(this.T&65536);V.prototype.gd.call(this,a);if(!b)for(0!==(this.T&65536)!==!0&&(this.T=this.T^65536),b=this.cv();b.next();){var c=b.value;if(null===a||!a.contains(c)){var d=c.fromNode;null!==d&&d!==this&&d.Xd(this)&&!d.isVisible()?(Ro(d,c.fromPort),Ro(d,c.toPort),c.Ta()):(d=c.toNode,null!==d&&d!==this&&d.Xd(this)&&!d.isVisible()&&(Ro(d,c.fromPort),Ro(d,c.toPort),c.Ta()))}}};
t.cv=function(){var a=this.fk();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.Vy=function(){var a=this.fk();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.Uy=function(){function a(b,d){null!==b&&(d.add(b),a(b.containingGroup,d))}var b=new H;a(this,b);return b};t.fk=function(){var a=new H;Xk(a,this,!0,0,!0);a.remove(this);return a};t.Ob=function(a){V.prototype.Ob.call(this,a);for(var b=this.memberParts;b.next();)b.value.Ob(a)};xg.prototype.collapseSubGraph=function(){var a=this.diagram;if(null!==a&&!a.He){a.He=!0;var b=this.fk();bp(this,b,a,this);a.He=!1}};
function bp(a,b,c,d){for(var e=a.memberParts;e.next();){var f=e.value;f.Ob(!1);f instanceof xg&&f.isSubGraphExpanded&&(f.wasSubGraphExpanded=f.isSubGraphExpanded,bp(f,b,c,d));if(f instanceof V)f.gd(b),c.Qp(f,d);else if(f instanceof S)for(f=f.labelNodes;f.next();)f.value.gd(b)}a.isSubGraphExpanded=!1}xg.prototype.expandSubGraph=function(){var a=this.diagram;if(null!==a&&!a.He){a.He=!0;var b=this.fk();cp(this,b,a,this);a.He=!1}};
function cp(a,b,c,d){for(var e=a.memberParts;e.next();){var f=e.value;f.Ob(!0);f instanceof xg&&f.wasSubGraphExpanded&&(f.wasSubGraphExpanded=!1,cp(f,b,c,d));if(f instanceof V)f.gd(b),c.Rp(f,d);else if(f instanceof S)for(f=f.labelNodes;f.next();)f.value.gd(b)}a.isSubGraphExpanded=!0}
xg.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.fk().iterator;b.next();){var f=b.value;f instanceof S&&(f.suspendsRouting&&a.add(f),f.Mc||f.fromNode!==this&&f.toNode!==this)&&(f.suspendsRouting=!0)}for(b.reset();b.next();)if(f=b.value,!(f.Bh()||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 S&&(f.suspendsRouting=a.contains(f),f.Mc||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.Ta(),bk(f)&&f.Ta();J.free(e)};
na.Object.defineProperties(xg.prototype,{placeholder:{configurable:!0,get:function(){return this.Pa}},computesBoundsAfterDrag:{configurable:!0,get:function(){return 0!==(this.T&2048)},set:function(a){var b=0!==(this.T&2048);b!==a&&(z(a,"boolean",xg,"computesBoundsAfterDrag"),this.T^=2048,this.g("computesBoundsAfterDrag",b,a))}},computesBoundsIncludingLinks:{configurable:!0,get:function(){return 0!==(this.T&4096)},set:function(a){z(a,"boolean",xg,"computesBoundsIncludingLinks");
var b=0!==(this.T&4096);b!==a&&(this.T^=4096,this.g("computesBoundsIncludingLinks",b,a))}},computesBoundsIncludingLocation:{configurable:!0,get:function(){return 0!==(this.T&8192)},set:function(a){z(a,"boolean",xg,"computesBoundsIncludingLocation");var b=0!==(this.T&8192);b!==a&&(this.T^=8192,this.g("computesBoundsIncludingLocation",b,a))}},handlesDragDropForMembers:{configurable:!0,get:function(){return 0!==(this.T&16384)},set:function(a){z(a,"boolean",xg,"handlesDragDropForMembers");
var b=0!==(this.T&16384);b!==a&&(this.T^=16384,this.g("handlesDragDropForMembers",b,a))}},memberParts:{configurable:!0,get:function(){return this.so.iterator}},layout:{configurable:!0,get:function(){return this.ic},set:function(a){var b=this.ic;if(b!==a){null!==a&&w(a,Ni,xg,"layout");null!==b&&(b.diagram=null,b.group=null);this.ic=a;var c=this.diagram;null!==a&&(a.diagram=c,a.group=this);null!==c&&(c.Dg=!0);this.g("layout",b,a);null!==c&&c.ec()}}},memberAdded:{configurable:!0,
enumerable:!0,get:function(){return this.ro},set:function(a){var b=this.ro;b!==a&&(null!==a&&z(a,"function",xg,"memberAdded"),this.ro=a,this.g("memberAdded",b,a))}},memberRemoved:{configurable:!0,get:function(){return this.to},set:function(a){var b=this.to;b!==a&&(null!==a&&z(a,"function",xg,"memberRemoved"),this.to=a,this.g("memberRemoved",b,a))}},memberValidation:{configurable:!0,get:function(){return this.mi},set:function(a){var b=this.mi;b!==a&&(null!==a&&z(a,"function",
xg,"memberValidation"),this.mi=a,this.g("memberValidation",b,a))}},ungroupable:{configurable:!0,get:function(){return 0!==(this.T&256)},set:function(a){var b=0!==(this.T&256);b!==a&&(z(a,"boolean",xg,"ungroupable"),this.T^=256,this.g("ungroupable",b,a))}},isSubGraphExpanded:{configurable:!0,get:function(){return 0!==(this.T&512)},set:function(a){var b=0!==(this.T&512);if(b!==a){z(a,"boolean",xg,"isSubGraphExpanded");this.T^=512;var c=this.diagram;this.g("isSubGraphExpanded",
b,a);b=this.subGraphExpandedChanged;if(null!==b){var d=!0;null!==c&&(d=c.fa,c.fa=!0);b(this);null!==c&&(c.fa=d)}null!==c&&c.undoManager.isUndoingRedoing?(null!==this.Pa&&this.Pa.v(),this.memberParts.each(function(a){a.updateAdornments()})):a?this.expandSubGraph():this.collapseSubGraph()}}},wasSubGraphExpanded:{configurable:!0,get:function(){return 0!==(this.T&1024)},set:function(a){var b=0!==(this.T&1024);b!==a&&(z(a,"boolean",xg,"wasSubGraphExpanded"),this.T^=1024,this.g("wasSubGraphExpanded",
b,a))}},subGraphExpandedChanged:{configurable:!0,get:function(){return this.Bp},set:function(a){var b=this.Bp;b!==a&&(null!==a&&z(a,"function",xg,"subGraphExpandedChanged"),this.Bp=a,this.g("subGraphExpandedChanged",b,a))}},sk:{configurable:!0,get:function(){return 0!==(this.T&32768)},set:function(a){0!==(this.T&32768)!==a&&(this.T^=32768)}}});xg.prototype.expandSubGraph=xg.prototype.expandSubGraph;xg.prototype.collapseSubGraph=xg.prototype.collapseSubGraph;
xg.prototype.findSubGraphParts=xg.prototype.fk;xg.prototype.findContainingGroupChain=xg.prototype.Uy;xg.prototype.findExternalNodesConnected=xg.prototype.Vy;xg.prototype.findExternalLinksConnected=xg.prototype.cv;xg.className="Group";function lh(){N.call(this);this.gb=Zc;this.lp=new L(NaN,NaN,NaN,NaN)}ma(lh,N);lh.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.gb=this.gb.J();a.lp=this.lp.copy()};
lh.prototype.xh=function(a){if(null===this.background&&null===this.areaBackground)return!1;var b=this.naturalBounds;return Qc(0,0,b.width,b.height,a.x,a.y)};
lh.prototype.mm=function(){var a=this.part;null!==a&&(a instanceof xg||a instanceof Cf)||v("Placeholder is not inside a Group or Adornment.");if(a instanceof xg){var b=this.computeBorder(this.lp),c=this.minSize,d=this.rc;Cc(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);ml(this,0,0,d.width,d.height);c=a.memberParts;for(d=!1;c.next();)if(c.value.isVisible()){d=!0;break}c=a.diagram;(d=!d||null===c)||(d=c.animationManager,d.Nf?
(d=d.Cj.K(a),d=null!==d&&(d.start.position||d.start.location)):d=!1);d||isNaN(b.x)||isNaN(b.y)?null!==c&&c.animationManager.isAnimating&&c.animationManager.hs.add(this):(c=J.alloc(),c.Yi(b,a.locationSpot),c.A(a.location)||(a.location=new J(c.x,c.y)),J.free(c))}else{b=this.rc;c=this.gb;d=c.left+c.right;var e=c.top+c.bottom,f=a.adornedObject;a.angle=f.Oi();var g=0;f instanceof Hg&&(g=f.strokeWidth);var h=f.Fe(),k=f.naturalBounds,l=(k.width+g)*h;g=(k.height+g)*h;a.type!==W.Link&&(f=f.oa("Selection"===
a.category?fd:a.locationSpot,J.alloc()),a.location=f,J.free(f));isNaN(l)||isNaN(g)?(a=a.adornedObject,l=a.oa(fd,J.alloc()),f=L.allocAt(l.x,l.y,0,0),f.Le(a.oa(ud,l)),f.Le(a.oa(hd,l)),f.Le(a.oa(sd,l)),Cc(b,f.width+d||0,f.height+e||0),ml(this,-c.left,-c.top,b.width,b.height),J.free(l),L.free(f)):(Cc(b,l+d||0,g+e||0),ml(this,-c.left,-c.top,b.width,b.height))}};lh.prototype.vh=function(a,b,c,d){this.actualBounds.h(a,b,c,d)};
lh.prototype.computeBorder=function(a){var b=this.part,c=b.diagram;if(null!==c&&b instanceof xg&&!b.layer.isTemporary&&b.computesBoundsAfterDrag&&this.lp.o()){var d=c.toolManager.findTool("Dragging");if(d===c.currentTool&&(c=d.computeBorder(b,this.lp,a),null!==c))return c}c=L.alloc();d=this.computeMemberBounds(c);var e=this.gb;b instanceof xg&&!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 xg&&b.computesBoundsIncludingLocation&&b.location.o()&&a.Le(b.location);return a};
lh.prototype.computeMemberBounds=function(a){if(!(this.part instanceof xg))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 S){if(!b.computesBoundsIncludingLinks)continue;if(Dj(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(lh.prototype,{padding:{configurable:!0,get:function(){return this.gb},set:function(a){"number"===typeof a?a=new Hc(a):w(a,Hc,lh,"padding");var b=this.gb;b.A(a)||(this.gb=a=a.J(),this.g("padding",b,a))}}});lh.className="Placeholder";
function S(){T.call(this,W.Link);this.Va=8;this.Qe=null;this.Re="";this.hf=this.Jn=null;this.jf="";this.Ip=null;this.Qm=ch;this.ln=0;this.on=ch;this.pn=NaN;this.Jj=dp;this.xp=.5;this.bd=null;this.yb=(new F).freeze();this.dh=this.Hc=null;this.Cl=new L;this.sa=new me;this.Un=!0;this.L=this.w=this.Af=this.Jf=null;this.l=[];this.Eu=new J;this.wr=this.Qw=this.Pw=null;this.fu=NaN;this.R=null}ma(S,T);
S.prototype.cloneProtected=function(a){T.prototype.cloneProtected.call(this,a);a.Va=this.Va&-113;a.Re=this.Re;a.Jn=this.Jn;a.jf=this.jf;a.Ip=this.Ip;a.Qm=this.Qm;a.ln=this.ln;a.on=this.on;a.pn=this.pn;a.Jj=this.Jj;a.xp=this.xp;null!==this.R&&(a.R=this.R.copy())};t=S.prototype;t.qf=function(a){T.prototype.qf.call(this,a);this.Re=a.Re;this.jf=a.jf;a.Hc=null;a.Ta();a.Af=this.Af;var b=a.fromPort;null!==b&&Ro(a.fromNode,b);b=a.toPort;null!==b&&Ro(a.toNode,b)};
t.hb=function(a){a.classType===S?2===(a.value&2)?this.routing=a:a===fh||a===bh||a===ah?this.curve=a:a===ep||a===fp||a===gp?this.adjusting=a:a!==dp&&a!==ch&&v("Unknown Link enum value for a Link property: "+a):T.prototype.hb.call(this,a)};t.Jc=function(){null===this.R&&(this.R=new il)};t.Vi=function(){var a=this.fromNode;if(null!==a){var b=a.findVisibleNode();null!==b&&(a=b);if(Ej(a)||Fj(a))return!1}a=this.toNode;return null!==a&&(b=a.findVisibleNode(),null!==b&&(a=b),Ej(a)||Fj(a))?!1:!0};t.Rv=function(){return!1};
t.Sv=function(){};t.dc=function(){return!1};S.prototype.computeAngle=function(a,b,c){return S.computeAngle(b,c)};S.computeAngle=function(a,b){switch(a){default:case ch:a=0;break;case Kn:a=b;break;case Tm:a=b+90;break;case Vm:a=b-90;break;case hp:a=b+180;break;case ip:a=K.qq(b);90<a&&270>a&&(a-=180);break;case Um:a=K.qq(b+90);90<a&&270>a&&(a-=180);break;case Wm:a=K.qq(b-90);90<a&&270>a&&(a-=180);break;case Xm:a=K.qq(b);if(45<a&&135>a||225<a&&315>a)return 0;90<a&&270>a&&(a-=180)}return K.qq(a)};
function No(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.Uh;if(c!==b){null!==c&&Io(c,a);a.Uh=b;null!==b&&Ho(b,a);var e=a.containingGroupChanged;if(null!==e){var f=!0,g=a.diagram;null!==g&&(f=g.fa,g.fa=!0);e(a,c,b);null!==g&&(g.fa=f)}!a.Mc||a.Pw!==c&&a.Qw!==c||a.Ta()}if(a.isLabeledLink)for(a=a.labelNodes;a.next();)a.value.containingGroup=d}t=S.prototype;
t.Ah=function(){var a=this.containingGroup;null!==a&&this.fromNode!==a&&this.toNode!==a&&a.computesBoundsIncludingLinks&&T.prototype.Ah.call(this)};t.bt=function(a){E&&w(a,V,S,"getOtherNode:node");var b=this.fromNode;return a===b?this.toNode:b};t.nz=function(a){E&&w(a,N,S,"getOtherPort:port");var b=this.fromPort;return a===b?this.toPort:b};function Uo(a,b){null===a.bd&&(a.bd=new H);a.bd.add(b);a.v()}
t.hq=function(a){T.prototype.hq.call(this,a);jp(this)&&this.jq(this.actualBounds);if(!a){a=this.Qe;var b=null;null!==a&&(b=this.fromPort,So(a,this,b));var c=this.hf;if(null!==c){var d=this.toPort;c===a&&d===b||So(c,this,d)}kp(this)}};t.iq=function(a){T.prototype.iq.call(this,a);jp(this)&&this.jq(this.actualBounds);if(!a){a=this.Qe;var b=null;null!==a&&(b=this.fromPort,To(a,this,b));var c=this.hf;if(null!==c){var d=this.toPort;c===a&&d===b||To(c,this,d)}lp(this)}};
t.ck=function(){this.Mc=!0;if(null!==this.bd){var a=this.diagram;if(null!==a)for(var b=this.bd.copy().iterator;b.next();)a.remove(b.value)}null!==this.data&&(a=this.diagram,null!==a&&a.partManager.removeDataForLink(this))};S.prototype.updateRelationshipsFromData=function(){if(null!==this.data){var a=this.diagram;null!==a&&a.partManager.updateRelationshipsFromData(this)}};
S.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?T.prototype.move.call(this,a,!1):(a=J.allocAt(c.x+d,c.y+e),T.prototype.move.call(this,a,!1),J.free(a));ng(this,d,e);for(a=this.labelNodes;a.next();)b=a.value,c=b.position,b.moveTo(c.x+d,c.y+e)};
S.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};S.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};
S.prototype.computeMidPoint=function(a){var b=this.pointsCount;if(0===b)return a.assign(qc),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()===fh))return this.sa.kv(.5,a),a.add(this.i(0)),c=this.sa.figures.first(),a.offset(-c.startX,-c.startY),a;if(this.computeCurve()===fh){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.wy(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};
S.prototype.computeMidAngle=function(){var a=this.pointsCount;if(2>a)return NaN;if(2===a)return this.i(0).Xa(this.i(1));if(this.isOrthogonal&&(15<=this.computeCorner()||this.computeCurve()===fh)){a:{a=this.sa;var b=.5;0>b?b=0:1<b&&(b=1);if(a.type===pe)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()===fh&&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.vy(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).Xa(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).Xa(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.Xa(e)};t=S.prototype;t.i=function(a){return this.yb.j[a]};
t.ld=function(a,b){E&&(w(b,J,S,"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.yb.jd(a,b)};t.N=function(a,b,c){E&&(B(b,S,"setPointAt:x"),B(c,S,"setPointAt:y"));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.yb.jd(a,new J(b,c))};
t.yz=function(a,b){E&&(w(b,J,S,"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.yb.Lb(a,b)};t.m=function(a,b,c){E&&(B(b,S,"insertPointAt:x"),B(c,S,"insertPointAt:y"));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.yb.Lb(a,new J(b,c))};
t.Be=function(a){E&&(w(a,J,S,"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.yb.add(a)};t.mf=function(a,b){E&&(B(a,S,"insertPointAt:x"),B(b,S,"insertPointAt:y"));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.yb.add(new J(a,b))};
t.Gv=function(a){E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.yb.nb(a)};t.Yj=function(){E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.yb.clear()};
function ng(a,b,c){if(0!==b||0!==c){for(var d=a.Mc,e=new F,f=a.yb.iterator;f.next();){var g=f.value;e.add((new J(g.x+b,g.y+c)).freeze())}e.freeze();f=a.yb;a.yb=e;isNaN(b)||isNaN(c)||a.diagram.animationManager.sb?a.v():(a.oe.h(a.oe.x+b,a.oe.y+c),a.ua.h(a.ua.x+b,a.ua.y+c),Hl(a));d&&mp(a);b=a.diagram;null!==b&&b.animationManager.sb&&(a.dh=e);a.g("points",f,e)}}t.Eh=function(){null===this.Hc&&(this.Hc=this.yb,this.yb=this.yb.copy())};
t.nf=function(){if(null!==this.Hc){for(var a=this.Hc,b=this.yb,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.cc();break}}else this.v(),this.cc();this.Hc=null;c=this.diagram;null!==c&&c.animationManager.sb&&(this.dh=b);mp(this);this.g("points",
a,b)}};t.Hx=function(){null!==this.Hc&&(this.yb=this.Hc,this.Hc=null)};function mp(a){0===a.yb.count?a.Mc=!1:(a.Mc=!0,a.wr=null,a.fu=NaN,a.defaultFromPoint=a.i(0),a.defaultToPoint=a.i(a.pointsCount-1),np(a,!1))}
t.Ta=function(){if(!this.suspendsRouting){var a=this.diagram;if(a){if(a.lt.contains(this)||a.undoManager.isUndoingRedoing)return;a=a.animationManager;if(a.isTicking&&!a.isAnimating)return;null!==this.dh&&!a.isTicking&&a.isAnimating&&(this.dh=null)}a=this.path;null!==a&&(this.Mc=!1,this.v(),a.v())}};t.cj=function(){if(!this.Mc&&!this.Uu){var a=!0;try{this.Uu=!0,this.Eh(),a=this.computePoints()}finally{this.Uu=!1,a?this.nf():this.Hx()}}};
S.prototype.computePoints=function(){var a=this.diagram;if(null===a)return!1;var b=this.fromNode,c=null;null===b?(a.ti||(a.gp=new Hg,a.gp.desiredSize=rc,a.gp.strokeWidth=0,a.ti=new V,a.ti.add(a.gp),a.ti.bc()),this.defaultFromPoint&&(a.ti.position=a.ti.location=this.defaultFromPoint,a.ti.bc(),b=a.ti,c=a.gp)):c=this.fromPort;if(null!==c&&!b.isVisible()){var d=b.findVisibleNode();null!==d&&d!==b?(b=d,c=d.port):b=d}this.Pw=b;if(null===b||!b.location.o())return!1;for(;!(null===c||c.actualBounds.o()&&c.uf());)c=
c.panel;if(null===c)return!1;var e=this.toNode,f=null;null===e?(a.ui||(a.hp=new Hg,a.hp.desiredSize=rc,a.hp.strokeWidth=0,a.ui=new V,a.ui.add(a.hp),a.ui.bc()),this.defaultToPoint&&(a.ui.position=a.ui.location=this.defaultToPoint,a.ui.bc(),e=a.ui,f=a.hp)):f=this.toPort;null===f||e.isVisible()||(a=e.findVisibleNode(),null!==a&&a!==e?(e=a,f=a.port):e=a);this.Qw=e;if(null===e||!e.location.o())return!1;for(;!(null===f||f.actualBounds.o()&&f.uf());)f=f.panel;if(null===f)return!1;var g=this.pointsCount;
d=this.computeSpot(!0,c);a=this.computeSpot(!1,f);var h=op(d),k=op(a),l=c===f&&null!==c,m=this.isOrthogonal,n=this.curve===fh;this.Jf=l&&!m?n=!0:!1;var p=this.adjusting===ch||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.Yj(),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,x=r;K.B(k,0)?x=0<h?x-l:x+l:(m=-h/k,n=Math.sqrt(l*l/(m*m+1)),0>l&&(n=-n),u=(0>k?-1:1)*n+q,x=m*(u-q)+r);q=g.x+2*h/3;r=g.y+2*k/3;var y=q,A=r;K.B(k,0)?A=0<h?A-l:A+l:(y=(0>k?-1:1)*n+q,A=m*(y-q)+r);this.Yj();this.Be(g);this.mf(u,x);this.mf(y,A);this.Be(p);this.ld(0,this.getLinkPoint(b,c,d,!0,!1,e,f));this.ld(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.mf(g,h)):this.Be(d),this.Be(a)}else{n=this.isAvoiding;p&&(m&&n||l)&&this.Yj();var C=l?this.computeCurviness():0;n=this.getLinkPoint(b,c,d,!0,m,e,f);q=u=r=0;if(m||!h||l)x=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>C&&(q-=180)),0>q?q+=360:360<=q&&(q-=360),l&&(x+=Math.abs(C)*(m?1:2)),0===q?r=x:90===q?u=x:180===q?r=-x:270===q?u=-x:(r=x*Math.cos(q*Math.PI/180),u=x*Math.sin(q*Math.PI/180)),d.Nb()&&l&&(x=c.oa(qd,J.alloc()),y=J.allocAt(x.x+1E3*r,x.y+1E3*u),this.getLinkPointFromPoint(b,c,x,y,!0,n),J.free(x),J.free(y));x=this.getLinkPoint(e,f,a,!1,m,b,c);var G=A=y=0;if(m||!k||l){var I=this.computeEndSegmentLength(e,f,a,!1);G=this.getLinkDirection(e,f,x,a,!1,m,b,c);l&&(k||d.A(a)||!m&&
1===d.x+a.x&&1===d.y+a.y)&&(G+=m?0:30,0>C&&(G+=180));0>G?G+=360:360<=G&&(G-=360);l&&(I+=Math.abs(C)*(m?1:2));0===G?y=I:90===G?A=I:180===G?y=-I:270===G?A=-I:(y=I*Math.cos(G*Math.PI/180),A=I*Math.sin(G*Math.PI/180));a.Nb()&&l&&(a=f.oa(qd,J.alloc()),d=J.allocAt(a.x+1E3*y,a.y+1E3*A),this.getLinkPointFromPoint(e,f,a,d,!1,x),J.free(a),J.free(d))}a=n;if(m||!h||l)a=new J(n.x+r,n.y+u);d=x;if(m||!k||l)d=new J(x.x+y,x.y+A);!p&&!m&&h&&3<g&&this.adjustPoints(0,n,g-2,d)?this.ld(g-1,x):!p&&!m&&k&&3<g&&this.adjustPoints(1,
a,g-1,x)?this.ld(0,n):!p&&(m?6<=g:4<g)&&this.adjustPoints(1,a,g-2,d)?(this.ld(0,n),this.ld(g-1,x)):(this.Yj(),this.Be(n),(m||!h||l)&&this.Be(a),m&&this.addOrthoPoints(a,q,d,G,b,e),(m||!k||l)&&this.Be(d),this.Be(x))}return!0};function pp(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}
S.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.ae()||(e=e.panel);if(null===e){e=d.x;d=d.y;var g=c.x;c=c.y}else{a=e.td;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.gk(e,d,g,c,f);null!==
a&&f.transform(a);return f};function qp(a,b){var c=b.Wo;null===c&&(c=new rp,c.port=b,c.node=b.part,b.Wo=c);return sp(c,a)}
S.prototype.getLinkPoint=function(a,b,c,d,e,f,g,h){void 0===h&&(h=new J);if(c.Za()&&!op(c))return b.oa(c,h),h;if(c.tf()){var k=qp(this,b);if(null!==k){h.assign(k.nq);if(e&&this.routing===tp){var l=qp(this,g);if(null!==l&&k.am<l.am){k=J.alloc();l=J.alloc();var m=new L(b.oa(fd,k),b.oa(ud,l)),n=this.computeSpot(!d,g);a=this.getLinkPoint(f,g,n,!d,e,a,b,l);(c.sf(wd)||c.sf(Ad))&&a.y>=m.y&&a.y<=m.y+m.height?h.y=a.y:(c.sf(vd)||c.sf(Bd))&&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:qd,J.alloc());this.pointsCount>(e?6:2)?(g=d?this.i(1):this.i(this.pointsCount-2),e&&(g=pp(c,g.copy()))):(k=this.computeSpot(!d,g),f=J.alloc(),g=g.oa(.5===k.x&&.5===k.y?k:qd,f),e&&(g=pp(c,g)),J.free(f));this.getLinkPointFromPoint(a,b,c,g,d,h);J.free(c);return h};
S.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.tf()&&(k=qp(this,b),null!==k))switch(k.Ac){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(qd,J.alloc());this.pointsCount>(f?6:2)?(h=e?this.i(1):this.i(this.pointsCount-2),h=f?pp(k,h.copy()):c):(c=J.alloc(),h=h.oa(qd,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.Nb()&&g.Xd(a)&&(k+=180,360<=k&&(k-=360));if(op(d))return k;a=b.Oi();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};S.prototype.computeEndSegmentLength=function(a,b,c,d){if(null!==b&&c.tf()&&(a=qp(this,b),null!==a))return a.av;a=d?this.fromEndSegmentLength:this.toEndSegmentLength;null!==b&&isNaN(a)&&(a=d?b.fromEndSegmentLength:b.toEndSegmentLength);isNaN(a)&&(a=10);return a};
S.prototype.computeSpot=function(a,b){void 0===b&&(b=null);a?(a=b?b:this.fromPort,null===a?a=qd:(b=this.fromSpot,b.Cb()&&(b=a.fromSpot),a=b===Qd?ed:b)):(a=b?b:this.toPort,null===a?a=qd:(b=this.toSpot,b.Cb()&&(b=a.toSpot),a=b===Qd?ed:b));return a};function op(a){return a===ed||.5===a.x&&.5===a.y}S.prototype.computeOtherPoint=function(a,b){a=b.oa(qd);b=b.Wo;b=null!==b?sp(b,this):null;null!==b&&(a=b.nq);return a};
S.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};
S.prototype.pg=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=$b.alloc(),g.reset());g.multiply(this.transform);if(this.wh(a,g))return mn(this,b,c,e),void 0===f&&$b.free(g),!0;if(this.Kc(a,g)){var h=!1;if(!this.isAtomic)for(var k=this.Z.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=$b.alloc();n.set(g);
if(m instanceof W)h=m.pg(a,b,c,d,e,n);else if(this.path===m){if(m instanceof Hg)if(h=a,p=d,!1===m.pickable)h=!1;else if(n.multiply(m.transform),p)b:{var q=h,r=n;if(m.wh(q,r))h=!0;else{if(void 0===r&&(r=m.transform,q.pf(m.actualBounds))){h=!0;break b}h=q.left;p=q.right;var u=q.top;q=q.bottom;var x=J.alloc(),y=J.alloc(),A=J.alloc(),C=$b.alloc();C.set(r);C.uv(m.transform);C.gt();y.x=p;y.y=u;y.transform(C);x.x=h;x.y=u;x.transform(C);r=!1;In(m,x,y,A)?r=!0:(x.x=p,x.y=q,x.transform(C),In(m,x,y,A)?r=!0:(y.x=
h,y.y=q,y.transform(C),In(m,x,y,A)?r=!0:(x.x=h,x.y=u,x.transform(C),In(m,x,y,A)&&(r=!0))));$b.free(C);J.free(x);J.free(y);J.free(A);h=r}}else h=m.wh(h,n)}else h=ol(m,a,d,n);h&&(p=m,null!==b&&(p=b(m)),p&&(null===c||c(p))&&e.add(p));$b.free(n)}}}void 0===f&&$b.free(g);return h||null!==this.background||null!==this.areaBackground}void 0===f&&$b.free(g);return!1};
S.prototype.computeCurve=function(){if(null===this.Jf){var a=this.fromPort,b=this.isOrthogonal;this.Jf=null!==a&&a===this.toPort&&!b}return this.Jf?fh:this.curve};S.prototype.computeCorner=function(){if(this.curve===fh)return 0;var a=this.corner;if(isNaN(a)||0>a)a=10;return a};
S.prototype.findMidLabel=function(){for(var a=this.path,b=this.Z.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};
S.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===Kn||d===ip||d===hp?a=Math.max(a,e):d===Vm||d===Wm||d===Tm||d===Um?a=Math.max(a,g):(b=b.oa(qd).Xa(c.oa(qd))/180*Math.PI,a=Math.max(a,
Math.abs(Math.sin(b)*g)+Math.abs(Math.cos(b)*e)+1));this.curve===fh&&(a*=1.333)}}return a};S.prototype.arrangeBundledLinks=function(a,b){if(b)for(b=0;b<a.length;b++){var c=a[b];c.adjusting===ch&&c.Ta()}};
S.prototype.computeCurviness=function(){var a=this.curviness;if(isNaN(a)){a=16;var b=this.Af;if(null!==b){for(var c=Qa(),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.ot===this.fromNode&&(a=-a);Ta(c)}}return a};S.prototype.computeThickness=function(){if(!this.isVisible())return 0;var a=this.path;return null!==a?Math.max(a.strokeWidth,1):1};
S.prototype.hasCurviness=function(){return!isNaN(this.curviness)||null!==this.Af};
S.prototype.adjustPoints=function(a,b,c,d){var e=this.adjusting;if(this.isOrthogonal){if(e===fp)return!1;e===gp&&(e=ep)}switch(e){case fp:var f=this.i(a),g=this.i(c);if(!f.Sa(b)||!g.Sa(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.da(l,0)){if(K.da(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.da(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.ld(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.da(b,0)||(K.da(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.ld(c,d)}}return!0;case gp:f=this.i(a);n=this.i(c);if(!f.Sa(b)||!n.Sa(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.ld(a,b);for(a+=1;a<c;a++){b=this.i(a);
var u=b.x,x=b.y,y=.5;0!==l&&(y=((e-u)*(e-g)+(f-x)*(f-n))/l);var A=e+y*(g-e),C=f+y*(n-f);b=Math.sqrt((u-A)*(u-A)+(x-C)*(x-C));x<r*(u-A)+C&&(b=-b);0<r&&(b=-b);u=h+y*(k-h);y=m+y*(p-m);0!==r?(b=u+b/q,this.N(a,b,y-(b-u)/r)):this.N(a,u,y+b)}this.ld(c,d)}return!0;case ep: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),bk(this))){this.N(a+1,n,l);this.N(c-1,k,p);c=!1;break a}this.ld(a,b);this.ld(c,d);c=!0}return c;default:return!1}};
S.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.Xc(8,8);h.Xc(8,8);g.Le(a);h.Le(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.ea(a)||g.ea(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.ea(a)||g.ea(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.ea(a)||g.ea(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.ea(a)||g.ea(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||!xk(q)||g.ea(p)&&!f.Xd(e)||h.ea(a)&&!e.Xd(f)||e===f||this.layer.isTemporary)b=!1;else{var r=yk(q,!0,this.containingGroup,null);
if(r.jk(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.jk(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.jk(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.Xc(-r.Zl,-r.Yl);var x=J.alloc();up(r,a.x,a.y)||(K.Wc(q.x,q.y,q.x+q.width,q.y+q.height,a.x,a.y,m.x,m.y,x)?(c=a=x.copy(),b=x.Xa(m)):K.Wc(q.x,q.y,q.x+q.width,q.y+q.height,m.x,m.y,n.x,n.y,x)?(c=a=
x.copy(),b=x.Xa(n)):K.Wc(q.x,q.y,q.x+q.width,q.y+q.height,n.x,n.y,p.x,p.y,x)&&(c=a=x.copy(),b=x.Xa(p)));up(r,p.x,p.y)||(K.Wc(q.x,q.y,q.x+q.width,q.y+q.height,p.x,p.y,n.x,n.y,x)?(u=p=x.copy(),d=n.Xa(x)):K.Wc(q.x,q.y,q.x+q.width,q.y+q.height,n.x,n.y,m.x,m.y,x)?(u=p=x.copy(),d=m.Xa(x)):K.Wc(q.x,q.y,q.x+q.width,q.y+q.height,m.x,m.y,a.x,a.y,x)&&(u=p=x.copy(),d=a.Xa(x)));J.free(x)}g=g.copy().Lc(h);h=r.cA;g.Xc(r.Zl*h,r.Yl*h);vp(r,a,b,p,d,g);h=wp(r,p.x,p.y);!r.abort&&h>=xp&&(Bk(r),h=r.Gz,g.Xc(r.Zl*h,r.Yl*
h),vp(r,a,b,p,d,g),h=wp(r,p.x,p.y));!r.abort&&h>=xp&&r.iA&&(Bk(r),vp(r,a,b,p,d,r.bounds),h=wp(r,p.x,p.y));if(!r.abort&&h<xp&&wp(r,p.x,p.y)!==yp){zp(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.Yl/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.Zl/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.mf(f.x,u.y):this.mf(u.x,f.y));b=!0}else b=!1}}}else b=
!1;b||(this.Be(k),this.Be(l))}};S.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 bk(a){if(null===a.diagram||!a.isAvoiding||!xk(a.diagram))return!1;var b=a.points.j,c=b.length;if(4>c)return!1;a=yk(a.diagram,!0,a.containingGroup,null);for(var d=1;d<c-2;d++){var e=b[d],f=b[d+1];if(!a.jk(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 zp(a,b,c,d,e,f){var g=b.Zl,h=b.Yl,k=wp(b,c,d),l=c,m=d;for(0===e?l+=g:90===e?m+=h:180===e?l-=g:m-=h;k>Ap&&wp(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>Ap)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>Ap&&(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),wp(b,l,m)===k-1?zp(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),wp(b,l,m)===k-1&&zp(a,b,l,m,f,!1)));a.mf(c,d)}S.prototype.Ry=function(a){E&&w(a,J,S,"findClosestSegment:p");var b=a.x;a=a.y;for(var c=this.i(0),d=this.i(1),e=cc(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=cc(b,a,d.x,d.y,c.x,c.y);d=c;h<e&&(f=g,e=h)}return f};S.prototype.cc=function(){this.Un=!0};
S.prototype.lk=function(a){if(!a){if(!1===this.Mc)return;a=this.Bb();if(!this.Un&&(null===a||null!==a.geometry))return}this.sa=this.makeGeometry();a=this.path;if(null!==a){a.sa=this.sa;for(var b=this.Z.j,c=b.length,d=0;d<c;d++){var e=b[d];e!==a&&e.isPanelMain&&e instanceof Hg&&(e.sa=this.sa)}}};
S.prototype.makeGeometry=function(){var a=this.sa,b=this.pointsCount;if(2>b)return a.type=pe,this.Un=!1,a;var c=!1,d=this.diagram;null!==d&&jp(this)&&d.Zh.contains(this)&&(0!==this.Cl.width||0!==this.Cl.height)&&(c=!0);var e=this.i(0).copy(),f=e.copy();d=this.yb.j;var g=this.computeCurve();if(g===fh&&3<=b&&!K.da(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.Eu.x;k-=this.Eu.y;e.x-=d;e.y-=k;if(2!==b||jp(this)){a.type=ne;h=Ae(a);0!==this.computeShortLength(!0)&&(e=Bp(this,e,!0,f));Be(h,e.x,e.y,!1);if(g===fh&&3<=b&&!K.da(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=Bp(this,e,!1,f)),Ce(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(Cp(this,l,n,!1));if(!K.da(p.x,q.x)||!K.da(q.x,r.x))if(!K.da(p.y,q.y)||!K.da(q.y,r.y)){var u=m;isNaN(u)&&(u=this.smoothness/3);var x=p.x;p=p.y;var y=q.x;q=q.y;var A=r.x;r=r.y;var C=u*Dp(x,p,y,q);u*=Dp(y,q,A,r);K.da(p,q)&&K.da(y,A)&&(y>x?r>q?(g.x=y-C,g.y=q-C,b.x=y+u,b.y=
q+u):(g.x=y-C,g.y=q+C,b.x=y+u,b.y=q-u):r>q?(g.x=y+C,g.y=q-C,b.x=y-u,b.y=q+u):(g.x=y+C,g.y=q+C,b.x=y-u,b.y=q-u));K.da(x,y)&&K.da(q,r)&&(q>p?(A>y?(g.x=y-C,g.y=q-C,b.x=y+u):(g.x=y+C,g.y=q-C,b.x=y-u),b.y=q+u):(A>y?(g.x=y-C,g.y=q+C,b.x=y+u):(g.x=y+C,g.y=q+C,b.x=y-u),b.y=q-u));if(K.da(x,y)&&K.da(y,A)||K.da(p,q)&&K.da(q,r))x=.5*(x+A),p=.5*(p+r),g.x=x,g.y=p,b.x=x,b.y=p;1===n?(e.x=.5*(c.x+l.x),e.y=.5*(c.y+l.y)):2===n&&K.da(c.x,this.i(0).x)&&K.da(c.y,this.i(0).y)&&(e.x=.5*(c.x+l.x),e.y=.5*(c.y+l.y));Ce(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=Bp(this,e.copy(),!1,gc));f=.5*(f+e.x);c=.5*(c+e.y);Ce(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=Bp(this,g.copy(),!1,gc)),Ce(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=Cp(this,f,g,1<g);m=this.i(g);if(g>=
b-1){if(!f.A(m))0!==this.computeShortLength(!1)&&(m=Bp(this,m.copy(),!1,gc)),Ep(this,h,-d,-k,f,m,c);else if(0===e)for(g=1;g<b;)m=this.i(g++),Ep(this,h,-d,-k,f,m,c),f.assign(m);break}e=Cp(this,m,g+1,g<b-3);g=-d;l=-k;n=this.i(e);x=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)?(Ep(this,h,g,l,f,m,x),f.assign(m)):(y=m.x,q=m.y,A=y,r=q,m.x>f.x?y=m.x-p:y=m.x+p,n.y>m.y?r=m.y+u:r=m.y-u,Ep(this,h,g,l,f,new J(y,q),x),He(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)?(Ep(this,h,g,l,f,m,x),f.assign(m)):(y=m.x,q=m.y,A=y,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,Ep(this,h,g,l,f,new J(y,q),x),He(h,m.x+g,m.y+l,A+g,r+l),f.h(A,r))):(Ep(this,h,g,l,f,m,x),f.assign(m));g=e}J.free(f)}Ke=h}else h=this.i(1).copy(),h.x-=d,h.y-=k,0!==this.computeShortLength(!0)&&(e=Bp(this,e,!0,f)),0!==this.computeShortLength(!1)&&
(h=Bp(this,h,!1,f)),a.type=pe,a.startX=e.x,a.startY=e.y,a.endX=h.x,a.endY=h.y;this.Un=!1;return a};function Dp(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.da(a,0)?b:K.da(b,0)?a:Math.sqrt(a*a+b*b)}
function Bp(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=Dp(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=Dp(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 Cp(a,b,c,d){for(var e=a.pointsCount,f=b;K.da(b.x,f.x)&&K.da(b.y,f.y);){if(c>=e)return e-1;f=a.i(c++)}if(!K.da(b.x,f.x)&&!K.da(b.y,f.y))return c-1;for(var g=f;K.da(b.x,f.x)&&K.da(f.x,g.x)&&(!d||(b.y>=f.y?f.y>=g.y:f.y<=g.y))||K.da(b.y,f.y)&&K.da(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 Ep(a,b,c,d,e,f,g){if(!g&&jp(a)){g=[];var h=0;a.isVisible()&&(h=Fp(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===bh?Be(b,n,p,!1):Ce(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===bh?Be(b,l,n,!1):Ce(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===bh?Be(b,p,l,!1):Ce(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===bh?Be(b,n,k,!1):Ce(b,l,m,l,k,n,k)}}b.lineTo(f.x+c,f.y+d)}
function Fp(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 S){if(k===a)return 0<d.length&&d.sort(function(a,b){return a-b}),d.length;if(k.isVisible()&&jp(k)){var l=k.routeBounds;l.o()&&a.routeBounds.Kc(l)&&!a.usesSamePort(k)&&(l=k.path,null!==l&&l.uf()&&Gp(b,c,d,k))}}}}}0<d.length&&d.sort(function(a,b){return a-b});return d.length}
function Gp(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,x=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,x)<n&&Math.max(g,x)>n&&!K.B(g,x)){h.x=r;h.y=n;m=!0;break a}}else if(!K.B(n,q)&&
K.B(g,x)&&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 jp(a){a=a.curve;return a===ah||a===bh}function np(a,b){if(b||jp(a))b=a.diagram,null===b||b.Zi||b.Zh.contains(a)||0===a.Cl.width&&0===a.Cl.height||b.Zh.add(a,a.Cl)}
S.prototype.jq=function(a){var b=this.layer;if(null!==b&&b.visible&&!b.isTemporary){var c=b.diagram;if(null!==c&&!c.animationManager.isAnimating){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 S&&(k===this?f=!0:f&&Hp(this,k,a))}}else if(d)for(f=e.Ga.j,e=f.length,g=0;g<e;g++)h=f[g],h instanceof S&&Hp(this,h,a)}}}};
function Hp(a,b,c){if(null!==b&&null!==b.sa&&jp(b)){var d=b.routeBounds;d.o()&&(a.routeBounds.Kc(d)||c.Kc(d))&&(a.usesSamePort(b)||b.cc())}}S.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.Sa(e))return!0;b=this.i(b-1);a=a.i(c-1);if(b.Sa(a)||d.Sa(a)||b.Sa(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};
S.prototype.isVisible=function(){if(!T.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};S.prototype.Ob=function(a){T.prototype.Ob.call(this,a);null!==this.Af&&this.Af.hm();if(null!==this.bd)for(var b=this.bd.iterator;b.next();)b.value.Ob(a)};
function kp(a){var b=a.Qe;if(null!==b){var c=a.hf;if(null!==c){for(var d=a.Re,e=a.jf,f=a=null,g=b.$a.j,h=g.length,k=0;k<h;k++){var l=g[k];if(l.Qe===b&&l.Re===d&&l.hf===c&&l.jf===e||l.Qe===c&&l.Re===e&&l.hf===b&&l.jf===d)null===f?f=l:(null===a&&(a=[],a.push(f)),a.push(l))}if(null!==a){f=Qo(b,c,d,e);null===f&&(f=new Ip(b,d,c,e),Po(b,f),Po(c,f));f.links=a;for(b=0;b<a.length;b++)a[b].Af=f;f.hm()}}}}function lp(a){var b=a.Af;null!==b&&(a.Af=null,a=b.links.indexOf(a),0<=a&&(Oa(b.links,a),b.hm()))}
S.prototype.Bh=function(){return!0};
na.Object.defineProperties(S.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,S,"fromNode");var c=this.fromPort;null!==b&&(this.hf!==b&&To(b,this,c),lp(this),this.C(2));this.Qe=a;null!==a&&this.Ob(a.isVisible());this.Jf=null;this.Ta();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.fa,d.fa=!0);f(this,c,e);
null!==d&&(d.fa=g)}null!==a&&(this.hf!==a&&So(a,this,e),kp(this),this.C(1));this.g("fromNode",b,a);No(this)}}},fromPortId:{configurable:!0,get:function(){return this.Re},set:function(a){var b=this.Re;if(b!==a){E&&z(a,"string",S,"fromPortId");var c=this.fromPort;null!==c&&Ro(this.fromNode,c);lp(this);this.Re=a;var d=this.fromPort;null!==d&&Ro(this.fromNode,d);var e=this.diagram;if(null!==e){var f=this.data,g=e.model;null!==f&&g.jm()&&g.Lx(f,a)}c!==d&&(this.Jf=null,this.Ta(),f=this.fromPortChanged,
null!==f&&(g=!0,null!==e&&(g=e.fa,e.fa=!0),f(this,c,d),null!==e&&(e.fa=g)));kp(this);this.g("fromPortId",b,a)}}},fromPort:{configurable:!0,get:function(){var a=this.Qe;return null===a?null:a.Ys(this.Re)}},fromPortChanged:{configurable:!0,get:function(){return this.Jn},set:function(a){var b=this.Jn;b!==a&&(null!==a&&z(a,"function",S,"fromPortChanged"),this.Jn=a,this.g("fromPortChanged",b,a))}},toNode:{configurable:!0,get:function(){return this.hf},set:function(a){var b=
this.hf;if(b!==a){E&&null!==a&&w(a,V,S,"toNode");var c=this.toPort;null!==b&&(this.Qe!==b&&To(b,this,c),lp(this),this.C(2));this.hf=a;null!==a&&this.Ob(a.isVisible());this.Jf=null;this.Ta();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.fa,d.fa=!0);f(this,c,e);null!==d&&(d.fa=g)}null!==a&&(this.Qe!==a&&So(a,this,e),kp(this),this.C(1));this.g("toNode",b,a);No(this)}}},toPortId:{configurable:!0,
get:function(){return this.jf},set:function(a){var b=this.jf;if(b!==a){E&&z(a,"string",S,"toPortId");var c=this.toPort;null!==c&&Ro(this.toNode,c);lp(this);this.jf=a;var d=this.toPort;null!==d&&Ro(this.toNode,d);var e=this.diagram;if(null!==e){var f=this.data,g=e.model;null!==f&&g.jm()&&g.Px(f,a)}c!==d&&(this.Jf=null,this.Ta(),f=this.toPortChanged,null!==f&&(g=!0,null!==e&&(g=e.fa,e.fa=!0),f(this,c,d),null!==e&&(e.fa=g)));kp(this);this.g("toPortId",b,a)}}},toPort:{configurable:!0,get:function(){var a=
this.hf;return null===a?null:a.Ys(this.jf)}},toPortChanged:{configurable:!0,get:function(){return this.Ip},set:function(a){var b=this.Ip;b!==a&&(null!==a&&z(a,"function",S,"toPortChanged"),this.Ip=a,this.g("toPortChanged",b,a))}},fromSpot:{configurable:!0,get:function(){return null!==this.R?this.R.Pg:Qd},set:function(a){this.Jc();var b=this.R.Pg;b.A(a)||(E&&w(a,M,S,"fromSpot"),a=a.J(),this.R.Pg=a,this.g("fromSpot",b,a),this.Ta())}},fromEndSegmentLength:{configurable:!0,
enumerable:!0,get:function(){return null!==this.R?this.R.Ng:NaN},set:function(a){this.Jc();var b=this.R.Ng;b!==a&&(E&&z(a,"number",S,"fromEndSegmentLength"),0>a&&Ca(a,">= 0",S,"fromEndSegmentLength"),this.R.Ng=a,this.g("fromEndSegmentLength",b,a),this.Ta())}},fromShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.Og:NaN},set:function(a){this.Jc();var b=this.R.Og;b!==a&&(E&&z(a,"number",S,"fromShortLength"),this.R.Og=a,this.g("fromShortLength",b,a),this.Ta(),this.cc())}},
toSpot:{configurable:!0,get:function(){return null!==this.R?this.R.oh:Qd},set:function(a){this.Jc();var b=this.R.oh;b.A(a)||(E&&w(a,M,S,"toSpot"),a=a.J(),this.R.oh=a,this.g("toSpot",b,a),this.Ta())}},toEndSegmentLength:{configurable:!0,get:function(){return null!==this.R?this.R.mh:NaN},set:function(a){this.Jc();var b=this.R.mh;b!==a&&(E&&z(a,"number",S,"toEndSegmentLength"),0>a&&Ca(a,">= 0",S,"toEndSegmentLength"),this.R.mh=a,this.g("toEndSegmentLength",b,a),this.Ta())}},
toShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.nh:NaN},set:function(a){this.Jc();var b=this.R.nh;b!==a&&(E&&z(a,"number",S,"toShortLength"),this.R.nh=a,this.g("toShortLength",b,a),this.Ta(),this.cc())}},isLabeledLink:{configurable:!0,get:function(){return null===this.bd?!1:0<this.bd.count}},labelNodes:{configurable:!0,get:function(){return null===this.bd?Db:this.bd.iterator}},relinkableFrom:{configurable:!0,get:function(){return 0!==
(this.Va&1)},set:function(a){var b=0!==(this.Va&1);b!==a&&(E&&z(a,"boolean",S,"relinkableFrom"),this.Va^=1,this.g("relinkableFrom",b,a),this.Mb())}},relinkableTo:{configurable:!0,get:function(){return 0!==(this.Va&2)},set:function(a){var b=0!==(this.Va&2);b!==a&&(E&&z(a,"boolean",S,"relinkableTo"),this.Va^=2,this.g("relinkableTo",b,a),this.Mb())}},resegmentable:{configurable:!0,get:function(){return 0!==(this.Va&4)},set:function(a){var b=0!==(this.Va&4);b!==a&&(E&&z(a,
"boolean",S,"resegmentable"),this.Va^=4,this.g("resegmentable",b,a),this.Mb())}},isTreeLink:{configurable:!0,get:function(){return 0!==(this.Va&8)},set:function(a){var b=0!==(this.Va&8);b!==a&&(E&&z(a,"boolean",S,"isTreeLink"),this.Va^=8,this.g("isTreeLink",b,a),null!==this.fromNode&&Kk(this.fromNode),null!==this.toNode&&Kk(this.toNode))}},path:{configurable:!0,get:function(){var a=this.Bb();return a instanceof Hg?a:null}},routeBounds:{configurable:!0,get:function(){this.cj();
var a=this.Cl,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.Le(e)}else if(this.computeCurve()===fh&&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.Xl(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.Xl(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.Le(f),e=2;e<d;e++)f=this.i(e),b=Math.min(f.x,b),c=Math.min(f.y,c),a.Le(f);this.Eu.h(b-a.x,c-a.y)}return a}},midPoint:{configurable:!0,get:function(){this.cj();return this.computeMidPoint(new J)}},midAngle:{configurable:!0,
enumerable:!0,get:function(){this.cj();return this.computeMidAngle()}},flattenedLengths:{configurable:!0,get:function(){if(null===this.wr){this.Mc||mp(this);for(var a=this.wr=[],b=this.pointsCount,c=0;c<b-1;c++){var d=this.i(c);var e=this.i(c+1);K.da(d.x,e.x)?(d=e.y-d.y,0>d&&(d=-d)):K.da(d.y,e.y)?(d=e.x-d.x,0>d&&(d=-d)):d=Math.sqrt(d.Ee(e));a.push(d)}}return this.wr}},flattenedTotalLength:{configurable:!0,get:function(){var a=this.fu;if(isNaN(a)){for(var b=this.flattenedLengths,
c=b.length,d=a=0;d<c;d++)a+=b[d];this.fu=a}return a}},points:{configurable:!0,get:function(){return this.yb},set:function(a){var b=this.yb;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 F,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(!Ja(f)||"number"!==typeof f.x||isNaN(f.x)||"number"!==typeof f.y||isNaN(f.y)){d=
!1;break}}if(d)for(c=new F,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 F)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.yb=c;this.cc();this.v();mp(this);a=this.diagram;null!==a&&(a.Ui||a.undoManager.isUndoingRedoing||a.lt.add(this),a.animationManager.sb&&
(this.dh=c));this.g("points",b,c)}}},pointsCount:{configurable:!0,get:function(){return this.yb.count}},Mc:{configurable:!0,get:function(){return 0!==(this.Va&16)},set:function(a){0!==(this.Va&16)!==a&&(this.Va^=16)}},suspendsRouting:{configurable:!0,get:function(){return 0!==(this.Va&32)},set:function(a){0!==(this.Va&32)!==a&&(this.Va^=32)}},Uu:{configurable:!0,get:function(){return 0!==(this.Va&64)},set:function(a){0!==(this.Va&64)!==a&&(this.Va^=
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.Jj.value&2)}},isAvoiding:{configurable:!0,get:function(){return 4===(this.Jj.value&4)}},geometry:{configurable:!0,get:function(){this.Un&&(this.cj(),this.sa=this.makeGeometry());
return this.sa}},firstPickIndex:{configurable:!0,get:function(){return 2>=this.pointsCount?0:this.isOrthogonal||!op(this.computeSpot(!0))?1:0}},lastPickIndex:{configurable:!0,get:function(){var a=this.pointsCount;return 0===a?0:2>=a?a-1:this.isOrthogonal||!op(this.computeSpot(!1))?a-2:a-1}},adjusting:{configurable:!0,get:function(){return this.Qm},set:function(a){var b=this.Qm;b!==a&&(E&&tb(a,S,S,"adjusting"),this.Qm=a,this.g("adjusting",b,a))}},corner:{configurable:!0,
enumerable:!0,get:function(){return this.ln},set:function(a){var b=this.ln;b!==a&&(E&&z(a,"number",S,"corner"),this.ln=a,this.cc(),this.g("corner",b,a))}},curve:{configurable:!0,get:function(){return this.on},set:function(a){var b=this.on;b!==a&&(E&&tb(a,S,S,"curve"),this.on=a,this.Ta(),this.cc(),np(this,b===bh||b===ah||a===bh||a===ah),this.g("curve",b,a))}},curviness:{configurable:!0,get:function(){return this.pn},set:function(a){var b=this.pn;b!==a&&(E&&z(a,"number",
S,"curviness"),this.pn=a,this.Ta(),this.cc(),this.g("curviness",b,a))}},routing:{configurable:!0,get:function(){return this.Jj},set:function(a){var b=this.Jj;b!==a&&(E&&tb(a,S,S,"routing"),this.Jj=a,this.Jf=null,this.Ta(),np(this,2===(b.value&2)||2===(a.value&2)),this.g("routing",b,a))}},smoothness:{configurable:!0,get:function(){return this.xp},set:function(a){var b=this.xp;b!==a&&(E&&z(a,"number",S,"smoothness"),this.xp=a,this.cc(),this.g("smoothness",b,a))}},key:{configurable:!0,
enumerable:!0,get:function(){var a=this.diagram;if(null!==a&&a.model.jm())return a.model.kc(this.data)}}});S.prototype.invalidateOtherJumpOvers=S.prototype.jq;S.prototype.findClosestSegment=S.prototype.Ry;S.prototype.updateRoute=S.prototype.cj;S.prototype.invalidateRoute=S.prototype.Ta;S.prototype.rollbackRoute=S.prototype.Hx;S.prototype.commitRoute=S.prototype.nf;S.prototype.startRoute=S.prototype.Eh;S.prototype.clearPoints=S.prototype.Yj;S.prototype.removePoint=S.prototype.Gv;
S.prototype.addPointAt=S.prototype.mf;S.prototype.addPoint=S.prototype.Be;S.prototype.insertPointAt=S.prototype.m;S.prototype.insertPoint=S.prototype.yz;S.prototype.setPointAt=S.prototype.N;S.prototype.setPoint=S.prototype.ld;S.prototype.getPoint=S.prototype.i;S.prototype.getOtherPort=S.prototype.nz;S.prototype.getOtherNode=S.prototype.bt;
var dp=new D(S,"Normal",1),Jp=new D(S,"Orthogonal",2),Kp=new D(S,"AvoidsNodes",6),tp=new D(S,"AvoidsNodesStraight",7),ch=new D(S,"None",0),fh=new D(S,"Bezier",9),bh=new D(S,"JumpGap",10),ah=new D(S,"JumpOver",11),ep=new D(S,"End",17),fp=new D(S,"Scale",18),gp=new D(S,"Stretch",19),Kn=new D(S,"OrientAlong",21),Tm=new D(S,"OrientPlus90",22),Vm=new D(S,"OrientMinus90",23),hp=new D(S,"OrientOpposite",24),ip=new D(S,"OrientUpright",25),Um=new D(S,"OrientPlus90Upright",26),Wm=new D(S,"OrientMinus90Upright",
27),Xm=new D(S,"OrientUpright45",28);S.className="Link";S.Normal=dp;S.Orthogonal=Jp;S.AvoidsNodes=Kp;S.AvoidsNodesStraight=tp;S.None=ch;S.Bezier=fh;S.JumpGap=bh;S.JumpOver=ah;S.End=ep;S.Scale=fp;S.Stretch=gp;S.OrientAlong=Kn;S.OrientPlus90=Tm;S.OrientMinus90=Vm;S.OrientOpposite=hp;S.OrientUpright=ip;S.OrientPlus90Upright=Um;S.OrientMinus90Upright=Wm;S.OrientUpright45=Xm;function Ip(a,b,c,d){qb(this);this.ke=this.Hr=!1;this.ot=a;this.Cx=b;this.vv=c;this.Ex=d;this.links=[]}
Ip.prototype.hm=function(){if(!this.Hr){var a=this.links;0<a.length&&(a=a[0].diagram,null!==a&&(a.Ew.add(this),this.ke=a.undoManager.isUndoingRedoing))}this.Hr=!0};Ip.prototype.ew=function(){if(this.Hr){this.Hr=!1;var a=this.links;if(0<a.length){var b=a[0],c=b.diagram;c=null===c||c.Ui&&!this.ke;this.ke=!1;b.arrangeBundledLinks(a,c);1===a.length&&(b.Af=null,a.length=0)}0===a.length&&(a=this.ot,null!==this&&null!==a.Ne&&a.Ne.remove(this),a=this.vv,null!==this&&null!==a.Ne&&a.Ne.remove(this))}};
Ip.className="LinkBundle";function zk(){qb(this);this.Qx=this.group=null;this.ft=!0;this.abort=!1;this.Md=this.Ld=1;this.qo=this.po=-1;this.mc=this.lc=8;this.Eb=[[]];this.Rj=this.Qj=0;this.iA=!1;this.cA=22;this.Gz=111}
zk.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.Ld=Math.floor((a.x-this.lc)/this.lc)*this.lc;this.Md=Math.floor((b-this.mc)/this.mc)*this.mc;this.po=Math.ceil((c+2*this.lc)/this.lc)*this.lc;this.qo=Math.ceil((d+2*this.mc)/this.mc)*this.mc;a=1+(Math.ceil((this.po-this.Ld)/this.lc)|0);b=1+(Math.ceil((this.qo-this.Md)/this.mc)|0);if(null===this.Eb||this.Qj<a-1||this.Rj<b-1){c=[];for(d=0;d<=a;d++)c[d]=[];this.Eb=c;this.Qj=a-1;this.Rj=b-1}a=
Lp;if(null!==this.Eb)for(b=0;b<=this.Qj;b++)for(c=0;c<=this.Rj;c++)this.Eb[b][c]=a}};function up(a,b,c){return a.Ld<=b&&b<=a.po&&a.Md<=c&&c<=a.qo}function wp(a,b,c){if(!up(a,b,c))return Lp;b-=a.Ld;b/=a.lc;c-=a.Md;c/=a.mc;return a.Eb[b|0][c|0]}function Ck(a,b,c){up(a,b,c)&&(b-=a.Ld,b/=a.lc,c-=a.Md,c/=a.mc,a.Eb[b|0][c|0]=yp)}function Bk(a){if(null!==a.Eb)for(var b=0;b<=a.Qj;b++)for(var c=0;c<=a.Rj;c++)a.Eb[b][c]>=Ap&&(a.Eb[b][c]=Lp)}
zk.prototype.jk=function(a,b,c,d){if(a>this.po||a+c<this.Ld||b>this.qo||b+d<this.Md)return!0;a=(a-this.Ld)/this.lc|0;b=(b-this.Md)/this.mc|0;c=Math.max(0,c)/this.lc+1|0;var e=Math.max(0,d)/this.mc+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.Qj)|0;for(c=Math.min(b+e-1,this.Rj)|0;a<=d;a++)for(e=b;e<=c;e++)if(this.Eb[a][e]===yp)return!1;return!0};
function Mp(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.Eb[l][m];if(n>=Ap&&n<xp)for(e?m+=d:l+=d,n+=1;f<=l&&l<=g&&h<=m&&m<=k&&!(n>=a.Eb[l][m]);)a.Eb[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)Mp(a,b,c,1,!e,f,g,h,k),Mp(a,b,c,-1,!e,f,g,h,k);else for(c+=d;c>l;c+=d)Mp(a,b,c,1,!e,f,g,h,k),Mp(a,b,c,-1,!e,f,g,h,k);else if(0<d)for(b+=d;b<l;b+=d)Mp(a,b,c,1,!e,f,g,h,k),Mp(a,b,c,-1,!e,f,g,h,k);else for(b+=d;b>l;b+=d)Mp(a,b,c,1,!e,f,g,h,k),Mp(a,b,c,-1,!e,f,g,h,
k)}}function Np(a,b,c,d,e,f,g,h,k){b|=0;c|=0;var l=yp,m=Ap;for(a.Eb[b][c]=m;l===yp&&b>f&&b<g&&c>h&&c<k;)m+=1,a.Eb[b][c]=m,e?c+=d:b+=d,l=a.Eb[b][c]}function Op(a,b,c,d,e,f,g,h,k){b|=0;c|=0;var l=yp,m=xp;for(a.Eb[b][c]=m;l===yp&&b>f&&b<g&&c>h&&c<k;)a.Eb[b][c]=m,e?c+=d:b+=d,l=a.Eb[b][c]}
function vp(a,b,c,d,e,f){if(null!==a.Eb){a.abort=!1;var g=b.x,h=b.y;if(up(a,g,h)&&(g-=a.Ld,g/=a.lc,h-=a.Md,h/=a.mc,b=d.x,d=d.y,up(a,b,d)))if(b-=a.Ld,b/=a.lc,d-=a.Md,d/=a.mc,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.Ld;k/=a.lc;l-=a.Md;l/=a.mc;m-=a.Ld;m/=a.lc;n-=a.Md;n/=a.mc;f=Math.max(0,Math.min(a.Qj,k|0));m=Math.min(a.Qj,Math.max(0,m|0));l=Math.max(0,Math.min(a.Rj,l|0));n=Math.min(a.Rj,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.Eb[g][h]===yp?(Np(a,g,h,k,c,f,m,l,n),Np(a,g,h,1,!c,f,m,l,n),Np(a,g,h,-1,!c,f,m,l,n)):Np(a,g,h,k,c,g,h,g,h);a.Eb[b][d]===yp?(Op(a,b,d,0===e||90===e?1:-1,90===e||270===e,f,m,l,n),Op(a,b,d,1,!(90===e||270===e),f,m,l,n),Op(a,b,d,-1,!(90===e||270===e),f,m,l,n)):Op(a,b,d,k,c,b,d,b,d);a.abort||(Mp(a,g,h,1,!1,f,m,l,n),Mp(a,g,h,-1,!1,f,m,l,n),Mp(a,g,h,1,!0,f,m,l,n),Mp(a,g,h,-1,!0,f,m,l,n))}}}
na.Object.defineProperties(zk.prototype,{bounds:{configurable:!0,get:function(){return new L(this.Ld,this.Md,this.po-this.Ld,this.qo-this.Md)}},Zl:{configurable:!0,get:function(){return this.lc},set:function(a){0<a&&a!==this.lc&&(this.lc=a,this.initialize(this.bounds))}},Yl:{configurable:!0,get:function(){return this.mc},set:function(a){0<a&&a!==this.mc&&(this.mc=a,this.initialize(this.bounds))}}});var yp=0,Ap=1,xp=999999,Lp=xp+1;zk.className="PositionArray";
function rp(){qb(this);this.port=this.node=null;this.Yd=[];this.pq=!1}rp.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 Pp(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}rp.prototype.hm=function(){this.Yd.length=0};
function sp(a,b){var c=a.Yd;if(0===c.length){a:if(!a.pq){c=a.pq;a.pq=!0;var d=null,e=a.node;e=e instanceof xg?e:null;if(null===e||e.isSubGraphExpanded)var f=a.node.dv(a.port.portId);else{if(!e.actualBounds.o()){a.pq=c;break a}d=e;f=d.cv()}var g=a.Yd.length=0,h=a.port.oa(fd,J.alloc()),k=a.port.oa(ud,J.alloc());e=L.allocAt(h.x,h.y,0,0);e.Le(k);J.free(h);J.free(k);h=J.allocAt(e.x+e.width/2,e.y+e.height/2);k=a.port.Oi();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.Xd(d),n=l.computeSpot(m,a.port);if(n.tf()&&(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.Xa(m);p-=k;0>p&&(p+=360);n=Pp(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 Qp(l,p,n),a.Yd[g]=q):(q.link=l,q.angle=p,q.Ac=n);q.zv.set(m);g++}}}}J.free(h);a.Yd.sort(rp.prototype.l);k=a.Yd.length;d=-1;for(g=
h=0;g<k;g++)f=a.Yd[g],void 0!==f&&(f.Ac!==d&&(d=f.Ac,h=0),f.gq=h,h++);d=-1;h=0;for(g=k-1;0<=g;g--)k=a.Yd[g],void 0!==k&&(k.Ac!==d&&(d=k.Ac,h=k.gq+1),k.am=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(fd,h);n.oa(hd,k);n.oa(ud,f);n.oa(sd,l);q=p=m=n=0;if(d===ap)for(var r=0;r<g.length;r++){var u=g[r];if(null!==u){var x=u.link.computeThickness();switch(u.Ac){case 8:p+=x;break;case 2:q+=x;break;case 1:n+=x;break;default:case 4:m+=x}}}var y=r=0,A=1,C=u=0;
for(x=0;x<g.length;x++){var G=g[x];if(null!==G){if(r!==G.Ac){r=G.Ac;switch(r){case 8:var I=f;y=l;break;case 2:I=l;y=h;break;case 1:I=h;y=k;break;default:case 4:I=k,y=f}u=y.x-I.x;C=y.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(C)?(A=Math.abs(C)/q,q=Math.abs(C)):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(C)?(A=Math.abs(C)/m,m=Math.abs(C)):A=1}y=0}var O=G.nq;if(d===ap){G=G.link.computeThickness();
G*=A;O.set(I);switch(r){case 8:O.x=I.x+u/2+p/2-y-G/2;break;case 2:O.y=I.y+C/2+q/2-y-G/2;break;case 1:O.x=I.x+u/2-n/2+y+G/2;break;default:case 4:O.y=I.y+C/2-m/2+y+G/2}y+=G}else{var R=.5;d===Oo&&(R=(G.gq+1)/(G.am+1));O.x=I.x+u*R;O.y=I.y+C*R}}}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.av=a.computeEndSegmentLength(d));a.pq=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}
rp.prototype.l=function(a,b){return a===b?0:null===a?-1:null===b?1:a.Ac<b.Ac?-1:a.Ac>b.Ac?1:a.angle<b.angle?-1:a.angle>b.angle?1:0};rp.prototype.computeEndSegmentLength=function(a){var b=a.link,c=b.computeEndSegmentLength(this.node,this.port,ed,b.fromPort===this.port),d=a.gq;if(0>d)return c;var e=a.am;if(1>=e||!b.isOrthogonal)return c;b=a.zv;var f=a.nq;if(2===a.Ac||8===a.Ac)d=e-1-d;return((a=2===a.Ac||4===a.Ac)?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)};rp.className="Knot";
function Qp(a,b,c){this.link=a;this.angle=b;this.Ac=c;this.zv=new J;this.am=this.gq=0;this.nq=new J;this.av=0}Qp.prototype.toString=function(){return this.link.toString()+" "+this.angle.toString()+" "+this.Ac.toString()+":"+this.gq.toString()+"/"+this.am.toString()+" "+this.nq.toString()+" "+this.av.toString()+" "+this.zv.toString()};Qp.className="LinkInfo";function il(){this.oh=this.Pg=Qd;this.nh=this.Og=this.mh=this.Ng=NaN;this.Gp=this.Hn=null;this.Hp=this.In=Infinity}
il.prototype.copy=function(){var a=new il;a.Pg=this.Pg.J();a.oh=this.oh.J();a.Ng=this.Ng;a.mh=this.mh;a.Og=this.Og;a.nh=this.nh;a.Hn=this.Hn;a.Gp=this.Gp;a.In=this.In;a.Hp=this.Hp;return a};il.className="LinkSettings";function Ni(){0<arguments.length&&Da(Ni);qb(this);this.L=this.D=null;this.Tg=this.Wn=!0;this.bo=!1;this.Um=(new J(0,0)).freeze();this.Zn=!0;this.Yn=null;this.yw="";this.w=null;this.ao=!1;this.l=null}
Ni.prototype.cloneProtected=function(a){a.Wn=this.Wn;a.Tg=this.Tg;a.bo=this.bo;a.Um.assign(this.Um);a.Zn=this.Zn;a.Yn=this.Yn;a.yw=this.yw;a.ao=!0};Ni.prototype.copy=function(){var a=new this.constructor;this.cloneProtected(a);return a};Ni.prototype.hb=function(a){Fa(this,a)};Ni.prototype.toString=function(){var a=Va(this.constructor);a+="(";null!==this.group&&(a+=" in "+this.group);null!==this.diagram&&(a+=" for "+this.diagram);return a+")"};
Ni.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.xd(),this.isOngoing&&a.Ui||this.isInitial&&!a.Ui)&&(this.isValidLayout=!1,a.ec())}}};Ni.prototype.createNetwork=function(){return new Rp(this)};Ni.prototype.makeNetwork=function(a){var b=this.createNetwork();a instanceof P?(b.ng(a.nodes,!0),b.ng(a.links,!0)):a instanceof xg?b.ng(a.memberParts):b.ng(a.iterator);return b};
Ni.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.ab("Layout")}};Ni.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()}};
Ni.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?(Sp(this,b,a.nodes,!0,this.sk,!0,!1,!0),Sp(this,b,a.parts,!0,this.sk,!0,!1,!0)):a instanceof xg?Sp(this,b,a.memberParts,!1,this.sk,!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;Tp(k);var l=k.measuredBounds,m=l.width;l=l.height;k.moveTo(e,f);k instanceof xg&&(k.sk=!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.ab("Layout")}this.isValidLayout=!0};Ni.prototype.sk=function(a){return!a.location.o()||a instanceof xg&&a.sk?!0:!1};
function Sp(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 xg?null===k.layout?Sp(a,b,k.memberParts,!1,e,f,g,h):(Tp(k),b.add(k)):(Tp(k),b.add(k))):g&&k instanceof S?b.add(k):!h||!k.dc()||k instanceof V||(Tp(k),b.add(k)))}}function Tp(a){var b=a.actualBounds;(0===b.width||0===b.height||isNaN(b.width)||isNaN(b.height))&&a.bc()}
Ni.prototype.Qi=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};Ni.prototype.ax=function(a){var b=new H;a instanceof P?(Sp(this,b,a.nodes,!0,null,!0,!0,!0),Sp(this,b,a.links,!0,null,!0,!0,!0),Sp(this,b,a.parts,!0,null,!0,!0,!0)):a instanceof xg?Sp(this,b,a.memberParts,!1,null,!0,!0,!0):Sp(this,b,a.iterator,!1,null,!0,!0,!0);return b};
Ni.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(fd),(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(Ni.prototype,{diagram:{configurable:!0,get:function(){return this.D},set:function(a){null!==a&&w(a,P,Ni,"diagram");this.D=a}},group:{configurable:!0,get:function(){return this.L},set:function(a){this.L!==a&&(null!==a&&w(a,xg,Ni,"group"),this.L=a,null!==a&&(this.D=a.diagram))}},isOngoing:{configurable:!0,get:function(){return this.Wn},set:function(a){this.Wn!==a&&(z(a,"boolean",Ni,"isOngoing"),this.Wn=a)}},isInitial:{configurable:!0,
enumerable:!0,get:function(){return this.Tg},set:function(a){z(a,"boolean",Ni,"isInitial");this.Tg=a;a||(this.ao=!0)}},isViewportSized:{configurable:!0,get:function(){return this.bo},set:function(a){this.bo!==a&&(z(a,"boolean",Ni,"isViewportSized"),(this.bo=a)&&this.C())}},isRouting:{configurable:!0,get:function(){return this.Zn},set:function(a){this.Zn!==a&&(z(a,"boolean",Ni,"isRouting"),this.Zn=a)}},isRealtime:{configurable:!0,get:function(){return this.Yn},
set:function(a){this.Yn!==a&&(null!==a&&z(a,"boolean",Ni,"isRealtime"),this.Yn=a)}},isValidLayout:{configurable:!0,get:function(){return this.ao},set:function(a){this.ao!==a&&(z(a,"boolean",Ni,"isValidLayout"),this.ao=a,a||(a=this.diagram,null!==a&&(a.Dg=!0)))}},network:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(null!==a&&w(a,Rp,Ni,"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",Ni,"boundsComputation"),this.w=a,this.C())}},arrangementOrigin:{configurable:!0,get:function(){return this.Um},set:function(a){w(a,J,Ni,"arrangementOrigin");this.Um.A(a)||(this.Um.assign(a),this.C())}}});Ni.prototype.collectParts=Ni.prototype.ax;Ni.prototype.getLayoutBounds=Ni.prototype.Qi;Ni.prototype.invalidateLayout=Ni.prototype.C;Ni.className="Layout";
function Rp(a){qb(this);E&&!a&&v("LayoutNetwork constructor requires non-null Layout argument");this.ic=a;this.kf=new H;this.ge=new H;this.pt=new Ub;this.kt=new Ub}Rp.prototype.clear=function(){if(this.kf)for(var a=this.kf.iterator;a.next();)a.value.clear();if(this.ge)for(a=this.ge.iterator;a.next();)a.value.clear();this.kf=new H;this.ge=new H;this.pt=new Ub;this.kt=new Ub};
Rp.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.kf.count+" edges: "+this.ge.count;if(1<a){for(var c=this.kf.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};Rp.prototype.createVertex=function(){return new Up(this)};Rp.prototype.createEdge=function(){return new Vp(this)};
Rp.prototype.ng=function(a,b,c){if(null!==a){void 0===b&&(b=!1);z(b,"boolean",Rp,"addParts:toplevelonly");void 0===c&&(c=null);null===c&&(c=function(a){if(a instanceof V)return!a.isLinkLabel;if(a instanceof S){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 xg&&null===d.layout)this.ng(d.memberParts,!1);else if(null===this.Ni(d)){var e=
this.createVertex();e.node=d;this.uh(e)}}for(a.reset();a.next();)if(d=a.value,d instanceof S&&(!b||d.isTopLevel)&&d.canLayout()&&c(d)&&null===this.$p(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.kk(f,e,d))}}};
Rp.prototype.findGroupVertex=function(a){if(null===a)return null;var b=a.findVisibleNode();if(null===b)return null;a=this.Ni(b);if(null!==a)return a;for(b=b.containingGroup;null!==b;){a=this.Ni(b);if(null!==a)return a;b=b.containingGroup}return null};t=Rp.prototype;t.uh=function(a){if(null!==a){E&&w(a,Up,Rp,"addVertex:vertex");this.kf.add(a);var b=a.node;null!==b&&this.pt.add(b,a);a.network=this}};
t.Wl=function(a){if(null===a)return null;E&&w(a,V,Rp,"addNode:node");var b=this.Ni(a);null===b&&(b=this.createVertex(),b.node=a,this.uh(b));return b};t.Yu=function(a){if(null!==a&&(E&&w(a,Up,Rp,"deleteVertex:vertex"),Wp(this,a))){for(var b=a.xg,c=b.count-1;0<=c;c--){var d=b.O(c);this.dk(d)}b=a.og;for(a=b.count-1;0<=a;a--)c=b.O(a),this.dk(c)}};function Wp(a,b){if(null===b)return!1;var c=a.kf.remove(b);c&&a.pt.remove(b.node);return c}
t.Hy=function(a){null!==a&&(E&&w(a,V,Rp,"deleteNode:node"),a=this.Ni(a),null!==a&&this.Yu(a))};t.Ni=function(a){if(null===a)return null;E&&w(a,V,Rp,"findVertex:node");return this.pt.K(a)};t.Tj=function(a){if(null!==a){E&&w(a,Vp,Rp,"addEdge:edge");this.ge.add(a);var b=a.link;null!==b&&null===this.$p(b)&&this.kt.add(b,a);b=a.toVertex;null!==b&&b.Mu(a);b=a.fromVertex;null!==b&&b.Ku(a);a.network=this}};
t.my=function(a){if(null===a)return null;E&&w(a,S,Rp,"addLink:link");var b=a.fromNode,c=a.toNode,d=this.$p(a);null===d?(d=this.createEdge(),d.link=a,null!==b&&(d.fromVertex=this.Wl(b)),null!==c&&(d.toVertex=this.Wl(c)),this.Tj(d)):(null!==b?d.fromVertex=this.Wl(b):d.fromVertex=null,null!==c?d.toVertex=this.Wl(c):d.toVertex=null);return d};t.dk=function(a){if(null!==a){E&&w(a,Vp,Rp,"deleteEdge:edge");var b=a.toVertex;null!==b&&b.Xu(a);b=a.fromVertex;null!==b&&b.Wu(a);Xp(this,a)}};
function Xp(a,b){null!==b&&a.ge.remove(b)&&a.kt.remove(b.link)}t.Gy=function(a){null!==a&&(E&&w(a,S,Rp,"deleteLink:link"),a=this.$p(a),null!==a&&this.dk(a))};t.$p=function(a){if(null===a)return null;E&&w(a,S,Rp,"findEdge:link");return this.kt.K(a)};
t.kk=function(a,b,c){if(null===a||null===b)return null;E&&(w(a,Up,Rp,"linkVertexes:fromVertex"),w(b,Up,Rp,"linkVertexes:toVertex"),null!==c&&w(c,S,Rp,"linkVertexes:link"));if(a.network===this&&b.network===this){var d=this.createEdge();d.link=c;d.fromVertex=a;d.toVertex=b;this.Tj(d);return d}return null};t.ym=function(a){if(null!==a){E&&w(a,Vp,Rp,"reverseEdge:edge");var b=a.fromVertex,c=a.toVertex;null!==b&&null!==c&&(b.Wu(a),c.Xu(a),a.ym(),b.Mu(a),c.Ku(a))}};
t.Xp=function(){for(var a=Qa(),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.dk(a[c]);Ta(a)};Rp.prototype.deleteArtificialVertexes=function(){for(var a=Qa(),b=this.kf.iterator;b.next();){var c=b.value;null===c.node&&a.push(c)}c=a.length;for(b=0;b<c;b++)this.Yu(a[b]);b=Qa();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.dk(b[d]);Ta(a);Ta(b)};
function Yp(a){for(var b=Qa(),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.dk(b[d]);Ta(b)}
Rp.prototype.Rx=function(){this.deleteArtificialVertexes();Yp(this);this.Xp();for(var a=new F,b=!0;b;){b=!1;for(var c=this.kf.iterator;c.next();){var d=c.value;if(0<d.xg.count||0<d.og.count){b=this.layout.createNetwork();a.add(b);Zp(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 Zp(a,b,c){if(null!==c&&c.network!==b){Wp(a,c);b.uh(c);for(var d=c.sourceEdges;d.next();){var e=d.value;e.network!==b&&(Xp(a,e),b.Tj(e),Zp(a,b,e.fromVertex))}for(d=c.destinationEdges;d.next();)c=d.value,c.network!==b&&(Xp(a,c),b.Tj(c),Zp(a,b,c.toVertex))}}Rp.prototype.Qy=function(){for(var a=new H,b=this.kf.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(Rp.prototype,{layout:{configurable:!0,get:function(){return this.ic},set:function(a){null!==a&&(this.ic=a)}},vertexes:{configurable:!0,get:function(){return this.kf}},edges:{configurable:!0,get:function(){return this.ge}}});Rp.prototype.findAllParts=Rp.prototype.Qy;Rp.prototype.splitIntoSubNetworks=Rp.prototype.Rx;Rp.prototype.deleteSelfEdges=Rp.prototype.Xp;Rp.prototype.reverseEdge=Rp.prototype.ym;Rp.prototype.linkVertexes=Rp.prototype.kk;
Rp.prototype.findEdge=Rp.prototype.$p;Rp.prototype.deleteLink=Rp.prototype.Gy;Rp.prototype.deleteEdge=Rp.prototype.dk;Rp.prototype.addLink=Rp.prototype.my;Rp.prototype.addEdge=Rp.prototype.Tj;Rp.prototype.findVertex=Rp.prototype.Ni;Rp.prototype.deleteNode=Rp.prototype.Hy;Rp.prototype.deleteVertex=Rp.prototype.Yu;Rp.prototype.addNode=Rp.prototype.Wl;Rp.prototype.addVertex=Rp.prototype.uh;Rp.prototype.addParts=Rp.prototype.ng;Rp.className="LayoutNetwork";
function Up(a){qb(this);E&&!a&&v("LayoutVertex constructor requires non-null LayoutNetwork argument");this.Oc=a;this.l=(new L(0,0,10,10)).freeze();this.w=(new J(5,5)).freeze();this.ni=this.kb=null;this.xg=new F;this.og=new F}Up.prototype.clear=function(){this.ni=this.kb=null;this.xg=new F;this.og=new F};
Up.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutVertex#"+Jb(this);if(0<a&&(b+=null!==this.node?"("+this.node.toString()+")":"",1<a)){a="";for(var c=!0,d=this.xg.iterator;d.next();){var e=d.value;c?c=!1:a+=",";a+=e.toString(0)}e="";c=!0;for(d=this.og.iterator;d.next();){var f=d.value;c?c=!1:e+=",";e+=f.toString(0)}b+=" sources: "+a+" destinations: "+e}return b};
Up.prototype.commit=function(){var a=this.kb;if(null!==a){var b=this.bounds,c=a.bounds;Ja(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 xg)){c=L.alloc();var d=this.network.layout.Qi(a,c),e=a.locationObject.oa(qd);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)}};
Up.prototype.Mu=function(a){null!==a&&(E&&w(a,Vp,Up,"addSourceEdge:edge"),this.xg.contains(a)||this.xg.add(a))};Up.prototype.Xu=function(a){null!==a&&(E&&w(a,Vp,Up,"deleteSourceEdge:edge"),this.xg.remove(a))};Up.prototype.Ku=function(a){null!==a&&(E&&w(a,Vp,Up,"addDestinationEdge:edge"),this.og.contains(a)||this.og.add(a))};Up.prototype.Wu=function(a){null!==a&&(E&&w(a,Vp,Up,"deleteDestinationEdge:edge"),this.og.remove(a))};
function $p(a,b){E&&w(a,Up,Up,"standardComparer:m");E&&w(b,Up,Up,"standardComparer:n");a=a.ni;b=b.ni;return a?b?(a=a.text,b=b.text,a<b?-1:a>b?1:0):1:null!==b?-1:0}
na.Object.defineProperties(Up.prototype,{sourceEdgesArrayAccess:{configurable:!0,get:function(){return this.xg._dataArray}},destinationEdgesArrayAccess:{configurable:!0,get:function(){return this.og._dataArray}},data:{configurable:!0,get:function(){return this.kb},set:function(a){this.kb=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.ni},
set:function(a){if(this.ni!==a){E&&null!==a&&w(a,V,Up,"node");this.ni=a;a.bc();var b=this.network.layout,c=L.alloc(),d=b.Qi(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 xg)&&(a=a.locationObject.oa(qd),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,Up,"bounds"),this.l.assign(a))}},focus:{configurable:!0,
get:function(){return this.w},set:function(a){this.w.A(a)||(E&&w(a,J,Up,"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&&B(a,Up,"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&&B(a,Up,"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.Oc},set:function(a){E&&w(a,Rp,Up,"network");this.Oc=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.xg.iterator}},destinationEdges:{configurable:!0,
enumerable:!0,get:function(){return this.og.iterator}},edges:{configurable:!0,get:function(){for(var a=new F,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.xg.count+this.og.count}}});Up.prototype.deleteDestinationEdge=Up.prototype.Wu;Up.prototype.addDestinationEdge=Up.prototype.Ku;Up.prototype.deleteSourceEdge=Up.prototype.Xu;
Up.prototype.addSourceEdge=Up.prototype.Mu;Up.className="LayoutVertex";Up.standardComparer=$p;
Up.smartComparer=function(a,b){E&&w(a,Up,Up,"smartComparer:m");E&&w(b,Up,Up,"smartComparer:n");if(null!==a){if(null!==b){a=a.ni;var c=b.ni;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 Vp(a){qb(this);E&&!a&&v("LayoutEdge constructor requires non-null LayoutNetwork argument");this.Xb=a;this.ig=this.Lf=this.rl=this.kb=null}Vp.prototype.clear=function(){this.ig=this.Lf=this.rl=this.kb=null};
Vp.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutEdge#"+Jb(this);0<a&&(b+=null!==this.rl?"("+this.rl.toString()+")":"",1<a&&(b+=" "+(this.Lf?this.Lf.toString():"null")+" --\x3e "+(this.ig?this.ig.toString():"null")));return b};Vp.prototype.ym=function(){var a=this.Lf;this.Lf=this.ig;this.ig=a};Vp.prototype.commit=function(){};Vp.prototype.sx=function(a){E&&w(a,Up,Vp,"getOtherVertex:v");return this.ig===a?this.Lf:this.Lf===a?this.ig:null};
na.Object.defineProperties(Vp.prototype,{network:{configurable:!0,get:function(){return this.Xb},set:function(a){E&&w(a,Rp,Vp,"network");this.Xb=a}},data:{configurable:!0,get:function(){return this.kb},set:function(a){this.kb!==a&&(E&&null!==a&&z(a,"object",Vp,"data"),this.kb=a)}},link:{configurable:!0,get:function(){return this.rl},set:function(a){this.rl!==a&&(E&&null!==a&&w(a,S,Vp,"link"),this.rl=a)}},fromVertex:{configurable:!0,get:function(){return this.Lf},
set:function(a){this.Lf!==a&&(E&&null!==a&&w(a,Up,Vp,"network"),this.Lf=a)}},toVertex:{configurable:!0,get:function(){return this.ig},set:function(a){this.ig!==a&&(E&&null!==a&&w(a,Up,Vp,"network"),this.ig=a)}}});Vp.prototype.getOtherVertex=Vp.prototype.sx;Vp.className="LayoutEdge";
function Rk(){0<arguments.length&&Da(Rk);Ni.call(this);this.isViewportSized=!0;this.Np=this.Op=NaN;this.Fg=(new Zb(NaN,NaN)).freeze();this.bf=(new Zb(10,10)).freeze();this.xb=aq;this.Db=bq;this.Tc=cq;this.Pc=dq}ma(Rk,Ni);Rk.prototype.cloneProtected=function(a){Ni.prototype.cloneProtected.call(this,a);a.Op=this.Op;a.Np=this.Np;a.Fg.assign(this.Fg);a.bf.assign(this.bf);a.xb=this.xb;a.Db=this.Db;a.Tc=this.Tc;a.Pc=this.Pc};
Rk.prototype.hb=function(a){a.classType===Rk?a===cq||a===eq||a===fq||a===gq?this.sorting=a:a===bq||a===hq?this.arrangement=a:a===aq||a===iq?this.alignment=a:v("Unknown enum value: "+a):Ni.prototype.hb.call(this,a)};
Rk.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.ax(a);a=this.diagram;for(var c=b.copy().iterator;c.next();){var d=c.value;if(!d.Bh()||null===d.fromNode&&null===d.toNode){if(d.bc(),d instanceof xg)for(d=d.memberParts;d.next();)b.remove(d.value)}else b.remove(d)}var e=b.Oa();if(0!==e.length){switch(this.sorting){case gq:e.reverse();
break;case cq:e.sort(this.comparer);break;case eq: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 iq: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.Qi(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.Qi(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,x=0,y=0,A=0;A<e.length;A++){var C=e[A],G=this.Qi(C,l),I=Math.ceil((G.width+h)/m)*m,O=Math.ceil((G.height+k)/n)*n;switch(p){case hq:var R=Math.abs(r-G.width);break;default:R=r+G.width}if(0<f&&x>f-1||
0<g&&0<x&&R-q>g)d.push(new L(0,u,g+h,y)),x=0,r=q,u+=y,y=0;y=Math.max(y,O);switch(p){case hq:G=-G.width;break;default:G=0}C.moveTo(r+G,u);switch(p){case hq:r-=I;break;default:r+=I}x++}d.push(new L(0,u,g+h,y));L.free(l);break;case aq: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++)y=e[r],x=this.Qi(y,g),y=y.rf(y.locationObject,y.locationSpot,h),l=Math.max(l,y.x),u=Math.max(u,x.width-y.x),f=Math.max(f,y.y);r=this.arrangement;switch(r){case hq:l+=
n;break;default:u+=n}q=isFinite(q)?Math.max(q+n,1):Math.max(l+u,1);var U=y=this.arrangementOrigin.x;A=this.arrangementOrigin.y;u=0;k>=l&&(k-=l);l=C=0;I=Math.max(this.cellSize.height,1);G=f=0;O=!0;x=J.alloc();for(R=0;R<e.length;R++){var ea=e[R],Z=this.Qi(ea,g),qa=ea.rf(ea.locationObject,ea.locationSpot,h);if(0<u)switch(r){case hq:U=(U-y-(Z.width-qa.x))/q;U=K.da(Math.round(U),U)?Math.round(U):Math.floor(U);U=U*q+y;break;default:U=(U-y+qa.x)/q,U=K.da(Math.round(U),U)?Math.round(U):Math.ceil(U),U=U*q+
y}else switch(r){case hq:C=U+qa.x+Z.width;break;default:C=U-qa.x}switch(r){case hq:var xa=-(U+qa.x)+C;break;default:xa=U+Z.width-qa.x-C}if(0<m&&u>m-1||0<k&&0<u&&xa>k){d.push(new L(0,O?A-f:A,k+n,G+f+p));for(U=0;U<u&&R!==u;U++){xa=e[R-u+U];var Q=xa.rf(xa.locationObject,xa.locationSpot,x);xa.moveTo(xa.position.x,xa.position.y+f-Q.y)}G+=p;A=O?A+G:A+(G+f);u=G=f=0;U=y;O=!1}U===y&&(l=r===hq?Math.max(l,Z.width-qa.x):Math.min(l,-qa.x));f=Math.max(f,qa.y);G=Math.max(G,Z.height-qa.y);isFinite(I)&&(G=Math.max(G,
Math.max(Z.height,I)-qa.y));O?ea.moveTo(U-qa.x,A-qa.y):ea.moveTo(U-qa.x,A);switch(r){case hq:U-=qa.x+n;break;default:U+=Z.width-qa.x+n}u++}d.push(new L(0,A,k+n,(O?G:G+f)+p));if(e.length!==u)for(k=0;k<u;k++)m=e[e.length-u+k],n=m.rf(m.locationObject,m.locationSpot,h),m.moveTo(m.position.x,m.position.y+f-n.y);J.free(h);J.free(x);if(r===hq)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===hq?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.ab("Layout");this.isValidLayout=!0}};Rk.prototype.commitLayers=function(){};function dq(a,b){E&&w(a,T,Rk,"standardComparer:a");E&&w(b,T,Rk,"standardComparer:b");a=a.text;b=b.text;return a<b?-1:a>b?1:0}
na.Object.defineProperties(Rk.prototype,{wrappingWidth:{configurable:!0,get:function(){return this.Op},set:function(a){this.Op!==a&&(z(a,"number",Rk,"wrappingWidth"),0<a||isNaN(a))&&(this.Op=a,this.isViewportSized=isNaN(a),this.C())}},wrappingColumn:{configurable:!0,get:function(){return this.Np},set:function(a){this.Np!==a&&(z(a,"number",Rk,"wrappingColumn"),0<a||isNaN(a))&&(this.Np=a,this.C())}},cellSize:{configurable:!0,get:function(){return this.Fg},set:function(a){w(a,
Zb,Rk,"cellSize");this.Fg.A(a)||(this.Fg.assign(a),this.C())}},spacing:{configurable:!0,get:function(){return this.bf},set:function(a){w(a,Zb,Rk,"spacing");this.bf.A(a)||(this.bf.assign(a),this.C())}},alignment:{configurable:!0,get:function(){return this.xb},set:function(a){this.xb!==a&&(tb(a,Rk,Rk,"alignment"),a===aq||a===iq)&&(this.xb=a,this.C())}},arrangement:{configurable:!0,get:function(){return this.Db},set:function(a){this.Db!==a&&(tb(a,Rk,Rk,"arrangement"),
a===bq||a===hq)&&(this.Db=a,this.C())}},sorting:{configurable:!0,get:function(){return this.Tc},set:function(a){this.Tc!==a&&(tb(a,Rk,Rk,"sorting"),a===fq||a===gq||a===cq||a===eq)&&(this.Tc=a,this.C())}},comparer:{configurable:!0,get:function(){return this.Pc},set:function(a){this.Pc!==a&&(z(a,"function",Rk,"comparer"),this.Pc=a,this.C())}}});
var iq=new D(Rk,"Position",0),aq=new D(Rk,"Location",1),bq=new D(Rk,"LeftToRight",2),hq=new D(Rk,"RightToLeft",3),fq=new D(Rk,"Forward",4),gq=new D(Rk,"Reverse",5),cq=new D(Rk,"Ascending",6),eq=new D(Rk,"Descending",7);Rk.className="GridLayout";Rk.standardComparer=dq;
Rk.smartComparer=function(a,b){E&&w(a,T,Rk,"standardComparer:a");E&&w(b,T,Rk,"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};Rk.Position=iq;Rk.Location=aq;Rk.LeftToRight=bq;Rk.RightToLeft=hq;Rk.Forward=fq;Rk.Reverse=gq;Rk.Ascending=cq;Rk.Descending=eq;function Ii(){this.Jo=new H;this.lo=new H;this.Ga=new H;this.Oe=new Ub;this.Hg=new Ub;this.tj=new Ub;this.D=null;this.Jq=!1}t=Ii.prototype;t.clear=function(){this.Jo.clear();this.lo.clear();this.Ga.clear();this.Oe.clear();this.Hg.clear();this.tj.clear()};
t.ib=function(a){E&&null!==a&&w(a,P,Ii,"setDiagram");this.D=a};t.Si=function(a){if(a instanceof V){if(this.Jo.add(a),a instanceof xg){var b=a.containingGroup;null===b?this.D.Bi.add(a):b.wl.add(a);b=a.layout;null!==b&&(b.diagram=this.D)}}else a instanceof S?this.lo.add(a):a instanceof Cf||this.Ga.add(a);b=a.data;null===b||a instanceof Cf||(a instanceof S?this.Hg.add(b,a):this.Oe.add(b,a))};
t.zc=function(a){a.Xj();if(a instanceof V){if(this.Jo.remove(a),a instanceof xg){var b=a.containingGroup;null===b?this.D.Bi.remove(a):b.wl.remove(a);b=a.layout;null!==b&&(b.diagram=null)}}else a instanceof S?this.lo.remove(a):a instanceof Cf||this.Ga.remove(a);b=a.data;null===b||a instanceof Cf||(a instanceof S?this.Hg.remove(b):this.Oe.remove(b))};
t.wd=function(){for(var a=this.D.nodeTemplateMap.iterator;a.next();){var b=a.value,c=a.key;(!b.dc()||b instanceof xg)&&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.D.groupTemplateMap.iterator;a.next();)b=a.value,c=a.key,b instanceof xg||v('Invalid group template in Diagram.groupTemplateMap: template for "'+c+'" must be a Group, not a normal Node or Link: '+b);for(a=this.D.linkTemplateMap.iterator;a.next();)b=
a.value,c=a.key,b instanceof S||v('Invalid link template in Diagram.linkTemplateMap: template for "'+c+'" must be a Link, not a normal Node or simple Part: '+b);a=Qa();for(b=this.D.selection.iterator;b.next();)(c=b.value.data)&&a.push(c);b=Qa();for(c=this.D.highlighteds.iterator;c.next();){var d=c.value.data;d&&b.push(d)}c=Qa();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.xc(a[d]),null!==e&&(e.isSelected=!0);for(d=0;d<b.length;d++)e=this.xc(b[d]),null!==e&&(e.isHighlighted=!0);for(d=0;d<c.length;d+=2)e=this.xc(c[d]),null!==e&&(e.location=c[d+1]);Ta(a);Ta(b);Ta(c)};Ii.prototype.addAllModeledParts=function(){this.addModeledParts(this.diagram.model.nodeDataArray)};
Ii.prototype.addModeledParts=function(a,b){var c=this,d=this.diagram.model;a.forEach(function(a){d.Ab(a)&&jq(c,a,!1)});a.forEach(function(a){d.Ab(a)&&c.resolveReferencesForData(a)});!1!==b&&tk(this.diagram,!1)};
function jq(a,b,c){if(void 0!==b&&null!==b&&!a.diagram.undoManager.isUndoingRedoing&&!a.Oe.contains(b)){void 0===c&&(c=!0);a:{if(void 0!==b&&null!==b&&!a.D.undoManager.isUndoingRedoing&&!a.Oe.contains(b)){var d=a.$s(b);var e=Mo(a,b,d);if(null!==e&&(mh(e),e=e.copy(),null!==e)){var f=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;e.Bf=d;e.kb=b;a.Jq&&(e.Vg="Tool");a.diagram.add(e);e.kb=null;e.data=b;a.diagram.skipsModelSourceBindings=f;d=e;break a}}d=null}null!==d&&c&&a.resolveReferencesForData(b)}}
Ii.prototype.insertLink=function(){return null};Ii.prototype.resolveReferencesForData=function(){};Ii.prototype.$s=function(a){return this.D.model.$s(a)};
function Mo(a,b,c){a=a.D;var d=a.model;d.Ti()&&d.ht(b)?(b=a.groupTemplateMap.K(c),null===b&&(b=a.groupTemplateMap.K(""),null===b&&(kq||(kq=!0,Ha('No Group template found for category "'+c+'"'),Ha(" Using default group template")),b=a.vw))):(b=a.nodeTemplateMap.K(c),null===b&&(b=a.nodeTemplateMap.K(""),null===b&&(lq||(lq=!0,Ha('No Node template found for category "'+c+'"'),Ha(" Using default node template")),b=a.xw)));return b}Ii.prototype.getLinkCategoryForData=function(){return""};
Ii.prototype.setLinkCategoryForData=function(){};Ii.prototype.setFromNodeForLink=function(){};Ii.prototype.setToNodeForLink=function(){};Ii.prototype.findLinkTemplateForCategory=function(a){var b=this.D.linkTemplateMap.K(a);null===b&&(b=this.D.linkTemplateMap.K(""),null===b&&(mq||(mq=!0,Ha('No Link template found for category "'+a+'"'),Ha(" Using default link template")),b=this.D.ww));return b};Ii.prototype.removeAllModeledParts=function(){this.vt(this.diagram.model.nodeDataArray)};
Ii.prototype.vt=function(a){var b=this;a.forEach(function(a){b.wq(a)})};Ii.prototype.wq=function(a){a=this.xc(a);null!==a&&(Wj(this.diagram,a,!1),this.unresolveReferencesForPart(a))};Ii.prototype.unresolveReferencesForPart=function(){};Ii.prototype.removeDataForLink=function(){};Ii.prototype.findPartForKey=function(a){if(null===a||void 0===a)return null;a=this.D.model.Sb(a);return null!==a?this.Oe.K(a):null};t=Ii.prototype;
t.Kb=function(a){if(null===a||void 0===a)return null;a=this.D.model.Sb(a);if(null===a)return null;a=this.Oe.K(a);return a instanceof V?a:null};t.xc=function(a){if(null===a)return null;var b=this.Oe.K(a);return null!==b?b:b=this.Hg.K(a)};t.Ji=function(a){if(null===a)return null;a=this.Oe.K(a);return a instanceof V?a:null};t.wc=function(a){return null===a?null:this.Hg.K(a)};
t.Xs=function(a){for(var b=0;b<arguments.length;++b);b=new H;for(var c=this.Jo.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(Ja(g)&&nq(this,e,g)){b.add(d);break}}}return b.iterator};t.Ws=function(a){for(var b=0;b<arguments.length;++b);b=new H;for(var c=this.lo.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(Ja(g)&&nq(this,e,g)){b.add(d);break}}}return b.iterator};
function nq(a,b,c){for(var d in c){var e=b[d],f=c[d];if(Ka(f)){if(!Ka(e)||e.length<f.length)return!1;for(var g=0;g<e.length;g++){var h=f[g];if(void 0!==h&&!oq(a,e[g],h))return!1}}else if(!oq(a,e,f))return!1}return!0}function oq(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(Ja(b)&&Ja(c)){if(!nq(a,b,c))return!1}else if(b!==c)return!1;return!0}
Ii.prototype.doModelChanged=function(a){if(this.D){var b=this.D;if(a.model===b.model){var c=a.change;b.doModelChanged(a);if(b.fa){b.fa=!1;try{var d=a.modelChange;if(""!==d)if(c===of){if("nodeCategory"===d){var e=this.xc(a.object),f=a.newValue;null!==e&&"string"===typeof f&&(e.category=f)}else"nodeDataArray"===d&&(this.vt(a.oldValue),this.addModeledParts(a.newValue));b.isModified=!0}else if(c===qf){var g=a.newValue;"nodeDataArray"===d&&Ja(g)&&jq(this,g);b.isModified=!0}else if(c===rf){var h=a.oldValue;
"nodeDataArray"===d&&Ja(h)&&this.wq(h);b.isModified=!0}else c===pf&&("SourceChanged"===d?null!==a.object?this.updateDataBindings(a.object,a.propertyName):(this.Dq(),this.updateAllTargetBindings()):"ModelDisplaced"===d&&this.wd());else if(c===of){var k=a.propertyName,l=a.object;if(l===b.model){if("nodeKeyProperty"===k||"nodeCategoryProperty"===k)b.undoManager.isUndoingRedoing||this.wd()}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.tj.K(a.object);if(Array.isArray(q))for(a=0;a<q.length;a++){var r=q[a];if(m)sn(r,p,n);else if(!(0>n)){var u=n+kn(r);r.zc(u,!0);wn(r,u,n)}}b.isModified=!0}}finally{b.fa=!0}}}}};Ii.prototype.updateAllTargetBindings=function(a){void 0===a&&(a="");for(var b=this.parts.iterator;b.next();)b.value.Fa(a);for(b=this.nodes.iterator;b.next();)b.value.Fa(a);for(b=this.links.iterator;b.next();)b.value.Fa(a)};
Ii.prototype.Dq=function(){for(var a=this.D.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){pq(a,b,!1)});for(d=0;d<c.length;d++){var f=c[d];null===this.xc(f)&&qq(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()};Ii.prototype.refreshDataBoundLinks=function(){};Ii.prototype.updateRelationshipsFromData=function(){};
Ii.prototype.updateDataBindings=function(a,b){if("string"===typeof b){var c=this.xc(a);if(null!==c)c.Fa(b);else{c=null;for(var d=this.tj.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=Qa()),c.push(g))}if(null!==c)break}if(null!==c){for(d=0;d<c.length;d++)c[d].Fa(b);Ta(c)}}a===this.diagram.model.modelData&&this.updateAllTargetBindings(b)}};
function Sj(a,b){var c=b.hi;if(Ka(c)){var d=a.tj.K(c);if(null===d)d=[],d.push(b),a.tj.add(c,d);else{for(a=0;a<d.length;a++)if(d[a]===b)return;d.push(b)}}}function Vj(a,b,c){Qj(b,function(a){a=a.Z.j;for(var b=a.length,d=0;d<b;d++)lk(c,a[d])});var d=b.hi;if(Ka(d)){var e=a.tj.K(d);if(null!==e)for(var f=0;f<e.length;f++)if(e[f]===b){e.splice(f,1);0===e.length&&a.tj.remove(d);break}}}
Ii.prototype.bk=function(a,b,c){var d=new Ub;if(Ka(a))for(var e=0;e<a.length;e++)rq(this,a[e],b,d,c);else for(a=a.iterator;a.next();)rq(this,a.value,b,d,c);if(null!==b){c=b.model;a=b.toolManager.findTool("Dragging");a=null!==a?a.dragOptions.dragsLink:b.Qk.dragsLink;e=new H;for(var f=new Ub,g=d.iterator;g.next();){var h=g.value;if(h instanceof S)a||null!==h.fromNode&&null!==h.toNode||e.add(h);else if(h instanceof V&&null!==h.data&&c.km()){var k=h;h=g.key;var l=h.rg();null!==l&&(l=d.K(l),null!==l?(c.Ke(k.data,
c.ra(l.data)),k=b.wc(k.data),h=h.Mi(),null!==h&&null!==k&&f.add(h,k)):c.Ke(k.data,void 0))}}0<e.count&&b.wt(e,!1);if(0<f.count)for(c=f.iterator;c.next();)d.add(c.key,c.value)}if(null!==b&&null!==this.D&&(b=b.model,c=b.afterCopyFunction,null!==c)){var m=new Ub;d.each(function(a){null!==a.key.data&&m.add(a.key.data,a.value.data)});c(m,b,this.D.model)}for(b=d.iterator;b.next();)b.value.Fa();return d};
function rq(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 T))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 xg&&f instanceof xg)for(b=b.memberParts;b.next();)g=rq(a,b.value,c,d,e),g instanceof S||null===g||(g.containingGroup=
f)}else if(b instanceof S&&f instanceof S)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=rq(a,b.value,c,d,e),null!==g&&g instanceof V&&(g.labeledLink=f);return f}
Ii.prototype.copyPartData=function(a,b){var c=null,d=a.data;if(null!==d&&null!==b){var e=b.model;a instanceof S||(d=e.copyNodeData(d),Ja(d)&&(e.lf(d),c=b.xc(d)))}else mh(a),c=a.copy(),null!==c&&(e=this.D,null!==b?b.add(c):null!==d&&null!==e&&null!==e.commandHandler&&e.commandHandler.copiesClipboardData&&(b=e.model,e=null,c instanceof S||(e=b.copyNodeData(d)),Ja(e)&&(c.data=e)));return c};
na.Object.defineProperties(Ii.prototype,{nodes:{configurable:!0,get:function(){return this.Jo}},links:{configurable:!0,get:function(){return this.lo}},parts:{configurable:!0,get:function(){return this.Ga}},diagram:{configurable:!0,get:function(){return this.D}},addsToTemporaryLayer:{configurable:!0,get:function(){return this.Jq},set:function(a){z(a,"boolean",Ii,"addsToTemporaryLayer");this.Jq=a}}});
Ii.prototype.updateAllRelationshipsFromData=Ii.prototype.Dq;Ii.prototype.findLinksByExample=Ii.prototype.Ws;Ii.prototype.findNodesByExample=Ii.prototype.Xs;Ii.prototype.findLinkForData=Ii.prototype.wc;Ii.prototype.findNodeForData=Ii.prototype.Ji;Ii.prototype.findPartForData=Ii.prototype.xc;Ii.prototype.findNodeForKey=Ii.prototype.Kb;Ii.prototype.removeModeledPart=Ii.prototype.wq;Ii.prototype.removeModeledParts=Ii.prototype.vt;Ii.prototype.rebuildParts=Ii.prototype.wd;var lq=!1,kq=!1,mq=!1;
Ii.className="PartManager";function sq(a){Ii.apply(this,arguments)}ma(sq,Ii);sq.prototype.addAllModeledParts=function(){var a=this.diagram.model;this.addModeledParts(a.nodeDataArray);tq(this,a.linkDataArray)};sq.prototype.addModeledParts=function(a){Ii.prototype.addModeledParts.call(this,a,!1);for(a=this.links.iterator;a.next();)No(a.value);tk(this.diagram,!1)};function tq(a,b){b.forEach(function(b){uq(a,b)});tk(a.diagram,!1)}
function uq(a,b){if(void 0!==b&&null!==b&&!a.diagram.undoManager.isUndoingRedoing&&!a.Hg.contains(b)){var c=a.getLinkCategoryForData(b),d=a.findLinkTemplateForCategory(c);if(null!==d){mh(d);var e=d.copy();if(null!==e){d=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;e.Bf=c;e.kb=b;c=a.diagram.model;var f=vq(c,b,!0);""!==f&&(e.fromPortId=f);f=wq(c,b,!0);void 0!==f&&(f=a.Kb(f),f instanceof V&&(e.fromNode=f));f=vq(c,b,!1);""!==f&&(e.toPortId=f);f=wq(c,b,!1);void 0!==f&&(f=a.Kb(f),
f instanceof V&&(e.toNode=f));c=c.sg(b);Array.isArray(c)&&c.forEach(function(b){b=a.Kb(b);null!==b&&(b.labeledLink=e)});a.Jq&&(e.Vg="Tool");a.diagram.add(e);e.kb=null;e.data=b;a.diagram.skipsModelSourceBindings=d}}}}sq.prototype.removeAllModeledParts=function(){var a=this.diagram.model;xq(this,a.linkDataArray);this.vt(a.nodeDataArray)};function xq(a,b){b.forEach(function(b){a.wq(b)})}sq.prototype.getLinkCategoryForData=function(a){return this.diagram.model.iv(a)};
sq.prototype.setLinkCategoryForData=function(a,b){return this.diagram.model.yt(a,b)};sq.prototype.setFromNodeForLink=function(a,b){var c=this.diagram.model;c.Kx(a.data,c.ra(null!==b?b.data:null))};sq.prototype.setToNodeForLink=function(a,b){var c=this.diagram.model;c.Ox(a.data,c.ra(null!==b?b.data:null))};sq.prototype.removeDataForLink=function(a){this.diagram.model.tm(a.data)};
sq.prototype.findPartForKey=function(a){var b=Ii.prototype.findPartForKey.call(this,a);return null===b&&(a=this.diagram.model.yh(a),null!==a)?this.Hg.K(a):b};
sq.prototype.doModelChanged=function(a){var b=this;Ii.prototype.doModelChanged.call(this,a);if(this.diagram){var c=this.diagram;if(a.model===c.model){var d=a.change;if(c.fa){c.fa=!1;try{var e=a.modelChange;if(""!==e)if(d===of){if("linkFromKey"===e){var f=this.wc(a.object);if(null!==f){var g=this.Kb(a.newValue);f.fromNode=g}}else if("linkToKey"===e){var h=this.wc(a.object);if(null!==h){var k=this.Kb(a.newValue);h.toNode=k}}else if("linkFromPortId"===e){var l=this.wc(a.object);if(null!==l){var m=a.newValue;
"string"===typeof m&&(l.fromPortId=m)}}else if("linkToPortId"===e){var n=this.wc(a.object);if(null!==n){var p=a.newValue;"string"===typeof p&&(n.toPortId=p)}}else if("nodeGroupKey"===e){var q=this.xc(a.object);if(null!==q){var r=a.newValue;if(void 0!==r){var u=this.Kb(r);u instanceof xg?q.containingGroup=u:q.containingGroup=null}else q.containingGroup=null}}else if("linkLabelKeys"===e){var x=this.wc(a.object);if(null!==x){var y=a.oldValue,A=a.newValue;Array.isArray(y)&&y.forEach(function(a){a=b.Kb(a);
null!==a&&(a.labeledLink=null)});Array.isArray(A)&&A.forEach(function(a){a=b.Kb(a);null!==a&&(a.labeledLink=x)})}}else if("linkCategory"===e){var C=this.wc(a.object),G=a.newValue;null!==C&&"string"===typeof G&&(C.category=G)}else"linkDataArray"===e&&(xq(this,a.oldValue),tq(this,a.newValue));c.isModified=!0}else if(d===qf){var I=a.newValue;if("linkDataArray"===e&&"object"===typeof I&&null!==I)uq(this,I);else if("linkLabelKeys"===e&&yq(I)){var O=this.wc(a.object),R=this.Kb(I);null!==O&&null!==R&&(R.labeledLink=
O)}c.isModified=!0}else{if(d===rf){var U=a.oldValue;if("linkDataArray"===e&&"object"===typeof U&&null!==U)this.wq(U);else if("linkLabelKeys"===e&&yq(U)){var ea=this.Kb(U);null!==ea&&(ea.labeledLink=null)}c.isModified=!0}}else if(d===of){var Z=a.propertyName,qa=a.object;if(qa===c.model){if("linkFromKeyProperty"===Z||"linkToKeyProperty"===Z||"linkFromPortIdProperty"===Z||"linkToPortIdProperty"===Z||"linkLabelKeysProperty"===Z||"nodeIsGroupProperty"===Z||"nodeGroupKeyProperty"===Z||"linkCategoryProperty"===
Z)c.undoManager.isUndoingRedoing||this.wd()}else this.updateDataBindings(qa,Z);c.isModified=!0}}finally{c.fa=!0}}}}};sq.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){zq(b,a,!1)});d.forEach(function(c){null===a.wc(c)&&Aq(b,c,!1)})};
sq.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 S){var e=wq(d,b,!0);e=c.Kb(e);a.fromNode=e;e=wq(d,b,!1);e=c.Kb(e);a.toNode=e;b=d.sg(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.ra(f.data)===e)return}e=(new H).addAll(b);var g=new H;a.labelNodes.each(function(a){null!==a.data&&(a=d.ra(a.data),void 0!==a&&g.add(a))});b=g.copy();b.vq(e);e=
e.copy();e.vq(g);if(0<b.count||0<e.count)b.each(function(b){b=c.Kb(b);null!==b&&b.labeledLink===a&&(b.labeledLink=null)}),e.each(function(b){b=c.Kb(b);null!==b&&b.labeledLink!==a&&(b.labeledLink=a)})}}else!(a instanceof Cf)&&(b=d.Pi(b),b=c.findPartForKey(b),null===b||b instanceof xg)&&(a.containingGroup=b)}}};
sq.prototype.resolveReferencesForData=function(a){var b=this.diagram.model,c=b.ra(a);if(void 0!==c){var d=Bq(b,c),e=this.xc(a);if(null!==d&&null!==e){d=d.iterator;for(var f={};d.next();){var g=d.value;b.Ab(g)?e instanceof xg&&b.Pi(g)===c&&(g=this.xc(g),null!==g&&(g.containingGroup=e)):(f.link=this.wc(g),null!==f.link&&e instanceof V&&(wq(b,g,!0)===c&&(f.link.fromNode=e),wq(b,g,!1)===c&&(f.link.toNode=e),g=b.sg(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}}Cq(b,c)}a=b.Pi(a);void 0!==a&&(a=this.Kb(a),a instanceof xg&&(e.containingGroup=a))}};sq.prototype.unresolveReferencesForPart=function(a){var b=this.diagram.model;if(a instanceof V){var c=b.ra(a.data);if(void 0!==c){for(var d=a.linksConnected;d.next();)Dq(b,c,d.value.data);a.isLinkLabel&&(d=a.labeledLink,null!==d&&Dq(b,c,d.data));if(a instanceof xg)for(a=a.memberParts;a.next();)d=a.value.data,b.Ab(d)&&Dq(b,c,d)}}};
sq.prototype.copyPartData=function(a,b){var c=Ii.prototype.copyPartData.call(this,a,b);if(a instanceof S)if(a=a.data,null!==a&&null!==b){var d=b.model;a=d.Wp(a);"object"===typeof a&&null!==a&&(d.Ei(a),c=b.wc(a))}else null!==c&&(b=this.diagram,null!==a&&null!==b&&null!==b.commandHandler&&b.commandHandler.copiesClipboardData&&(b=b.model.Wp(a),"object"===typeof b&&null!==b&&(c.data=b)));return c};
sq.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 S){if(mh(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&&(mh(a),a=a.copy(),null!==a&&(a.labeledLink=f,e.add(a))),f}else if(null!==d&&(d=f.Wp(d),"object"===
typeof d&&null!==d))return null!==a&&Eq(f,d,f.ra(a.data),!0),Fq(f,d,h,!0),null!==c&&Eq(f,d,f.ra(c.data),!1),Fq(f,d,b,!1),f.Ei(d),a=g.archetypeLabelNodeData,null===a||a instanceof V||(a=f.copyNodeData(a),"object"===typeof a&&null!==a&&(f.lf(a),a=f.ra(a),void 0!==a&&f.Lu(d,a))),e.wc(d);return null};sq.prototype.findPartForKey=sq.prototype.findPartForKey;sq.prototype.removeAllModeledParts=sq.prototype.removeAllModeledParts;sq.prototype.addModeledParts=sq.prototype.addModeledParts;
sq.prototype.addAllModeledParts=sq.prototype.addAllModeledParts;sq.className="GraphLinksPartManager";function Gq(){Ii.apply(this,arguments);this.bh=null}ma(Gq,Ii);
function Hq(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||!Lg(d,e,f,null,!0))if(d=a.getLinkCategoryForData(c.data),b=a.findLinkTemplateForCategory(d),null!==b&&(mh(b),b=b.copy(),null!==b)){var g=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;b.Bf=d;
b.kb=c.data;b.fromNode=e;b.toNode=f;a.diagram.add(b);b.kb=null;b.data=c.data;a.diagram.skipsModelSourceBindings=g}}}Gq.prototype.getLinkCategoryForData=function(a){return this.diagram.model.jv(a)};Gq.prototype.setLinkCategoryForData=function(a,b){this.diagram.model.Pv(a,b)};
Gq.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.Ke(a.data,d.ra(b));else{var e=this.bh;this.bh=a;null!==c&&d.Ke(c.data,void 0);d.Ke(b,d.ra(null!==a.toNode?a.toNode.data:null));this.bh=e}};
Gq.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.bh;this.bh=a;null!==c&&d.Ke(c.data,void 0);d.Ke(b,d.ra(null!==a.fromNode?a.fromNode.data:null));this.bh=e}else d.Ke(a.data,d.ra(b))};Gq.prototype.removeDataForLink=function(a){this.diagram.model.Ke(a.data,void 0)};
Gq.prototype.doModelChanged=function(a){Ii.prototype.doModelChanged.call(this,a);if(this.diagram){var b=this.diagram;if(a.model===b.model){var c=a.change;if(b.fa){b.fa=!1;try{var d=a.modelChange;if(""!==d){if(c===of){if("nodeParentKey"===d){var e=a.object,f=this.Kb(a.newValue),g=this.Ji(e);if(null!==this.bh)null!==f&&(this.bh.data=e,this.bh.category=this.getLinkCategoryForData(e));else if(null!==g){var h=g.Mi();null!==h?null===f?b.remove(h):b.isTreePathToChildren?h.fromNode=f:h.toNode=f:Hq(this,f,
g)}}else if("parentLinkCategory"===d){var k=this.Ji(a.object),l=a.newValue;if(null!==k&&"string"===typeof l){var m=k.Mi();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.wd()):this.updateDataBindings(p,n);b.isModified=!0}}finally{b.fa=!0}}}}};
Gq.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.Ri(b),b=c.Kb(b),d=a.rg(),b!==d&&(d=a.Mi(),null!==b?null!==d?c.isTreePathToChildren?d.fromNode=b:d.toNode=b:Hq(this,b,a):null!==d&&Wj(c,d,!1)))}}};Gq.prototype.updateDataBindings=function(a,b){Ii.prototype.updateDataBindings.call(this,a,b);"string"===typeof b&&null!==this.xc(a)&&(a=this.wc(a),null!==a&&a.Fa(b))};
Gq.prototype.resolveReferencesForData=function(a){var b=this.diagram.model,c=b.ra(a);if(void 0!==c){var d=Bq(b,c),e=this.xc(a);if(null!==d&&null!==e){for(d=d.iterator;d.next();){var f=d.value;b.Ab(f)&&e instanceof V&&b.Ri(f)===c&&Hq(this,e,this.Ji(f))}Cq(b,c)}a=b.Ri(a);void 0!==a&&e instanceof V&&(a=this.Kb(a),Hq(this,a,e))}};
Gq.prototype.unresolveReferencesForPart=function(a){var b=this.diagram.model;if(a instanceof V){var c=b.ra(a.data),d=this.wc(a.data);if(null!==d){d.isSelected=!1;d.isHighlighted=!1;var e=d.layer;if(null!==e){var f=e.zc(-1,d,!1);0<=f&&this.diagram.cb(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.Ab(e)&&Dq(b,c,e)}};
Gq.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.Ke(e.data,b.ra(d.data)),e.Mi()):null};Gq.className="TreePartManager";
function X(a){this.Jt=',\n "insertedNodeKeys": ';this.lw=',\n "modifiedNodeData": ';this.Lt=',\n "removedNodeKeys": ';E&&1<arguments.length&&v("Model constructor can only take one optional argument, the Array of node data.");qb(this);this.qn=this.Wa="";this.Of=!1;this.l={};this.sc=[];this.fb=new Ub;this.oi="key";this.Nk=this.tl=null;this.fn=this.gn=!1;this.jn=!0;this.Rm=null;this.Bj="category";this.Hf=new Ub;this.ku=new F;this.fh=!1;this.w=null;this.undoManager=new tf;void 0!==a&&(this.nodeDataArray=
a)}X.prototype.cloneProtected=function(a){a.Wa=this.Wa;a.qn=this.qn;a.Of=this.Of;a.oi=this.oi;a.tl=this.tl;a.Nk=this.Nk;a.gn=this.gn;a.fn=this.fn;a.jn=this.jn;a.Rm=this.Rm;a.Bj=this.Bj};X.prototype.copy=function(){var a=new this.constructor;this.cloneProtected(a);return a};t=X.prototype;t.clear=function(){this.sc=[];this.fb.clear();this.Hf.clear();this.undoManager.clear()};
t.toString=function(a){void 0===a&&(a=0);if(1<a)return this.Bq();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.ra(e)+":"+Wa(e)}}return b};
t.yk=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.uq=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);!1===a.copiesKey&&(this.copiesKey=!1);a.nodeCategoryProperty&&(this.nodeCategoryProperty=a.nodeCategoryProperty)};function Iq(a){return',\n "modelData": '+Jq(a,a.modelData)}
function Kq(a,b){b=b.modelData;Ja(b)&&(a.vm(b),a.modelData=b)}t.gw=function(){var a=this.modelData,b=!1,c;for(c in a)if(!Lq(c,a[c])){b=!0;break}a="";b&&(a=Iq(this));return a+',\n "nodeDataArray": '+Mq(this,this.nodeDataArray,!0)};t.Dv=function(a){Kq(this,a);a=a.nodeDataArray;Ka(a)&&(this.vm(a),this.nodeDataArray=a)};
function Nq(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(!Nq(a,b[e],c[e],d))return!1;return!0}if(Ja(b)&&Ja(c)){if(d.K(b)===c)return!0;d.add(b,c);for(var f in b){var g=b[f];if(!Lq(f,g)){var h=c[f];if(void 0===h||!Nq(a,g,h,d))return!1}}for(e in c)if(f=c[e],!Lq(e,f)&&(g=b[e],void 0===g||!Nq(a,g,f,d)))return!1;
return!0}return!1}function Oq(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.Fq=function(a){Oq(this,a,"nodeKeyProperty");for(var b=new H,c=new H,d=(new H).addAll(this.fb.iteratorKeys),e=new Ub,f=a.nodeDataArray,g=f.length,h=0;h<g;h++){var k=f[h],l=a.ra(k);if(void 0!==l){d.remove(l);var m=this.Sb(l);null===m?(b.add(l),c.add(k)):Nq(this,m,k,e)||c.add(k)}else this.mt(k),l=this.ra(k),b.add(l),c.add(k)}f="";Nq(this,this.modelData,a.modelData,e)||(f+=Iq(this));0<b.count&&(f+=this.Jt+Mq(this,b.Oa(),!0));0<c.count&&(f+=this.lw+Mq(this,c.Oa(),!0));0<d.count&&(f+=this.Lt+Mq(this,
d.Oa(),!0));return f};t.zy=function(a,b){w(a,X,X,"computeJsonDifference:newmodel");void 0===b&&(b=Pq(this,this));return'{ "class": '+this.quote(b)+', "incremental": 1'+this.yk()+this.Fq(a)+"}"};
t.Et=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.Ab(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.ra(a));b||f.add(a)});var k=new H;g.each(function(a){k.add(c.ra(a));b&&f.add(a)});a="";d&&(a+=Iq(this));0<h.count&&(a+=(b?this.Lt:this.Jt)+Mq(this,h.Oa(),!0));0<f.count&&(a+=this.lw+Mq(this,
f.Oa(),!0));0<k.count&&(a+=(b?this.Jt:this.Lt)+Mq(this,k.Oa(),!0));return a};
t.Cv=function(a){Kq(this,a);var b=a.insertedNodeKeys,c=a.modifiedNodeData,d=new Ub;if(Array.isArray(c))for(var e=0;e<c.length;e++){var f=c[e],g=this.ra(f);void 0!==g&&null!==g&&d.set(g,f)}if(Array.isArray(b))for(e=b.length,f=0;f<e;f++){g=b[f];var h=this.Sb(g);null===h&&(h=(h=d.get(g))?h:this.copyNodeData({}),this.Bm(h,g),this.lf(h))}if(Array.isArray(c))for(b=c.length,d=0;d<b;d++)if(e=c[d],f=this.ra(e),f=this.Sb(f),null!==f)for(var k in e)"__gohashid"===k||k===this.nodeKeyProperty||this.ik()&&k===
this.nodeIsGroupProperty||this.setDataProperty(f,k,e[k]);a=a.removedNodeKeys;if(Array.isArray(a))for(c=a.length,k=0;k<c;k++)b=this.Sb(a[k]),null!==b&&this.um(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 sf))return'{ "incremental": 0 }';void 0===b&&(b=Pq(this,this));return"2"===b?'{ "incremental": 2'+this.Et(c,"FinishedUndo"===a.propertyName)+"}":'{ "class": '+this.quote(b)+', "incremental": 1'+this.yk()+this.Et(c,"FinishedUndo"===a.propertyName)+"}"};t.gA=function(a,b){return this.Sx(a,b)};
t.Bq=function(a){void 0===a&&(a=Pq(this,this));return'{ "class": '+this.quote(a)+this.yk()+this.gw()+"}"};t.toJSON=function(a){return this.Bq(a)};t.Zw=function(a){var b=null;if("string"===typeof a)try{b=ra.JSON.parse(a)}catch(d){E&&Ha("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.Cv(b),this.ab("applyIncrementalJson"))};
t.sy=function(a){return this.Zw(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.vm=function(a){if(Ka(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];if(Ja(d)){var e=c;d=this.vm(d);Array.isArray(a)?a[e]=d:v("Cannot replace an object in an HTMLCollection or NodeList at "+e)}}else if(Ja(a)){for(c in a)if(e=a[c],Ja(e)&&(e=this.vm(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 F;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(Qq(a.x),Qq(a.y));else if("go.Size"===e)c=new Zb(Qq(a.width),Qq(a.height));else if("go.Rect"===e)c=new L(Qq(a.x),Qq(a.y),Qq(a.width),Qq(a.height));else if("go.Margin"===e)c=new Hc(Qq(a.top),Qq(a.right),Qq(a.bottom),Qq(a.left));else if("go.Spot"===e)"string"===typeof a["enum"]?c=je(a["enum"]):c=new M(Qq(a.x),Qq(a.y),Qq(a.offsetX),Qq(a.offsetY));else if("go.Brush"===e){if(c=new yl,c.type=sb(yl,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=Qq(a.startRadius)),"number"===typeof a.endRadius&&(c.endRadius=Qq(a.endRadius)),a=a.colorStops,Ja(a))for(b in a)c.addColorStop(parseFloat(b),a[b])}else"go.Geometry"===e?(b=null,"string"===typeof a.path?b=ze(a.path):b=new me,b.type=sb(me,a.type),"number"===typeof a.startX&&(b.startX=Qq(a.startX)),"number"===typeof a.startY&&(b.startY=Qq(a.startY)),
"number"===typeof a.endX&&(b.endX=Qq(a.endX)),"number"===typeof a.endY&&(b.endY=Qq(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=sb(Rq(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.Em=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.Em(a.valueOf()):Ka(a)?Mq(this,a):Ja(a)?Jq(this,a):"function"===typeof a?"null":a.toString()};
function Mq(a,b,c){void 0===c&&(c=!1);var d=b.length;if(0>=d)return"[]";var e=new ub;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.Em(g)))}c&&1<d&&e.add("\n");e.add(" ]");return e.toString()}function Lq(a,b){return void 0===b||"__gohashid"===a||"_"===a[0]||"function"===typeof b?!0:!1}function Sq(a){return isNaN(a)?"NaN":Infinity===a?"9e9999":-Infinity===a?"-9e9999":a}
function Jq(a,b){var c=b;if(c instanceof J)b={"class":"go.Point",x:Sq(c.x),y:Sq(c.y)};else if(c instanceof Zb)b={"class":"go.Size",width:Sq(c.width),height:Sq(c.height)};else if(c instanceof L)b={"class":"go.Rect",x:Sq(c.x),y:Sq(c.y),width:Sq(c.width),height:Sq(c.height)};else if(c instanceof Hc)b={"class":"go.Margin",top:Sq(c.top),right:Sq(c.right),bottom:Sq(c.bottom),left:Sq(c.left)};else if(c instanceof M)c.Za()?b={"class":"go.Spot",x:Sq(c.x),y:Sq(c.y),offsetX:Sq(c.offsetX),offsetY:Sq(c.offsetY)}:
b={"class":"go.Spot","enum":c.toString()};else if(c instanceof yl){b={"class":"go.Brush",type:c.type.name};if(c.type===Bl)b.color=c.color;else if(c.type===El||c.type===zl)b.start=c.start,b.end=c.end,c.type===zl&&(0!==c.startRadius&&(b.startRadius=Sq(c.startRadius)),isNaN(c.endRadius)||(b.endRadius=Sq(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 me)b={"class":"go.Geometry",type:c.type.name},0!==c.startX&&
(b.startX=Sq(c.startX)),0!==c.startY&&(b.startY=Sq(c.startY)),0!==c.endX&&(b.endX=Sq(c.endX)),0!==c.endY&&(b.endY=Sq(c.endY)),c.spot1.A(fd)||(b.spot1=c.spot1),c.spot2.A(ud)||(b.spot2=c.spot2),c.type===ne&&(b.path=we(c));else if(c instanceof D)b={"class":"go.EnumValue",classType:Pq(a,c.classType),name:c.name};else if(E&&null!==Rq(Pq(a,c)))return Ha("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=xn(b,e);if(!Lq(e,f))if(c?c=!1:d+=", ",d+='"'+e+'":',"points"===e&&f instanceof F){var g="[";for(f=f.iterator;f.next();){var h=f.value;1<g.length&&(g+=",");g+=a.Em(h.x);g+=",";g+=a.Em(h.y)}g+="]";d+=g}else d+=a.Em(f)}return d+"}"}function Qq(a){return"number"===typeof a?a:"NaN"===a?NaN:"9e9999"===a?Infinity:"-9e9999"===a?-Infinity:parseFloat(a)}t.sh=function(a){z(a,"function",X,"addChangedListener:listener");this.ku.add(a)};
t.uk=function(a){z(a,"function",X,"removeChangedListener:listener");this.ku.remove(a)};t.Qs=function(a){this.skipsUndoManager||this.undoManager.nv(a);for(var b=this.ku,c=b.length,d=0;d<c;d++)b.O(d)(a)};t.cb=function(a,b,c,d,e,f,g){Tq(this,"",a,b,c,d,e,f,g)};t.g=function(a,b,c,d,e){Tq(this,"",of,a,this,b,c,d,e)};t.rt=function(a,b,c,d,e,f){Tq(this,"",of,b,a,c,d,e,f)};
function Tq(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.Qs(l)}
t.Wj=function(a,b){if(null!==a&&a.model===this)if(a.change===of)dk(a.object,a.propertyName,a.K(b));else if(a.change===qf){var c=a.newParam;if("nodeDataArray"===a.modelChange){if(a=a.newValue,Ja(a)&&"number"===typeof c){var d=this.ra(a);b?(this.sc[c]===a&&Oa(this.sc,c),void 0!==d&&this.fb.remove(d)):(this.sc[c]!==a&&Na(this.sc,c,a),void 0!==d&&this.fb.add(d,a))}}else""===a.modelChange?((d=a.object)&&!Ka(d)&&a.propertyName&&(d=xn(a.object,a.propertyName)),Ka(d)&&"number"===typeof c&&(a=a.newValue,b?
Oa(d,c):Na(d,c,a))):v("unknown ChangedEvent.Insert modelChange: "+a.toString())}else a.change===rf?(c=a.oldParam,"nodeDataArray"===a.modelChange?(a=a.oldValue,Ja(a)&&"number"===typeof c&&(d=this.ra(a),b?(this.sc[c]!==a&&Na(this.sc,c,a),void 0!==d&&this.fb.add(d,a)):(this.sc[c]===a&&Oa(this.sc,c),void 0!==d&&this.fb.remove(d)))):""===a.modelChange?((d=a.object)&&!Ka(d)&&a.propertyName&&(d=xn(a.object,a.propertyName)),Ka(d)&&"number"===typeof c&&(a=a.oldValue,b?Na(d,c,a):Oa(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.ab=function(a){return this.undoManager.ab(a)};t.xf=function(){return this.undoManager.xf()};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.ab(b):this.undoManager.xf(),this.skipsUndoManager=c}};t=X.prototype;
t.Fa=function(a,b){void 0===b&&(b="");Tq(this,"SourceChanged",pf,b,a,null,null)};function Uq(a,b,c){"string"!==typeof a&&"function"!==typeof a&&Ba(a,"string or function",b,c)}t.ra=function(a){if(null!==a){var b=this.oi;if(""!==b&&(b=xn(a,b),void 0!==b)){if(yq(b))return b;v("Key value for node data "+a+" is not a number or a string: "+b)}}};
t.Bm=function(a,b){void 0!==b&&null!==b&&yq(b)||Ba(b,"number or string",X,"setKeyForNodeData:key");if(null!==a){var c=this.oi;if(""!==c)if(this.Ab(a)){var d=xn(a,c);d!==b&&null===this.Sb(b)&&(dk(a,c,b),void 0!==d&&this.fb.remove(d),this.fb.add(b,a),Tq(this,"nodeKey",of,c,a,d,b),"string"===typeof c&&this.Fa(a,c),this.xq(d,b))}else dk(a,c,b)}};function yq(a){return"number"===typeof a||"string"===typeof a}t.Ab=function(a){var b=this.ra(a);return void 0===b?!1:this.fb.K(b)===a};
t.Sb=function(a){null===a&&v("Model.findNodeDataForKey:key must not be null");return void 0!==a&&yq(a)?this.fb.K(a):null};
t.mt=function(a){if(null!==a){var b=this.oi;if(""!==b){var c=this.ra(a);if(void 0===c||this.fb.contains(c)){var d=this.tl;if(null!==d&&(c=d(this,a),void 0!==c&&null!==c&&!this.fb.contains(c))){dk(a,b,c);return}if("string"===typeof c){for(d=2;this.fb.contains(c+d);)d++;dk(a,b,c+d)}else if(void 0===c||"number"===typeof c){for(c=-this.fb.count-1;this.fb.contains(c);)c--;dk(a,b,c)}else E&&v("Model.getKeyForNodeData returned something other than a string or a number: "+c)}}}};
t.lf=function(a){null!==a&&(Nb(a),this.Ab(a)||qq(this,a,!0))};function qq(a,b,c){var d=a.ra(b);if(void 0===d||a.fb.K(d)!==b)a.mt(b),d=a.ra(b),void 0===d?v("Model.makeNodeDataKeyUnique failed on "+b+". Data not added to Model."):(a.fb.add(d,b),d=null,c&&(d=a.sc.length,Na(a.sc,d,b)),Tq(a,"nodeDataArray",qf,"nodeDataArray",a,null,b,null,d),a.xm(b),a.wm(b))}t.oy=function(a){if(Ka(a))for(var b=a.length,c=0;c<b;c++)this.lf(a[c]);else for(a=a.iterator;a.next();)this.lf(a.value)};
t.um=function(a){null!==a&&pq(this,a,!0)};function pq(a,b,c){var d=a.ra(b);void 0!==d&&a.fb.remove(d);d=null;if(c){a:if(c=a.sc,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;Oa(a.sc,d)}Tq(a,"nodeDataArray",rf,"nodeDataArray",a,b,null,d,null);a.Cq(b)}t.Yz=function(a){if(Ka(a))for(var b=a.length,c=0;c<b;c++)this.um(a[c]);else for(a=a.iterator;a.next();)this.um(a.value)};
t.Nz=function(a){if(Ka(a)){for(var b=new H(this.fb.iteratorKeys),c=new H,d=a.length,e=0;e<d;e++){var f=a[e],g=this.ra(f);if(void 0!==g){c.add(g);var h=this.Sb(g);null!==h?this.Vj(h,f):(h={},this.Bm(h,g),this.Vj(h,f),this.lf(h))}else this.lf(f),c.add(this.ra(f))}for(a=b.iterator;a.next();)b=a.value,c.contains(b)||(b=this.Sb(b))&&this.um(b)}};t.xq=function(a,b){void 0!==b&&(a=Bq(this,a),a instanceof H&&this.Hf.add(b,a))};t.cw=function(){};t.xm=function(){};t.wm=function(){};t.Cq=function(){};
function Dq(a,b,c){if(void 0!==b){var d=a.Hf.K(b);null===d&&(d=new H,a.Hf.add(b,d));d.add(c)}}function Cq(a,b,c){if(void 0!==b){var d=a.Hf.K(b);d instanceof H&&(void 0===c||null===c?a.Hf.remove(b):(d.remove(c),0===d.count&&a.Hf.remove(b)))}}function Bq(a,b){if(void 0===b)return null;a=a.Hf.K(b);return a instanceof H?a:null}t.Ru=function(a){void 0===a?this.Hf.clear():this.Hf.remove(a)};
X.prototype.copyNodeData=function(a){if(null===a)return null;var b=this.Nk;a=null!==b?b(a,this):Vq(this,a,!0);Ja(a)&&qb(a);return a};
function Vq(a,b,c){if(a.copiesArrays&&Array.isArray(b)){var d=[];for(c=0;c<b.length;c++){var e=Vq(a,b[c],a.copiesArrayObjects);d.push(e)}qb(d);return d}if(c&&Ja(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=xn(b,d);var g=Pq(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]&&Ha('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 tf||f instanceof sf||f instanceof nf?!0:!1;g?dk(c,d,f):(f=Vq(a,f,!1),dk(c,d,f))}qb(c);return c}return b instanceof J?b.copy():b instanceof Zb?b.copy():b instanceof
L?b.copy():b instanceof M?b.copy():b instanceof Hc?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.Ab(a))if(b===this.nodeKeyProperty)this.Bm(a,c);else{if(b===this.nodeCategoryProperty){this.zq(a,c);return}}else!Wq&&a instanceof N&&(Wq=!0,Ha('Model.setDataProperty is modifying a GraphObject, "'+a.toString()+'"'),Ha(" Is that really your intent?"));var d=xn(a,
b);d!==c&&(dk(a,b,c),this.rt(a,b,d,c))};t=X.prototype;t.set=function(a,b,c){this.setDataProperty(a,b,c)};t.Vj=function(a,b){if(b){var c=this.Ab(a),d;for(d in b)"__gohashid"===d||c&&d===this.nodeKeyProperty||this.setDataProperty(a,d,b[d])}};t.ky=function(a,b){this.ct(a,-1,b)};
t.ct=function(a,b,c){E&&(La(a,X,"insertArrayItem:arr"),B(b,X,"insertArrayItem:idx"),a===this.sc&&v("Model.insertArrayItem or Model.addArrayItem should not be called on the Model.nodeDataArray"));0>b&&(b=a.length);Na(a,b,c);Tq(this,"",qf,"",a,null,c,null,b)};
t.Ev=function(a,b){void 0===b&&(b=-1);E&&(La(a,X,"removeArrayItem:arr"),B(b,X,"removeArrayItem:idx"));a===this.sc&&v("Model.removeArrayItem should not be called on the Model.nodeDataArray");-1===b&&(b=a.length-1);var c=a[b];Oa(a,b);Tq(this,"",rf,"",a,c,null,b,null)};t.$s=function(a){if(null===a)return"";var b=this.Bj;if(""===b)return"";b=xn(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.zq=function(a,b){z(b,"string",X,"setCategoryForNodeData:cat");if(null!==a){var c=this.Bj;if(""!==c)if(this.Ab(a)){var d=xn(a,c);void 0===d&&(d="");d!==b&&(dk(a,c,b),Tq(this,"nodeCategory",of,c,a,d,b))}else dk(a,c,b)}};t.km=function(){return!1};t.ik=function(){return!1};t.jm=function(){return!1};t.jt=function(){return!1};t.Ti=function(){return!1};function Mi(){return new X}
function Pq(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 Pq(a,b.constructor);return typeof b}function Rq(a){return Xq[a]?Xq[a]:null}function xn(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&&Ha("property get error: "+d.toString())}return c}
function dk(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&&Ha("property set error: "+d.toString())}}
na.Object.defineProperties(X.prototype,{name:{configurable:!0,get:function(){return this.Wa},set:function(a){var b=this.Wa;b!==a&&(z(a,"string",X,"name"),this.Wa=a,this.g("name",b,a))}},dataFormat:{configurable:!0,get:function(){return this.qn},set:function(a){var b=this.qn;b!==a&&(z(a,"string",X,"dataFormat"),this.qn=a,this.g("dataFormat",b,a))}},isReadOnly:{configurable:!0,get:function(){return this.Of},set:function(a){var b=this.Of;b!==a&&(z(a,"boolean",
X,"isReadOnly"),this.Of=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.Fa(a))}},undoManager:{configurable:!0,get:function(){return this.w},set:function(a){var b=this.w;b!==a&&(w(a,tf,X,"undoManager"),null!==b&&b.Gx(this),this.w=a,null!==a&&a.Xw(this))}},skipsUndoManager:{configurable:!0,get:function(){return this.fh},
set:function(a){z(a,"boolean",X,"skipsUndoManager");this.fh=a}},nodeKeyProperty:{configurable:!0,get:function(){return this.oi},set:function(a){var b=this.oi;b!==a&&(Uq(a,X,"nodeKeyProperty"),""===a&&v("Model.nodeKeyProperty may not be the empty string"),0<this.fb.count&&v("Cannot set Model.nodeKeyProperty when there is existing node data"),this.oi=a,this.g("nodeKeyProperty",b,a))}},makeUniqueKeyFunction:{configurable:!0,get:function(){return this.tl},set:function(a){var b=
this.tl;b!==a&&(null!==a&&z(a,"function",X,"makeUniqueKeyFunction"),this.tl=a,this.g("makeUniqueKeyFunction",b,a))}},nodeDataArray:{configurable:!0,get:function(){return this.sc},set:function(a){var b=this.sc;if(b!==a){La(a,X,"nodeDataArray");this.fb.clear();this.cw();for(var c=a.length,d=0;d<c;d++){var e=a[d];if(!Ja(e)){v("Model.nodeDataArray must only contain Objects, not: "+e);return}Nb(e)}this.sc=a;d=new F;for(e=0;e<c;e++){var f=a[e],g=this.ra(f);void 0===g?d.add(f):null!==this.fb.K(g)?
d.add(f):this.fb.add(g,f)}for(d=d.iterator;d.next();)e=d.value,this.mt(e),f=this.ra(e),void 0!==f&&this.fb.add(f,e);Tq(this,"nodeDataArray",of,"nodeDataArray",this,b,a);for(b=0;b<c;b++)d=a[b],this.xm(d),this.wm(d);this.Ru();Array.isArray(a)||(this.isReadOnly=!0)}}},copyNodeDataFunction:{configurable:!0,get:function(){return this.Nk},set:function(a){var b=this.Nk;b!==a&&(null!==a&&z(a,"function",X,"copyNodeDataFunction"),this.Nk=a,this.g("copyNodeDataFunction",b,a))}},copiesArrays:{configurable:!0,
enumerable:!0,get:function(){return this.gn},set:function(a){var b=this.gn;b!==a&&(null!==a&&z(a,"boolean",X,"copiesArrays"),this.gn=a,this.g("copiesArrays",b,a))}},copiesArrayObjects:{configurable:!0,get:function(){return this.fn},set:function(a){var b=this.fn;b!==a&&(null!==a&&z(a,"boolean",X,"copiesArrayObjects"),this.fn=a,this.g("copiesArrayObjects",b,a))}},copiesKey:{configurable:!0,get:function(){return this.jn},set:function(a){var b=this.jn;b!==a&&(null!==a&&z(a,
"boolean",X,"copiesKey"),this.jn=a,this.g("copiesKey",b,a))}},afterCopyFunction:{configurable:!0,get:function(){return this.Rm},set:function(a){var b=this.Rm;b!==a&&(null!==a&&z(a,"function",X,"afterCopyFunction"),this.Rm=a,this.g("afterCopyFunction",b,a))}},nodeCategoryProperty:{configurable:!0,get:function(){return this.Bj},set:function(a){var b=this.Bj;b!==a&&(Uq(a,X,"nodeCategoryProperty"),this.Bj=a,this.g("nodeCategoryProperty",b,a))}}});
na.Object.defineProperties(X,{type:{configurable:!0,get:function(){return"Model"}}});X.prototype.setCategoryForNodeData=X.prototype.zq;X.prototype.getCategoryForNodeData=X.prototype.$s;X.prototype.removeArrayItem=X.prototype.Ev;X.prototype.insertArrayItem=X.prototype.ct;X.prototype.addArrayItem=X.prototype.ky;X.prototype.assignAllDataProperties=X.prototype.Vj;X.prototype.set=X.prototype.set;X.prototype.clearUnresolvedReferences=X.prototype.Ru;X.prototype.mergeNodeDataArray=X.prototype.Nz;
X.prototype.removeNodeDataCollection=X.prototype.Yz;X.prototype.removeNodeData=X.prototype.um;X.prototype.addNodeDataCollection=X.prototype.oy;X.prototype.addNodeData=X.prototype.lf;X.prototype.makeNodeDataKeyUnique=X.prototype.mt;X.prototype.findNodeDataForKey=X.prototype.Sb;X.prototype.containsNodeData=X.prototype.Ab;X.prototype.setKeyForNodeData=X.prototype.Bm;X.prototype.getKeyForNodeData=X.prototype.ra;X.prototype.updateTargetBindings=X.prototype.Fa;X.prototype.commit=X.prototype.commit;
X.prototype.rollbackTransaction=X.prototype.xf;X.prototype.commitTransaction=X.prototype.ab;X.prototype.startTransaction=X.prototype.Ca;X.prototype.raiseDataChanged=X.prototype.rt;X.prototype.raiseChanged=X.prototype.g;X.prototype.raiseChangedEvent=X.prototype.cb;X.prototype.removeChangedListener=X.prototype.uk;X.prototype.addChangedListener=X.prototype.sh;X.prototype.writeJsonValue=X.prototype.Em;X.prototype.replaceJsonObjects=X.prototype.vm;X.prototype.applyIncrementalJSON=X.prototype.sy;
X.prototype.applyIncrementalJson=X.prototype.Zw;X.prototype.toJSON=X.prototype.toJSON;X.prototype.toJson=X.prototype.Bq;X.prototype.toIncrementalJSON=X.prototype.gA;X.prototype.toIncrementalJson=X.prototype.Sx;X.prototype.computeJsonDifference=X.prototype.zy;X.prototype.clear=X.prototype.clear;var Wq=!1,Xq={};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&&Ha("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=Rq(d)):(e=Rq(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.uq(c);b.Dv(c);return b};X.safePropertyValue=xn;X.safePropertySet=dk;Xq.Brush=yl;Xq.ChangedEvent=nf;Xq.Geometry=me;Xq.GraphObject=N;Xq.Margin=Hc;Xq.Panel=W;Xq.Point=J;Xq.Rect=L;Xq.Size=Zb;Xq.Spot=M;Xq.Transaction=sf;Xq.UndoManager=tf;
function Ti(a,b,c){qb(this);this.u=!1;void 0===a?a="":z(a,"string",Ti,"constructor:targetprop");void 0===b?b=a:z(b,"string",Ti,"constructor:sourceprop");void 0===c?c=null:null!==c&&z(c,"function",Ti,"constructor:conv");this.l=-1;this.Sd=null;this.Tl=a;this.Sl=this.Dp=0;this.Cs=null;this.$n=!1;this.Jl=b;this.en=c;this.wo=Yq;this.Zm=null;this.du=new H}
Ti.prototype.copy=function(){var a=new Ti;a.Tl=this.Tl;a.Dp=this.Dp;a.Sl=this.Sl;a.Cs=this.Cs;a.$n=this.$n;a.Jl=this.Jl;a.en=this.en;a.wo=this.wo;a.Zm=this.Zm;return a};t=Ti.prototype;t.hb=function(a){a.classType===Ti?this.mode=a:Fa(this,a)};t.toString=function(){return"Binding("+this.targetProperty+":"+this.sourceProperty+(-1!==this.bj?" "+this.bj:"")+" "+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",Ti,"makeTwoWay");this.mode=pn;this.backConverter=a;return this};t.rq=function(a){void 0===a&&(a="");E&&z(a,"string",Ti,"ofObject:srcname");this.sourceName=a;this.isToModel=!1;return this};t.Pz=function(){this.sourceName=null;this.isToModel=!0;return this};function ll(a,b,c){a=a.sourceName;return null===a||""===a?b:"/"===a?c.part:"."===a?c:".."===a?c.panel:b.bb(a)}
t.dw=function(a,b,c){var d=this.Jl;if(void 0===c||""===d||d===c){c=this.Tl;var e=this.en;if(null===e&&""===c)Ha("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)?Ha("Binding error: undefined target property: "+c+" on "+a.toString()):"name"===c&&a instanceof N&&Ha("Binding error: cannot modify GraphObject.name on "+a.toString()));var f=b;""!==d&&(f=xn(b,d));if(void 0!==f)if(null===
e)""!==c&&dk(a,c,f);else try{if(""!==c){var g=e(f,a);E&&void 0===g&&Ha('Binding warning: conversion function returned undefined when setting target property "'+c+'" on '+a.toString()+", function is: "+e);dk(a,c,g)}else e(f,a)}catch(h){E&&Ha("Binding error: "+h.toString()+' setting target property "'+c+'" on '+a.toString()+" with conversion function: "+e)}}}};
t.Eq=function(a,b,c,d){if(this.wo===pn){var e=this.Tl;if(void 0===c||e===c){c=this.Jl;var f=this.Zm,g=a;""!==e&&(g=xn(a,e));if(void 0!==g&&!this.du.contains(a))try{this.du.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.Ab(b)&&Ha("Binding error: cannot have TwoWay Binding on node data key property: "+this.toString()),k.setDataProperty(b,c,g)):dk(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.Ev(m,l);k.ct(m,l,g)}}else try{if(""!==c){var n=f(g,b,k);null!==k?(E&&(k.nodeKeyProperty===c&&k.Ab(b)&&Ha("Binding error: cannot have TwoWay Binding on node data key property: "+this.toString()),void 0===n&&Ha('Binding warning: conversion function returned undefined when setting source property "'+c+'" on '+b.toString()+", function is: "+f)),k.setDataProperty(b,c,n)):dk(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.Ev(r,q);k.ct(r,q,p)}}}catch(u){E&&Ha("Binding error: "+u.toString()+' setting source property "'+c+'" on '+b.toString()+" with conversion function: "+f)}}finally{this.du.remove(a)}}}};
na.Object.defineProperties(Ti.prototype,{bj:{configurable:!0,get:function(){return this.l},set:function(a){this.u&&za(this);z(a,"number",Ti,"targetId");this.l=a}},targetProperty:{configurable:!0,get:function(){return this.Tl},set:function(a){this.u&&za(this);z(a,"string",Ti,"targetProperty");this.Tl=a}},sourceName:{configurable:!0,get:function(){return this.Cs},set:function(a){this.u&&za(this);null!==a&&z(a,"string",Ti,"sourceName");this.Cs=a;null!==a&&(this.$n=
!1)}},isToModel:{configurable:!0,get:function(){return this.$n},set:function(a){this.u&&za(this);z(a,"boolean",Ti,"isToModel");this.$n=a}},sourceProperty:{configurable:!0,get:function(){return this.Jl},set:function(a){this.u&&za(this);z(a,"string",Ti,"sourceProperty");this.Jl=a}},converter:{configurable:!0,get:function(){return this.en},set:function(a){this.u&&za(this);null!==a&&z(a,"function",Ti,"converter");this.en=a}},backConverter:{configurable:!0,
get:function(){return this.Zm},set:function(a){this.u&&za(this);null!==a&&z(a,"function",Ti,"backConverter");this.Zm=a}},mode:{configurable:!0,get:function(){return this.wo},set:function(a){this.u&&za(this);tb(a,Ti,Ti,"mode");this.wo=a}}});Ti.prototype.updateSource=Ti.prototype.Eq;Ti.prototype.updateTarget=Ti.prototype.dw;Ti.prototype.ofModel=Ti.prototype.Pz;Ti.prototype.ofObject=Ti.prototype.rq;Ti.prototype.makeTwoWay=Ti.prototype.yx;
var Yq=new D(Ti,"OneWay",1),pn=new D(Ti,"TwoWay",2);Ti.className="Binding";Ti.parseEnum=function(a,b){z(a,"function",Ti,"parseEnum:ctor");tb(b,a,Ti,"parseEnum:defval");return function(c){c=sb(a,c);return null===c?b:c}};Ti.toString=Wa;Ti.OneWay=Yq;Ti.TwoWay=pn;
function Zq(a,b){X.call(this);this.It=',\n "insertedLinkKeys": ';this.kw=',\n "modifiedLinkData": ';this.Kt=',\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.Rc=[];this.Pf=new H;this.rb=new Ub;this.ki="";this.ej=this.Mk=this.ul=null;this.We="from";this.Xe="to";this.yj=this.xj="";this.wj="category";this.Kd="";this.yl="isGroup";this.ue="group";this.hn=!1;void 0!==a&&(this.nodeDataArray=
a);void 0!==b&&(this.linkDataArray=b)}ma(Zq,X);Zq.constructGraphLinksModel=X.constructGraphLinksModel;Zq.prototype.cloneProtected=function(a){X.prototype.cloneProtected.call(this,a);a.ki=this.ki;a.ul=this.ul;a.Mk=this.Mk;a.We=this.We;a.Xe=this.Xe;a.xj=this.xj;a.yj=this.yj;a.wj=this.wj;a.Kd=this.Kd;a.yl=this.yl;a.ue=this.ue;a.hn=this.hn};t=Zq.prototype;t.clear=function(){X.prototype.clear.call(this);this.Rc=[];this.rb.clear();this.Pf.clear()};
t.toString=function(a){void 0===a&&(a=0);if(2<=a)return this.Bq();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.ra(e)+":"+Wa(e)}b+="\n link data:";a=this.linkDataArray;c=a.length;for(d=0;d<c;d++)e=a[d],b+=" "+wq(this,e,!0)+"--\x3e"+wq(this,e,!1)}return b};
t.yk=function(){var a=X.prototype.yk.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.uq=function(a){X.prototype.uq.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.gw=function(){var a=X.prototype.gw.call(this),b=',\n "linkDataArray": '+Mq(this,this.linkDataArray,!0);return a+b};t.Dv=function(a){X.prototype.Dv.call(this,a);a=a.linkDataArray;Array.isArray(a)&&(this.vm(a),this.linkDataArray=a)};
t.Fq=function(a){if(!(a instanceof Zq))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.Fq.call(this,a);Oq(this,a,"linkKeyProperty");Oq(this,a,"linkFromKeyProperty");Oq(this,a,"linkToKeyProperty");Oq(this,a,"linkLabelKeysProperty");Oq(this,a,"nodeIsGroupProperty");Oq(this,a,"nodeGroupKeyProperty");for(var c=new H,d=
new H,e=(new H).addAll(this.rb.iteratorKeys),f=new Ub,g=a.linkDataArray,h=g.length,k=0;k<h;k++){var l=g[k],m=a.kc(l);if(void 0!==m){e.remove(m);var n=this.yh(m);null===n?(c.add(m),d.add(l)):Nq(this,n,l,f)||d.add(l)}else this.oq(l),m=this.kc(l),c.add(m),d.add(l)}a=b;0<c.count&&(a+=this.It+Mq(this,c.Oa(),!0));0<d.count&&(a+=this.kw+Mq(this,d.Oa(),!0));0<e.count&&(a+=this.Kt+Mq(this,e.Oa(),!0));return a};
t.Et=function(a,b){E&&""===this.linkKeyProperty&&v("GraphLinksModel.linkKeyProperty must not be an empty string for .toIncrementalJson() to succeed.");var c=X.prototype.Et.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.De(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.Kt:this.It)+Mq(this,h.Oa(),!0));0<f.count&&(a+=this.kw+Mq(this,f.Oa(),!0));0<k.count&&(a+=(b?this.It:this.Kt)+Mq(this,k.Oa(),!0));return a};
t.Cv=function(a){X.prototype.Cv.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.yh(e);null===f&&(f=this.Wp({}),this.At(f,e),this.Ei(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.yh(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.yh(a[b]),null!==c&&this.tm(c)};
t.Wj=function(a,b){if(a.change===qf){var c=a.newParam;if("linkDataArray"===a.modelChange){a=a.newValue;if(Ja(a)&&"number"===typeof c){var d=this.kc(a);b?(this.Pf.remove(a),this.Rc[c]===a&&this.Rc.splice(c,1),void 0!==d&&this.rb.remove(d)):(this.Pf.add(a),this.Rc[c]!==a&&this.Rc.splice(c,0,a),void 0!==d&&this.rb.add(d,a))}return}if("linkLabelKeys"===a.modelChange){d=this.sg(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;Ja(a)&&"number"===typeof c&&(d=this.kc(a),b?(this.Pf.add(a),this.Rc[c]!==a&&this.Rc.splice(c,0,a),void 0!==d&&this.rb.add(d,a)):(this.Pf.remove(a),this.Rc[c]===a&&this.Rc.splice(c,1),void 0!==d&&this.rb.remove(d)));return}if("linkLabelKeys"===a.modelChange){d=this.sg(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.Wj.call(this,a,b)};t.lm=function(a){if(void 0!==a){var b=this.ej;if(null!==b){var c=this.Sb(a);null===c&&(c=this.copyNodeData(b),dk(c,this.nodeKeyProperty,a),this.lf(c))}return a}};t.kz=function(a){return wq(this,a,!0)};t.Kx=function(a,b){Eq(this,a,b,!0)};t.pz=function(a){return wq(this,a,!1)};t.Ox=function(a,b){Eq(this,a,b,!1)};
function wq(a,b,c){if(null!==b&&(a=c?a.We:a.Xe,""!==a&&(a=xn(b,a),void 0!==a))){if(yq(a))return a;v((c?"FromKey":"ToKey")+" value for link data "+b+" is not a number or a string: "+a)}}
function Eq(a,b,c,d){null===c&&(c=void 0);void 0===c||yq(c)||Ba(c,"number or string",Zq,d?"setFromKeyForLinkData:key":"setToKeyForLinkData:key");if(null!==b){var e=d?a.We:a.Xe;if(""!==e)if(c=a.lm(c),a.De(b)){var f=xn(b,e);f!==c&&(Cq(a,f,b),dk(b,e,c),null===a.Sb(c)&&Dq(a,c,b),Tq(a,d?"linkFromKey":"linkToKey",of,e,b,f,c),"string"===typeof e&&a.Fa(b,e))}else dk(b,e,c)}}t.lz=function(a){return vq(this,a,!0)};t.Lx=function(a,b){Fq(this,a,b,!0)};t.qz=function(a){return vq(this,a,!1)};
t.Px=function(a,b){Fq(this,a,b,!1)};function vq(a,b,c){if(null===b)return"";a=c?a.xj:a.yj;if(""===a)return"";b=xn(b,a);return void 0===b?"":b}function Fq(a,b,c,d){z(c,"string",Zq,d?"setFromPortIdForLinkData:portname":"setToPortIdForLinkData:portname");if(null!==b){var e=d?a.xj:a.yj;if(""!==e)if(a.De(b)){var f=xn(b,e);void 0===f&&(f="");f!==c&&(dk(b,e,c),Tq(a,d?"linkFromPortId":"linkToPortId",of,e,b,f,c),"string"===typeof e&&a.Fa(b,e))}else dk(b,e,c)}}
t.sg=function(a){if(null===a)return $q;var b=this.Kd;if(""===b)return $q;a=xn(a,b);return void 0===a?$q:a};t.Ov=function(a,b){La(b,Zq,"setLabelKeysForLinkData:arr");if(null!==a){var c=this.Kd;if(""!==c)if(this.De(a)){var d=xn(a,c);void 0===d&&(d=$q);if(d!==b){if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)Cq(this,d[f],a);dk(a,c,b);e=b.length;for(f=0;f<e;f++){var g=b[f];null===this.Sb(g)&&Dq(this,g,a)}Tq(this,"linkLabelKeys",of,c,a,d,b);"string"===typeof c&&this.Fa(a,c)}}else dk(a,c,b)}};
t.Lu=function(a,b){if(null!==b&&void 0!==b&&(yq(b)||Ba(b,"number or string",Zq,"addLabelKeyForLinkData:key"),null!==a)){var c=this.Kd;if(""!==c){var d=xn(a,c);if(void 0===d)c=[],c.push(b),this.Ov(a,c);else if(Array.isArray(d)){var e=d.indexOf(b);0<=e||(e=d.length,d.push(b),this.De(a)&&(null===this.Sb(b)&&Dq(this,b,a),Tq(this,"linkLabelKeys",qf,c,a,null,b,null,e)))}else v(c+" property is not an Array; cannot addLabelKeyForLinkData: "+a)}}};
t.Fx=function(a,b){if(null!==b&&void 0!==b&&(yq(b)||Ba(b,"number or string",Zq,"removeLabelKeyForLinkData:key"),null!==a)){var c=this.Kd;if(""!==c){var d=xn(a,c);if(Array.isArray(d)){var e=d.indexOf(b);0>e||(d.splice(e,1),this.De(a)&&(Cq(this,b,a),Tq(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.ki;if(""!==b&&(b=xn(a,b),void 0!==b)){if(yq(b))return b;v("Key value for link data "+a+" is not a number or a string: "+b)}}};t.At=function(a,b){void 0!==b&&null!==b&&yq(b)||Ba(b,"number or string",Zq,"setKeyForLinkData:key");if(null!==a){var c=this.ki;if(""!==c)if(this.De(a)){var d=xn(a,c);d!==b&&null===this.yh(b)&&(dk(a,c,b),void 0!==d&&this.rb.remove(d),this.rb.add(b,a),Tq(this,"linkKey",of,c,a,d,b),"string"===typeof c&&this.Fa(a,c))}else dk(a,c,b)}};
t.yh=function(a){null===a&&v("GraphLinksModel.findLinkDataForKey:key must not be null");return void 0!==a&&yq(a)?this.rb.K(a):null};
t.oq=function(a){if(null!==a){var b=this.ki;if(""!==b){var c=this.kc(a);if(void 0===c||this.rb.contains(c)){var d=this.ul;if(null!==d&&(c=d(this,a),void 0!==c&&null!==c&&!this.rb.contains(c))){dk(a,b,c);return}if("string"===typeof c){for(d=2;this.rb.contains(c+d);)d++;dk(a,b,c+d)}else if(void 0===c||"number"===typeof c){for(c=-this.rb.count-1;this.rb.contains(c);)c--;dk(a,b,c)}else E&&v("GraphLinksModel.getKeyForLinkData returned something other than a string or a number: "+c)}}}};
t.De=function(a){return null===a?!1:this.Pf.contains(a)};t.Ei=function(a){null!==a&&(Nb(a),this.De(a)||Aq(this,a,!0))};function Aq(a,b,c){if(""!==a.linkKeyProperty){var d=a.kc(b);if(void 0!==d&&a.rb.K(d)===b)return;a.oq(b);d=a.kc(b);if(void 0===d){v("GraphLinksModel.makeLinkDataKeyUnique failed on "+b+". Data not added to model.");return}a.rb.add(d,b)}a.Pf.add(b);d=null;c&&(d=a.Rc.length,a.Rc.splice(d,0,b));Tq(a,"linkDataArray",qf,"linkDataArray",a,null,b,null,d);ar(a,b)}
t.ny=function(a){if(Array.isArray(a))for(var b=a.length,c=0;c<b;c++)this.Ei(a[c]);else for(a=a.iterator;a.next();)this.Ei(a.value)};t.tm=function(a){null!==a&&zq(this,a,!0)};function zq(a,b,c){a.Pf.remove(b);var d=a.kc(b);void 0!==d&&a.rb.remove(d);d=null;if(c){d=a.Rc.indexOf(b);if(0>d)return;a.Rc.splice(d,1)}Tq(a,"linkDataArray",rf,"linkDataArray",a,b,null,d,null);c=wq(a,b,!0);Cq(a,c,b);c=wq(a,b,!1);Cq(a,c,b);d=a.sg(b);if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)c=d[f],Cq(a,c,b)}
t.Wz=function(a){if(Array.isArray(a))for(var b=a.length,c=0;c<b;c++)this.tm(a[c]);else for(a=a.iterator;a.next();)this.tm(a.value)};
t.Mz=function(a){E&&""===this.linkKeyProperty&&v("GraphLinksModel.linkKeyProperty must not be an empty string for .mergeLinkDataArray() to succeed.");if(Ka(a)){for(var b=new H(this.rb.iteratorKeys),c=new H,d=a.length,e=0;e<d;e++){var f=a[e],g=this.kc(f);if(void 0!==g){c.add(g);var h=this.yh(g);null!==h?this.Vj(h,f):(h={},this.At(h,g),this.Vj(h,f),this.Ei(h))}else this.Ei(f),c.add(this.kc(f))}for(a=b.iterator;a.next();)b=a.value,c.contains(b)||(b=this.yh(b))&&this.tm(b)}};
function ar(a,b){var c=wq(a,b,!0);c=a.lm(c);null===a.Sb(c)&&Dq(a,c,b);c=wq(a,b,!1);c=a.lm(c);null===a.Sb(c)&&Dq(a,c,b);var d=a.sg(b);if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)c=d[f],null===a.Sb(c)&&Dq(a,c,b)}t.Wp=function(a){if(null===a)return null;var b=this.Mk;a=null!==b?b(a,this):Vq(this,a,!0);Ja(a)&&(qb(a),""!==this.We&&dk(a,this.We,void 0),""!==this.Xe&&dk(a,this.Xe,void 0),""!==this.Kd&&dk(a,this.Kd,[]));return a};
t.ht=function(a){if(null===a)return!1;var b=this.yl;return""===b?!1:xn(a,b)?!0:!1};t.Pi=function(a){if(null!==a){var b=this.ue;if(""!==b&&(b=xn(a,b),void 0!==b)){if(yq(b))return b;v("GroupKey value for node data "+a+" is not a number or a string: "+b)}}};
t.zt=function(a,b){null===b&&(b=void 0);void 0===b||yq(b)||Ba(b,"number or string",Zq,"setGroupKeyForNodeData:key");if(null!==a){var c=this.ue;if(""!==c)if(this.Ab(a)){var d=xn(a,c);d!==b&&(Cq(this,d,a),dk(a,c,b),null===this.Sb(b)&&Dq(this,b,a),Tq(this,"nodeGroupKey",of,c,a,d,b),"string"===typeof c&&this.Fa(a,c))}else dk(a,c,b)}};
Zq.prototype.copyNodeData=function(a){if(null===a)return null;a=X.prototype.copyNodeData.call(this,a);this.$j||""===this.ue||void 0===xn(a,this.ue)||dk(a,this.ue,void 0);return a};
Zq.prototype.setDataProperty=function(a,b,c){E&&(z(a,"object",Zq,"setDataProperty:data"),z(b,"string",Zq,"setDataProperty:propname"),""===b&&v("GraphLinksModel.setDataProperty: property name must not be an empty string when setting "+a+" to "+c));if(this.Ab(a))if(b===this.nodeKeyProperty)this.Bm(a,c);else{if(b===this.nodeCategoryProperty){this.zq(a,c);return}if(b===this.nodeGroupKeyProperty){this.zt(a,c);return}E&&b===this.nodeIsGroupProperty&&v("GraphLinksModel.setDataProperty: property name must not be the nodeIsGroupProperty: "+
b)}else if(this.De(a)){if(b===this.linkFromKeyProperty){Eq(this,a,c,!0);return}if(b===this.linkToKeyProperty){Eq(this,a,c,!1);return}if(b===this.linkFromPortIdProperty){Fq(this,a,c,!0);return}if(b===this.linkToPortIdProperty){Fq(this,a,c,!1);return}if(b===this.linkKeyProperty){this.At(a,c);return}if(b===this.linkCategoryProperty){this.yt(a,c);return}if(b===this.linkLabelKeysProperty){this.Ov(a,c);return}}var d=xn(a,b);d!==c&&(dk(a,b,c),this.rt(a,b,d,c))};t=Zq.prototype;
t.Vj=function(a,b){if(b){var c=this.Ab(a),d=this.De(a),e;for(e in b)"__gohashid"===e||c&&e===this.nodeKeyProperty||d&&e===this.linkKeyProperty||this.setDataProperty(a,e,b[e])}};
t.xq=function(a,b){X.prototype.xq.call(this,a,b);for(var c=this.fb.iterator;c.next();)this.Iv(c.value,a,b);for(c=this.Pf.iterator;c.next();){var d=c.value,e=a,f=b;if(wq(this,d,!0)===e){var g=this.We;dk(d,g,f);Tq(this,"linkFromKey",of,g,d,e,f);"string"===typeof g&&this.Fa(d,g)}wq(this,d,!1)===e&&(g=this.Xe,dk(d,g,f),Tq(this,"linkToKey",of,g,d,e,f),"string"===typeof g&&this.Fa(d,g));g=this.sg(d);if(Array.isArray(g))for(var h=g.length,k=this.Kd,l=0;l<h;l++)g[l]===e&&(g[l]=f,Tq(this,"linkLabelKeys",qf,
k,d,e,f,l,l))}};t.Iv=function(a,b,c){if(this.Pi(a)===b){var d=this.ue;dk(a,d,c);Tq(this,"nodeGroupKey",of,d,a,b,c);"string"===typeof d&&this.Fa(a,d)}};t.cw=function(){X.prototype.cw.call(this);for(var a=this.linkDataArray,b=a.length,c=0;c<b;c++)ar(this,a[c])};
t.xm=function(a){X.prototype.xm.call(this,a);a=this.ra(a);var b=Bq(this,a);if(null!==b){var c=Qa();for(b=b.iterator;b.next();){var d=b.value;if(this.Ab(d)){if(this.Pi(d)===a){var e=this.ue;Tq(this,"nodeGroupKey",of,e,d,a,a);"string"===typeof e&&this.Fa(d,e);c.push(d)}}else if(wq(this,d,!0)===a&&(e=this.We,Tq(this,"linkFromKey",of,e,d,a,a),"string"===typeof e&&this.Fa(d,e),c.push(d)),wq(this,d,!1)===a&&(e=this.Xe,Tq(this,"linkToKey",of,e,d,a,a),"string"===typeof e&&this.Fa(d,e),c.push(d)),e=this.sg(d),
Array.isArray(e))for(var f=e.length,g=this.Kd,h=0;h<f;h++)e[h]===a&&(Tq(this,"linkLabelKeys",qf,g,d,a,a,h,h),c.push(d))}for(b=0;b<c.length;b++)Cq(this,a,c[b]);Ta(c)}};t.wm=function(a){X.prototype.wm.call(this,a);var b=this.Pi(a);null===this.Sb(b)&&Dq(this,b,a)};t.Cq=function(a){X.prototype.Cq.call(this,a);var b=this.Pi(a);Cq(this,b,a)};
t.iv=function(a){if(null===a)return"";var b=this.wj;if(""===b)return"";b=xn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;v("getCategoryForLinkData found a non-string category for "+a+": "+b);return""};Zq.prototype.getLinkCategoryForData=function(a){return this.iv(a)};
Zq.prototype.yt=function(a,b){z(b,"string",Zq,"setCategoryForLinkData:cat");if(null!==a){var c=this.wj;if(""!==c)if(this.De(a)){var d=xn(a,c);void 0===d&&(d="");d!==b&&(dk(a,c,b),Tq(this,"linkCategory",of,c,a,d,b),"string"===typeof c&&this.Fa(a,c))}else dk(a,c,b)}};Zq.prototype.setLinkCategoryForData=function(a,b){this.yt(a,b)};Zq.prototype.ik=function(){return!0};Zq.prototype.jm=function(){return!0};Zq.prototype.jt=function(){return!0};Zq.prototype.Ti=function(){return!0};
na.Object.defineProperties(Zq.prototype,{archetypeNodeData:{configurable:!0,get:function(){return this.ej},set:function(a){var b=this.ej;b!==a&&(null!==a&&z(a,"object",Zq,"archetypeNodeData"),this.ej=a,this.g("archetypeNodeData",b,a))}},linkFromKeyProperty:{configurable:!0,get:function(){return this.We},set:function(a){var b=this.We;b!==a&&(Uq(a,Zq,"linkFromKeyProperty"),this.We=a,this.g("linkFromKeyProperty",b,a))}},linkToKeyProperty:{configurable:!0,get:function(){return this.Xe},
set:function(a){var b=this.Xe;b!==a&&(Uq(a,Zq,"linkToKeyProperty"),this.Xe=a,this.g("linkToKeyProperty",b,a))}},linkFromPortIdProperty:{configurable:!0,get:function(){return this.xj},set:function(a){var b=this.xj;b!==a&&(Uq(a,Zq,"linkFromPortIdProperty"),!E||a!==this.linkFromKeyProperty&&a!==this.linkToKeyProperty||v("linkFromPortIdProperty name must not be the same as the GraphLinksModel.linkFromKeyProperty or linkToKeyProperty: "+a),this.xj=a,this.g("linkFromPortIdProperty",b,a))}},
linkToPortIdProperty:{configurable:!0,get:function(){return this.yj},set:function(a){var b=this.yj;b!==a&&(Uq(a,Zq,"linkToPortIdProperty"),!E||a!==this.linkFromKeyProperty&&a!==this.linkToKeyProperty||v("linkFromPortIdProperty name must not be the same as the GraphLinksModel.linkFromKeyProperty or linkToKeyProperty: "+a),this.yj=a,this.g("linkToPortIdProperty",b,a))}},linkLabelKeysProperty:{configurable:!0,get:function(){return this.Kd},set:function(a){var b=this.Kd;b!==
a&&(Uq(a,Zq,"linkLabelKeysProperty"),this.Kd=a,this.g("linkLabelKeysProperty",b,a))}},linkDataArray:{configurable:!0,get:function(){return this.Rc},set:function(a){var b=this.Rc;if(b!==a){La(a,Zq,"linkDataArray");this.rb.clear();for(var c=a.length,d=0;d<c;d++){var e=a[d];if(!Ja(e)){v("GraphLinksModel.linkDataArray must only contain Objects, not: "+e);return}Nb(e)}this.Rc=a;if(""!==this.linkKeyProperty){d=new F;for(e=0;e<c;e++){var f=a[e],g=this.kc(f);void 0===g?d.add(f):null!==this.rb.K(g)?
d.add(f):this.rb.add(g,f)}for(d=d.iterator;d.next();)e=d.value,this.oq(e),f=this.kc(e),void 0!==f&&this.rb.add(f,e)}d=new H;for(e=0;e<c;e++)d.add(a[e]);this.Pf=d;Tq(this,"linkDataArray",of,"linkDataArray",this,b,a);for(b=0;b<c;b++)ar(this,a[b])}}},linkKeyProperty:{configurable:!0,get:function(){return this.ki},set:function(a){var b=this.ki;if(b!==a){Uq(a,Zq,"linkKeyProperty");this.ki=a;this.rb.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.oq(e),f=this.kc(e));void 0!==f&&this.rb.add(f,e)}this.g("linkKeyProperty",b,a)}}},makeUniqueLinkKeyFunction:{configurable:!0,get:function(){return this.ul},set:function(a){var b=this.ul;b!==a&&(null!==a&&z(a,"function",Zq,"makeUniqueLinkKeyFunction"),this.ul=a,this.g("makeUniqueLinkKeyFunction",b,a))}},copyLinkDataFunction:{configurable:!0,get:function(){return this.Mk},set:function(a){var b=this.Mk;b!==a&&(null!==a&&z(a,"function",Zq,"copyLinkDataFunction"),
this.Mk=a,this.g("copyLinkDataFunction",b,a))}},nodeIsGroupProperty:{configurable:!0,get:function(){return this.yl},set:function(a){var b=this.yl;b!==a&&(Uq(a,Zq,"nodeIsGroupProperty"),this.yl=a,this.g("nodeIsGroupProperty",b,a))}},nodeGroupKeyProperty:{configurable:!0,get:function(){return this.ue},set:function(a){var b=this.ue;b!==a&&(Uq(a,Zq,"nodeGroupKeyProperty"),this.ue=a,this.g("nodeGroupKeyProperty",b,a))}},$j:{configurable:!0,get:function(){return this.hn},
set:function(a){this.hn!==a&&(z(a,"boolean",Zq,"copiesGroupKeyOfNodeData"),this.hn=a)}},linkCategoryProperty:{configurable:!0,get:function(){return this.wj},set:function(a){var b=this.wj;b!==a&&(Uq(a,Zq,"linkCategoryProperty"),this.wj=a,this.g("linkCategoryProperty",b,a))}}});na.Object.defineProperties(Zq,{type:{configurable:!0,get:function(){return"GraphLinksModel"}}});Zq.prototype.setCategoryForLinkData=Zq.prototype.yt;Zq.prototype.getCategoryForLinkData=Zq.prototype.iv;
Zq.prototype.assignAllDataProperties=Zq.prototype.Vj;Zq.prototype.setGroupKeyForNodeData=Zq.prototype.zt;Zq.prototype.getGroupKeyForNodeData=Zq.prototype.Pi;Zq.prototype.isGroupForNodeData=Zq.prototype.ht;Zq.prototype.copyLinkData=Zq.prototype.Wp;Zq.prototype.mergeLinkDataArray=Zq.prototype.Mz;Zq.prototype.removeLinkDataCollection=Zq.prototype.Wz;Zq.prototype.removeLinkData=Zq.prototype.tm;Zq.prototype.addLinkDataCollection=Zq.prototype.ny;Zq.prototype.addLinkData=Zq.prototype.Ei;
Zq.prototype.containsLinkData=Zq.prototype.De;Zq.prototype.makeLinkDataKeyUnique=Zq.prototype.oq;Zq.prototype.findLinkDataForKey=Zq.prototype.yh;Zq.prototype.setKeyForLinkData=Zq.prototype.At;Zq.prototype.getKeyForLinkData=Zq.prototype.kc;Zq.prototype.removeLabelKeyForLinkData=Zq.prototype.Fx;Zq.prototype.addLabelKeyForLinkData=Zq.prototype.Lu;Zq.prototype.setLabelKeysForLinkData=Zq.prototype.Ov;Zq.prototype.getLabelKeysForLinkData=Zq.prototype.sg;Zq.prototype.setToPortIdForLinkData=Zq.prototype.Px;
Zq.prototype.getToPortIdForLinkData=Zq.prototype.qz;Zq.prototype.setFromPortIdForLinkData=Zq.prototype.Lx;Zq.prototype.getFromPortIdForLinkData=Zq.prototype.lz;Zq.prototype.setToKeyForLinkData=Zq.prototype.Ox;Zq.prototype.getToKeyForLinkData=Zq.prototype.pz;Zq.prototype.setFromKeyForLinkData=Zq.prototype.Kx;Zq.prototype.getFromKeyForLinkData=Zq.prototype.kz;Zq.prototype.clear=Zq.prototype.clear;var $q=Object.freeze([]);Zq.className="GraphLinksModel";Xq.GraphLinksModel=Zq;
X.constructGraphLinksModel=X.constructGraphLinksModel=function(){return new Zq};X.initDiagramModel=Mi=function(){return new Zq};function br(a){E&&1<arguments.length&&v("TreeModel constructor can only take one optional argument, the Array of node data.");X.call(this);this.ve="parent";this.kn=!1;this.Ej="parentLinkCategory";void 0!==a&&(this.nodeDataArray=a)}ma(br,X);br.constructGraphLinksModel=X.constructGraphLinksModel;
br.prototype.cloneProtected=function(a){X.prototype.cloneProtected.call(this,a);a.ve=this.ve;a.kn=this.kn;a.Ej=this.Ej};t=br.prototype;t.toString=function(a){void 0===a&&(a=0);if(2<=a)return this.Bq();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.ra(e)+":"+Wa(e)}}return b};
t.yk=function(){var a=X.prototype.yk.call(this),b="";"parent"!==this.nodeParentKeyProperty&&"string"===typeof this.nodeParentKeyProperty&&(b+=',\n "nodeParentKeyProperty": '+this.quote(this.nodeParentKeyProperty));return a+b};t.uq=function(a){X.prototype.uq.call(this,a);a.nodeParentKeyProperty&&(this.nodeParentKeyProperty=a.nodeParentKeyProperty)};t.Fq=function(a){Oq(this,a,"nodeParentKeyProperty");return X.prototype.Fq.call(this,a)};t.lm=function(a){return a};
t.Ri=function(a){if(null!==a){var b=this.ve;if(""!==b&&(b=xn(a,b),void 0!==b)){if(yq(b))return b;v("ParentKey value for node data "+a+" is not a number or a string: "+b)}}};
t.Ke=function(a,b){null===b&&(b=void 0);void 0===b||yq(b)||Ba(b,"number or string",br,"setParentKeyForNodeData:key");if(null!==a){var c=this.ve;if(""!==c)if(b=this.lm(b),this.Ab(a)){var d=xn(a,c);d!==b&&(Cq(this,d,a),dk(a,c,b),null===this.Sb(b)&&Dq(this,b,a),Tq(this,"nodeParentKey",of,c,a,d,b),"string"===typeof c&&this.Fa(a,c))}else dk(a,c,b)}};
t.jv=function(a){if(null===a)return"";var b=this.Ej;if(""===b)return"";b=xn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;v("getParentLinkCategoryForNodeData found a non-string category for "+a+": "+b);return""};br.prototype.getLinkCategoryForData=function(a){return this.jv(a)};
br.prototype.Pv=function(a,b){z(b,"string",br,"setParentLinkCategoryForNodeData:cat");if(null!==a){var c=this.Ej;if(""!==c)if(this.Ab(a)){var d=xn(a,c);void 0===d&&(d="");d!==b&&(dk(a,c,b),Tq(this,"parentLinkCategory",of,c,a,d,b),"string"===typeof c&&this.Fa(a,c))}else dk(a,c,b)}};br.prototype.setLinkCategoryForData=function(a,b){this.Pv(a,b)};
br.prototype.copyNodeData=function(a){if(null===a)return null;a=X.prototype.copyNodeData.call(this,a);this.ak||""===this.ve||void 0===xn(a,this.ve)||dk(a,this.ve,void 0);return a};
br.prototype.setDataProperty=function(a,b,c){E&&(z(a,"object",br,"setDataProperty:data"),z(b,"string",br,"setDataProperty:propname"),""===b&&v("TreeModel.setDataProperty: property name must not be an empty string when setting "+a+" to "+c));if(this.Ab(a))if(b===this.nodeKeyProperty)this.Bm(a,c);else{if(b===this.nodeCategoryProperty){this.zq(a,c);return}if(b===this.nodeParentKeyProperty){this.Ke(a,c);return}}var d=xn(a,b);d!==c&&(dk(a,b,c),this.rt(a,b,d,c))};t=br.prototype;
t.xq=function(a,b){X.prototype.xq.call(this,a,b);for(var c=this.fb.iterator;c.next();)this.Iv(c.value,a,b)};t.Iv=function(a,b,c){if(this.Ri(a)===b){var d=this.ve;dk(a,d,c);Tq(this,"nodeParentKey",of,d,a,b,c);"string"===typeof d&&this.Fa(a,d)}};
t.xm=function(a){X.prototype.xm.call(this,a);a=this.ra(a);var b=Bq(this,a);if(null!==b){var c=Qa();for(b=b.iterator;b.next();){var d=b.value;if(this.Ab(d)&&this.Ri(d)===a){var e=this.ve;Tq(this,"nodeParentKey",of,e,d,a,a);"string"===typeof e&&this.Fa(d,e);c.push(d)}}for(b=0;b<c.length;b++)Cq(this,a,c[b]);Ta(c)}};t.wm=function(a){X.prototype.wm.call(this,a);var b=this.Ri(a);b=this.lm(b);null===this.Sb(b)&&Dq(this,b,a)};t.Cq=function(a){X.prototype.Cq.call(this,a);var b=this.Ri(a);Cq(this,b,a)};
t.km=function(){return!0};t.jt=function(){return!0};
na.Object.defineProperties(br.prototype,{nodeParentKeyProperty:{configurable:!0,get:function(){return this.ve},set:function(a){var b=this.ve;b!==a&&(Uq(a,br,"nodeParentKeyProperty"),this.ve=a,this.g("nodeParentKeyProperty",b,a))}},ak:{configurable:!0,get:function(){return this.kn},set:function(a){this.kn!==a&&(z(a,"boolean",br,"copiesParentKeyOfNodeData"),this.kn=a)}},parentLinkCategoryProperty:{configurable:!0,get:function(){return this.Ej},set:function(a){var b=
this.Ej;b!==a&&(Uq(a,br,"parentLinkCategoryProperty"),this.Ej=a,this.g("parentLinkCategoryProperty",b,a))}},linkCategoryProperty:{configurable:!0,get:function(){return this.parentLinkCategoryProperty},set:function(a){this.parentLinkCategoryProperty=a}}});na.Object.defineProperties(br,{type:{configurable:!0,get:function(){return"TreeModel"}}});br.prototype.setParentLinkCategoryForNodeData=br.prototype.Pv;br.prototype.getParentLinkCategoryForNodeData=br.prototype.jv;
br.prototype.setParentKeyForNodeData=br.prototype.Ke;br.prototype.getParentKeyForNodeData=br.prototype.Ri;br.className="TreeModel";Xq.TreeModel=br;function cr(){0<arguments.length&&Da(cr);Ni.call(this);this.Bw=this.Dn=this.Zb=0;this.rr=360;this.Aw=dr;this.kj=0;this.mw=new J;this.cr=this.Td=0;this.Ms=new er;this.Rt=this.Dj=0;this.ay=600;this.Yo=NaN;this.Wm=1;this.Ap=0;this.Pl=360;this.Db=dr;this.M=gr;this.Tc=hr;this.Pc=$p;this.bf=6;this.Io=ir}ma(cr,Ni);
cr.prototype.cloneProtected=function(a){Ni.prototype.cloneProtected.call(this,a);a.Yo=this.Yo;a.Wm=this.Wm;a.Ap=this.Ap;a.Pl=this.Pl;a.Db=this.Db;a.M=this.M;a.Tc=this.Tc;a.Pc=this.Pc;a.bf=this.bf;a.Io=this.Io};
cr.prototype.hb=function(a){if(a.classType===cr)if(a===jr||a===kr||a===lr||a===mr||a===hr)this.sorting=a;else if(a===nr||a===or||a===gr||a===pr)this.direction=a;else if(a===qr||a===rr||a===dr||a===sr)this.arrangement=a;else{if(a===tr||a===ir)this.nodeDiameterFormula=a}else Ni.prototype.hb.call(this,a)};cr.prototype.createNetwork=function(){return new ur(this)};
cr.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 F;b.addAll(a.iterator);a=new F;var c=new F;var d=this.sort(b);var e,f,g=this.cr;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===sr&&k===tr?h=dr:h===sr&&k!==tr&&(h=this.arrangement);if((this.direction===nr||this.direction===or)&&this.sorting!==hr){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===nr?(this.arrangement===sr&&a.reverse(),d=new F,d.addAll(a),
d.addAll(c)):(this.arrangement===sr&&c.reverse(),d=new F,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===gr?1:-1)/k,u=d.O(q).diameter;isNaN(u)&&(u=vr(d.O(q),r));360>p&&(0===q||q===d.length-1)&&(u/=2);e+=u;f++}if(isNaN(l)||h===sr){isNaN(b)&&(b=6);if(h!==dr&&h!==sr){f=-Infinity;for(g=0;g<k;g++)q=d.O(g),e=d.O(g===k-1?0:g+1),isNaN(q.diameter)&&vr(q,0),isNaN(e.diameter)&&vr(e,0),f=Math.max(f,(q.diameter+e.diameter)/2);g=f+b;h===qr?l=(f+b)/(2*Math.PI/k):
l=wr(this,g*(360<=p?k:k-1),m,n*Math.PI/180,p*Math.PI/180)}else l=wr(this,e+(360<=p?k:k-1)*(h!==sr?b:1.6*b),m,n*Math.PI/180,p*Math.PI/180);f=l*m}else if(f=l*m,q=xr(this,l,f,n*Math.PI/180,p*Math.PI/180),isNaN(b)){if(h===dr||h===sr)b=(q-e)/(360<=p?k:k-1)}else if(h===dr||h===sr)q=(q-e)/(360<=p?k:k-1),q<b?(l=wr(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)&&vr(r,0),isNaN(u.diameter)&&vr(u,0),g=Math.max(g,
(r.diameter+u.diameter)/2);g+=b;e=wr(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.Aw=h;this.Zb=l;this.Dn=m;this.Bw=n;this.rr=p;this.kj=b;this.Td=f;this.cr=g;b=d;d=this.Aw;h=this.Zb;l=this.Bw;m=this.rr;n=this.kj;p=this.Td;k=this.cr;if(this.direction!==nr&&this.direction!==or||d!==sr)if(this.direction===nr||this.direction===or){g=0;switch(d){case rr:g=180*yr(this,h,p,l,k)/Math.PI;break;case dr:k=b=0;g=a.first();null!==g&&(b=vr(g,Math.PI/2));g=c.first();
null!==g&&(k=vr(g,Math.PI/2));g=180*yr(this,h,p,l,n+(b+k)/2)/Math.PI;break;case qr:g=m/b.length}if(this.direction===nr){switch(d){case rr:zr(this,a,l,pr);break;case dr:Ar(this,a,l,pr);break;case qr:Br(this,a,m/2,l,pr)}switch(d){case rr:zr(this,c,l+g,gr);break;case dr:Ar(this,c,l+g,gr);break;case qr:Br(this,c,m/2,l+g,gr)}}else{switch(d){case rr:zr(this,c,l,pr);break;case dr:Ar(this,c,l,pr);break;case qr:Br(this,c,m/2,l,pr)}switch(d){case rr:zr(this,a,l+g,gr);break;case dr:Ar(this,a,l+g,gr);break;case qr:Br(this,
a,m/2,l+g,gr)}}}else switch(d){case rr:zr(this,b,l,this.direction);break;case dr:Ar(this,b,l,this.direction);break;case qr:Br(this,b,m,l,this.direction);break;case sr:Cr(this,b,m,l,this.direction)}else Cr(this,b,m,l-m/2,gr)}this.updateParts();this.network=null;this.isValidLayout=!0};
function Br(a,b,c,d,e){var f=a.rr,g=a.Zb;a=a.Td;d=d*Math.PI/180;c=c*Math.PI/180;for(var h=b.length,k=0;k<h;k++){var l=d+(e===gr?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 Ar(a,b,c,d){var e=a.Zb,f=a.Td,g=a.kj;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)&&vr(l,0);isNaN(m.diameter)&&vr(m,0);l=yr(a,e,f,d===gr?c:-c,(l.diameter+m.diameter)/2+g);c+=d===gr?l:-l}}
function zr(a,b,c,d){var e=a.Zb,f=a.Td,g=a.cr;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=yr(a,e,f,d===gr?c:-c,g);c+=d===gr?l:-l}}function Cr(a,b,c,d,e){var f=a.rr;a.Dj=0;a.Ms=new er;if(360>c){for(f=d+(e===gr?f:-f);0>f;)f+=360;f%=360;180<f&&(f-=360);f*=Math.PI/180;a.Rt=f;Dr(a,b,c,d,e)}else Er(a,b,c,d,e);a.Ms.commit(b)}
function Er(a,b,c,d,e){var f=a.Zb,g=a.kj,h=a.Dn,k=f*Math.cos(d*Math.PI/180),l=a.Td*Math.sin(d*Math.PI/180),m=b.Oa();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;Fr(a,k,l,m,n,e,f)||Gr(a,k,l,m,n,e,f);k=f.x;l=f.y}J.free(f);a.Dj++;if(!(23<a.Dj)){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===gr?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.Ms.compare(g,m);1<Math.abs(g)&&(a.Zb=8>a.Dj?a.Zb-g/(2*Math.PI):5>m.length&&10<g?a.Zb/2:a.Zb-(0<g?1.7:-2.3),a.Td=a.Zb*h,Er(a,b,c,d,e))}}}
function Dr(a,b,c,d,e){for(var f=a.Zb,g=a.Td,h=a.Dn,k=f*Math.cos(d*Math.PI/180),l=g*Math.sin(d*Math.PI/180),m=J.alloc(),n=b.Oa(),p=0;p<n.length;p++){n[p].centerX=k;n[p].centerY=l;if(p>=n.length-1)break;Fr(a,k,l,n,p,e,m)||Gr(a,k,l,n,p,e,m);k=m.x;l=m.y}J.free(m);a.Dj++;if(!(23<a.Dj)){k=Math.atan2(l,k);k=e===gr?a.Rt-k:k-a.Rt;k=Math.abs(k)<Math.abs(k-2*Math.PI)?k:k-2*Math.PI;f=k*(f+g)/2;g=a.Ms;if(Math.abs(f)<Math.abs(g.fm))for(g.fm=f,g.zk=[],g.Fm=[],k=0;k<n.length;k++)g.zk[k]=n[k].bounds.x,g.Fm[k]=n[k].bounds.y;
1<Math.abs(f)&&(a.Zb=8>a.Dj?a.Zb-f/(2*Math.PI):a.Zb-(0<f?1.7:-2.3),a.Td=a.Zb*h,Dr(a,b,c,d,e))}}function Fr(a,b,c,d,e,f,g){var h=a.Zb,k=a.Td,l=0;a=(d[e].width+d[e+1].width)/2+a.kj;var m=!1;if(0<=c!==(f===gr)){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 Gr(a,b,c,d,e,f,g){var h=a.Zb,k=a.Td,l=0;a=(d[e].height+d[e+1].height)/2+a.kj;d=!1;if(0<=b!==(f===gr)){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}cr.prototype.commitLayout=function(){this.commitNodes();this.isRouting&&this.commitLinks()};
cr.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.Td);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.bc(),a=this.group.position.copy(),c=this.group.location.copy(),b=b.Zd(c.Zd(a)),this.group.move(b),this.mw=b.Zd(a))};
cr.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()};function xr(a,b,c,d,e){var f=a.ay;if(.001>Math.abs(a.Dn-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 wr(a,b,c,d,e){return b/(void 0!==d&&void 0!==e?xr(a,1,c,d,e):xr(a,1,c))}function yr(a,b,c,d,e){if(.001>Math.abs(a.Dn-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}}
cr.prototype.sort=function(a){switch(this.sorting){case lr:break;case mr:a.reverse();break;case jr:a.sort(this.comparer);break;case kr:a.sort(this.comparer);a.reverse();break;case hr:for(var b=[],c=0;c<a.length;c++)b.push(0);c=new F;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 F;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],x=a[l],y=0,A=0;A<g.length;A++){var C=f[g[A]],G=f[h[A]];if(C<G){var I=C;C=G}else I=G;if(I<u&&u<=C)for(G=0;G<x.length;G++){var O=x[G];0>b.indexOf(O)||I<f[O]&&f[O]<C||I===f[O]||C===f[O]||y++}else for(G=0;G<x.length;G++)O=x[G],0>b.indexOf(O)||I<f[O]&&f[O]<C&&I!==f[O]&&
C!==f[O]&&y++}x=y;for(A=y=0;A<a[l].length;A++)I=b.indexOf(a[l][A]),0<=I&&(I=Math.abs(u-(I>=u?I+1:I)),y+=I<b.length+1-I?I:b.length+1-I);for(A=0;A<g.length;A++)I=f[g[A]],C=f[h[A]],I>=u&&I++,C>=u&&C++,I>C&&(G=C,C=I,I=G),C-I<(b.length+2)/2===(I<u&&u<=C)&&y++;if(x<m||x===m&&y<n)m=x,n=y,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(cr.prototype,{radius:{configurable:!0,get:function(){return this.Yo},set:function(a){this.Yo!==a&&(z(a,"number",cr,"radius"),0<a||isNaN(a))&&(this.Yo=a,this.C())}},aspectRatio:{configurable:!0,get:function(){return this.Wm},set:function(a){this.Wm!==a&&(z(a,"number",cr,"aspectRatio"),0<a&&(this.Wm=a,this.C()))}},startAngle:{configurable:!0,get:function(){return this.Ap},set:function(a){this.Ap!==a&&(z(a,"number",cr,"startAngle"),
this.Ap=a,this.C())}},sweepAngle:{configurable:!0,get:function(){return this.Pl},set:function(a){this.Pl!==a&&(z(a,"number",cr,"sweepAngle"),0<a&&360>=a?this.Pl=a:this.Pl=360,this.C())}},arrangement:{configurable:!0,get:function(){return this.Db},set:function(a){this.Db!==a&&(tb(a,cr,cr,"arrangement"),a===sr||a===dr||a===rr||a===qr)&&(this.Db=a,this.C())}},direction:{configurable:!0,get:function(){return this.M},set:function(a){this.M!==a&&(tb(a,cr,cr,"direction"),
a===gr||a===pr||a===nr||a===or)&&(this.M=a,this.C())}},sorting:{configurable:!0,get:function(){return this.Tc},set:function(a){this.Tc!==a&&(tb(a,cr,cr,"sorting"),a===lr||a===mr||a===jr||kr||a===hr)&&(this.Tc=a,this.C())}},comparer:{configurable:!0,get:function(){return this.Pc},set:function(a){this.Pc!==a&&(z(a,"function",cr,"comparer"),this.Pc=a,this.C())}},spacing:{configurable:!0,get:function(){return this.bf},set:function(a){this.bf!==a&&(z(a,"number",
cr,"spacing"),this.bf=a,this.C())}},nodeDiameterFormula:{configurable:!0,get:function(){return this.Io},set:function(a){this.Io!==a&&(tb(a,cr,cr,"nodeDiameterFormula"),a===ir||a===tr)&&(this.Io=a,this.C())}},actualXRadius:{configurable:!0,get:function(){return this.Zb}},actualYRadius:{configurable:!0,get:function(){return this.Td}},actualSpacing:{configurable:!0,get:function(){return this.kj}},actualCenter:{configurable:!0,get:function(){return this.mw}}});
var dr=new D(cr,"ConstantSpacing",0),rr=new D(cr,"ConstantDistance",1),qr=new D(cr,"ConstantAngle",2),sr=new D(cr,"Packed",3),gr=new D(cr,"Clockwise",4),pr=new D(cr,"Counterclockwise",5),nr=new D(cr,"BidirectionalLeft",6),or=new D(cr,"BidirectionalRight",7),lr=new D(cr,"Forwards",8),mr=new D(cr,"Reverse",9),jr=new D(cr,"Ascending",10),kr=new D(cr,"Descending",11),hr=new D(cr,"Optimized",12),ir=new D(cr,"Pythagorean",13),tr=new D(cr,"Circular",14);cr.className="CircularLayout";cr.ConstantSpacing=dr;
cr.ConstantDistance=rr;cr.ConstantAngle=qr;cr.Packed=sr;cr.Clockwise=gr;cr.Counterclockwise=pr;cr.BidirectionalLeft=nr;cr.BidirectionalRight=or;cr.Forwards=lr;cr.Reverse=mr;cr.Ascending=jr;cr.Descending=kr;cr.Optimized=hr;cr.Pythagorean=ir;cr.Circular=tr;function er(){this.fm=-Infinity;this.Fm=this.zk=null}
er.prototype.compare=function(a,b){if(0<a&&0>this.fm||Math.abs(a)<Math.abs(this.fm)&&!(0>a&&0<this.fm))for(this.fm=a,this.zk=[],this.Fm=[],a=0;a<b.length;a++)this.zk[a]=b[a].bounds.x,this.Fm[a]=b[a].bounds.y};er.prototype.commit=function(a){if(null!==this.zk&&null!==this.Fm)for(var b=0;b<this.zk.length;b++){var c=a.O(b);c.x=this.zk[b];c.y=this.Fm[b]}};er.className="VertexArrangement";function ur(a){Rp.call(this,a)}ma(ur,Rp);ur.prototype.createVertex=function(){return new Hr(this)};
ur.prototype.createEdge=function(){return new Ir(this)};ur.className="CircularNetwork";function Hr(a){Up.call(this,a);this.L=this.jj=NaN}ma(Hr,Up);
function vr(a,b){var c=a.network;if(null===c)return NaN;c=c.layout;if(null===c)return NaN;if(c.arrangement===sr)if(c.nodeDiameterFormula===tr)a.jj=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.jj=Math.min(a.height/c,a.width/b)}else a.jj=c.nodeDiameterFormula===tr?Math.max(a.width,a.height):Math.sqrt(a.width*a.width+a.height*a.height);return a.jj}
na.Object.defineProperties(Hr.prototype,{diameter:{configurable:!0,get:function(){return this.jj},set:function(a){this.jj!==a&&(z(a,"number",Hr,"diameter"),this.jj=a)}},actualAngle:{configurable:!0,get:function(){return this.L},set:function(a){this.L!==a&&(z(a,"number",Hr,"actualAngle"),this.L=a)}}});Hr.className="CircularVertex";function Ir(a){Vp.call(this,a)}ma(Ir,Vp);Ir.className="CircularEdge";
function Jr(){0<arguments.length&&Da(Jr);Ni.call(this);this.qh=null;this.eo=0;this.yd=(new Zb(100,100)).freeze();this.Vm=!1;this.af=!0;this.Zc=!1;this.vl=100;this.Gn=1;this.Mf=1E3;this.zo=10;this.Zo=Math;this.Uk=.05;this.Tk=50;this.Rk=150;this.Sk=0;this.tn=10;this.sn=5}ma(Jr,Ni);
Jr.prototype.cloneProtected=function(a){Ni.prototype.cloneProtected.call(this,a);a.yd.assign(this.yd);a.Vm=this.Vm;a.af=this.af;a.Zc=this.Zc;a.vl=this.vl;a.Gn=this.Gn;a.Mf=this.Mf;a.zo=this.zo;a.Zo=this.Zo;a.Uk=this.Uk;a.Tk=this.Tk;a.Rk=this.Rk;a.Sk=this.Sk;a.tn=this.tn;a.sn=this.sn};Jr.prototype.createNetwork=function(){return new Kr(this)};
Jr.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.Xp();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.Nu();this.eo=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.vd=e.vertexes.count;e.Ch=1;e.Zj=null;e.Je=null}Lr(this,0,a)}this.network=b;c.reset();E&&w(b,Kr,Jr,"arrangeConnectedGraphs:singletons");d=this.arrangementSpacing;for(var f=c.count,g=!0,h=e=0,k=Qa(),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=Mr(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=Mr(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);Ta(k);for(c.reset();c.next();){d=c.value;for(e=d.vertexes.iterator;e.next();)b.uh(e.value);for(d=d.edges.iterator;d.next();)b.Tj(d.value)}}Nr(this,a);this.updateParts()}this.vl=a;this.network=null;this.isValidLayout=
!0};Jr.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.Kc(c)&&(a++,2<a))return!0;if(10<b)break;b++}return!1};Jr.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.Lc(d.bounds)}return b};
function Or(a,b,c){E&&(B(b,Jr,"computeClusterLayoutIterations:level"),B(c,Jr,"computeClusterLayoutIterations:maxiter"));return Math.max(Math.min(a.network.vertexes.count,c*(b+1)/11),10)}
function Lr(a,b,c){E&&(B(b,Jr,"layoutClusters:level"),B(c,Jr,"layoutClusters:maxiter"));if(Pr(a,b)){var d=a.Mf;a.Mf*=1+1/(b+1);var e=Qr(a,b),f=Math.max(0,Or(a,b,c));a.maxIterations+=f;Lr(a,b+1,c);Nr(a,f);Rr(a,e,b);c=e.vertexes.Oa();c.sort(function(a,b){return null===a||null===b||a===b?0:b.vd-a.vd});for(e=0;e<c.length;e++)Sr(a,c[e],b);a.Mf=d}}
function Pr(a,b){E&&B(b,Jr,"hasClusters:level");if(10<b||3>a.network.vertexes.count)return!1;a.qh=a.network.vertexes.Oa();a=a.qh;a.sort(function(a,b){return null===a||null===b||a===b?0:b.vd-a.vd});for(b=a.length-1;0<=b&&1>=a[b].vd;)b--;return 1<a.length-b}
function Qr(a,b){E&&B(b,Jr,"pushSubNetwork:level");for(var c=a.network,d=new Kr(a),e=0;e<a.qh.length;e++){var f=a.qh[e];if(1<f.vd){d.uh(f);var g=new Tr;g.Gt=f.vd;g.Ht=f.width;g.Ft=f.height;g.hw=f.focus.x;g.iw=f.focus.y;null===f.Je&&(f.Je=new F);f.Je.add(g);f.Lv=f.Je.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.Tj(h):e.network===d?(h=e.Zj,null===h&&(h=new F,e.Zj=h),h.add(g),e.vd--,e.Ch+=g.Ch):g.network===d&&(h=g.Zj,null===
h&&(h=new F,g.Zj=h),h.add(e),g.vd--,g.Ch+=e.Ch)}for(e=d.edges.iterator;e.next();)f=e.value,f.length*=Math.max(1,K.sqrt((f.fromVertex.Ch+f.toVertex.Ch)/(4*b+1)));for(b=d.vertexes.iterator;b.next();){e=b.value;var k=e.Zj;if(null!==k&&0<k.count&&(g=e.Je.O(e.Je.count-1).Gt-e.vd,!(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 Rr(a,b,c){E&&(w(b,Kr,Jr,"popNetwork:oldnet"),B(c,Jr,"popNetwork:level"));for(c=a.network.vertexes.iterator;c.next();){var d=c.value;d.network=b;if(null!==d.Je){var e=d.Je.O(d.Lv);d.vd=e.Gt;var f=e.hw,g=e.iw;d.bounds=new L(d.centerX-f,d.centerY-g,e.Ht,e.Ft);d.focus=new J(f,g);d.Lv--}}for(c=a.network.edges.iterator;c.next();)c.value.network=b;a.network=b}
function Sr(a,b,c){E&&(w(b,Ur,Jr,"surroundNode:oldnet"),B(c,Jr,"surroundNode:level"));var d=b.Zj;if(null!==d&&0!==d.count){c=b.centerX;var e=b.centerY,f=b.width,g=b.height;null!==b.Je&&0<b.Je.count&&(g=b.Je.O(0),f=g.Ht,g=g.Ft);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.vd?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.vd||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 Mr(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}Jr.prototype.Nu=function(){if(this.comments)for(var a=this.network.vertexes.iterator;a.next();)this.addComments(a.value)};
Jr.prototype.addComments=function(a){var b=a.node;if(null!==b)for(b=b.ev();b.next();){var c=b.value;if("Comment"===c.category&&c.isVisible()){var d=this.network.Ni(c);null===d&&(d=this.network.Wl(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.kk(a,d,null));c.length=this.defaultCommentSpringLength}}};
function Vr(a,b){E&&(w(a,Ur,Jr,"getNodeDistance:vertexA"),w(b,Ur,Jr,"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 Nr(a,b){E&&B(b,Jr,"performIterations:num");a.qh=null;for(b=a.eo+b;a.eo<b&&(a.eo++,Wr(a)););a.qh=null}
function Wr(a){null===a.qh&&(a.qh=a.network.vertexes.Oa());var b=a.qh;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.Mf;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=Vr(g,p);1>r?(d=a.randomNumberGenerator,null===d&&(a.randomNumberGenerator=d=new Xr),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=Vr(c,f),1>n?(n=a.randomNumberGenerator,null===n&&(a.randomNumberGenerator=n=new Xr),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}Jr.prototype.moveFixedVertex=function(){};Jr.prototype.commitLayout=function(){this.Qv();this.commitNodes();this.isRouting&&this.commitLinks()};Jr.prototype.Qv=function(){if(this.setsPortSpots)for(var a=this.network.edges.iterator;a.next();){var b=a.value.link;null!==b&&(b.fromSpot=Qd,b.toSpot=Qd)}};
Jr.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)};Jr.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()};
Jr.prototype.springStiffness=function(a){a=a.stiffness;return isNaN(a)?this.Uk:a};Jr.prototype.springLength=function(a){a=a.length;return isNaN(a)?this.Tk:a};Jr.prototype.electricalCharge=function(a){a=a.charge;return isNaN(a)?this.Rk:a};Jr.prototype.electricalFieldX=function(){return 0};Jr.prototype.electricalFieldY=function(){return 0};Jr.prototype.gravitationalMass=function(a){a=a.mass;return isNaN(a)?this.Sk:a};Jr.prototype.gravitationalFieldX=function(){return 0};
Jr.prototype.gravitationalFieldY=function(){return 0};Jr.prototype.isFixed=function(a){return a.isFixed};
na.Object.defineProperties(Jr.prototype,{currentIteration:{configurable:!0,get:function(){return this.eo}},arrangementSpacing:{configurable:!0,get:function(){return this.yd},set:function(a){w(a,Zb,Jr,"arrangementSpacing");this.yd.A(a)||(this.yd.assign(a),this.C())}},arrangesToOrigin:{configurable:!0,get:function(){return this.Vm},set:function(a){this.Vm!==a&&(z(a,"boolean",Jr,"arrangesToOrigin"),this.Vm=a,this.C())}},setsPortSpots:{configurable:!0,
get:function(){return this.af},set:function(a){this.af!==a&&(z(a,"boolean",Jr,"setsPortSpots"),this.af=a,this.C())}},comments:{configurable:!0,get:function(){return this.Zc},set:function(a){this.Zc!==a&&(z(a,"boolean",Jr,"comments"),this.Zc=a,this.C())}},maxIterations:{configurable:!0,get:function(){return this.vl},set:function(a){this.vl!==a&&(z(a,"number",Jr,"maxIterations"),0<=a&&(this.vl=a,this.C()))}},epsilonDistance:{configurable:!0,get:function(){return this.Gn},
set:function(a){this.Gn!==a&&(z(a,"number",Jr,"epsilonDistance"),0<a&&(this.Gn=a,this.C()))}},infinityDistance:{configurable:!0,get:function(){return this.Mf},set:function(a){this.Mf!==a&&(z(a,"number",Jr,"infinityDistance"),1<a&&(this.Mf=a,this.C()))}},moveLimit:{configurable:!0,get:function(){return this.zo},set:function(a){this.zo!==a&&(z(a,"number",Jr,"moveLimit"),1<a&&(this.zo=a,this.C()))}},randomNumberGenerator:{configurable:!0,get:function(){return this.Zo},
set:function(a){this.Zo!==a&&(null!==a&&"function"!==typeof a.random&&v('ForceDirectedLayout.randomNumberGenerator must have a "random()" function on it: '+a),this.Zo=a)}},defaultSpringStiffness:{configurable:!0,get:function(){return this.Uk},set:function(a){this.Uk!==a&&(z(a,"number",Jr,"defaultSpringStiffness"),this.Uk=a,this.C())}},defaultSpringLength:{configurable:!0,get:function(){return this.Tk},set:function(a){this.Tk!==a&&(z(a,"number",Jr,"defaultSpringLength"),
this.Tk=a,this.C())}},defaultElectricalCharge:{configurable:!0,get:function(){return this.Rk},set:function(a){this.Rk!==a&&(z(a,"number",Jr,"defaultElectricalCharge"),this.Rk=a,this.C())}},defaultGravitationalMass:{configurable:!0,get:function(){return this.Sk},set:function(a){this.Sk!==a&&(z(a,"number",Jr,"defaultGravitationalMass"),this.Sk=a,this.C())}},defaultCommentSpringLength:{configurable:!0,get:function(){return this.tn},set:function(a){this.tn!==
a&&(z(a,"number",Jr,"defaultCommentSpringLength"),this.tn=a,this.C())}},defaultCommentElectricalCharge:{configurable:!0,get:function(){return this.sn},set:function(a){this.sn!==a&&(z(a,"number",Jr,"defaultCommentElectricalCharge"),this.sn=a,this.C())}}});Jr.className="ForceDirectedLayout";function Tr(){this.iw=this.hw=this.Ft=this.Ht=this.Gt=0}Tr.className="ForceDirectedSubnet";function Kr(a){Rp.call(this,a)}ma(Kr,Rp);Kr.prototype.createVertex=function(){return new Ur(this)};
Kr.prototype.createEdge=function(){return new Yr(this)};Kr.className="ForceDirectedNetwork";function Ur(a){Up.call(this,a);this.Na=!1;this.Wb=this.L=NaN;this.Ch=this.vd=this.Ma=this.ca=0;this.Je=this.Zj=null;this.Lv=0}ma(Ur,Up);
na.Object.defineProperties(Ur.prototype,{isFixed:{configurable:!0,get:function(){return this.Na},set:function(a){this.Na!==a&&(z(a,"boolean",Ur,"isFixed"),this.Na=a)}},charge:{configurable:!0,get:function(){return this.L},set:function(a){this.L!==a&&(z(a,"number",Ur,"charge"),this.L=a)}},mass:{configurable:!0,get:function(){return this.Wb},set:function(a){this.Wb!==a&&(z(a,"number",Ur,"mass"),this.Wb=a)}},forceX:{configurable:!0,get:function(){return this.ca},
set:function(a){this.ca!==a&&(z(a,"number",Ur,"forceX"),this.ca=a)}},forceY:{configurable:!0,get:function(){return this.Ma},set:function(a){this.Ma!==a&&(z(a,"number",Ur,"forceY"),this.Ma=a)}}});Ur.className="ForceDirectedVertex";function Yr(a){Vp.call(this,a);this.l=this.w=NaN}ma(Yr,Vp);
na.Object.defineProperties(Yr.prototype,{stiffness:{configurable:!0,get:function(){return this.w},set:function(a){this.w!==a&&(z(a,"number",Yr,"stiffness"),this.w=a)}},length:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(z(a,"number",Yr,"length"),this.l=a)}}});Yr.className="ForceDirectedEdge";
function Xr(){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()}Xr.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};Xr.className="RandomNumberGenerator";
function Zr(){0<arguments.length&&Da(Zr);Ni.call(this);this.Yb=this.me=25;this.M=0;this.Pk=$r;this.ql=as;this.gl=bs;this.uj=4;this.Bk=cs;this.bg=7;this.af=!0;this.ko=4;this.Ia=this.Vr=this.Ba=-1;this.qd=this.uo=0;this.La=this.nd=this.od=this.Jd=this.hc=null;this.Eo=0;this.Do=this.zj=null;this.Nd=0;this.Fo=null;this.ow=new J;this.se=[];this.se.length=100}ma(Zr,Ni);
Zr.prototype.cloneProtected=function(a){Ni.prototype.cloneProtected.call(this,a);a.me=this.me;a.Yb=this.Yb;a.M=this.M;a.Pk=this.Pk;a.ql=this.ql;a.gl=this.gl;a.uj=this.uj;a.Bk=this.Bk;a.bg=this.bg;a.af=this.af;a.ko=this.ko};
Zr.prototype.hb=function(a){a.classType===Zr?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):Ni.prototype.hb.call(this,a)};Zr.prototype.createNetwork=function(){return new ds(this)};
Zr.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.Vr=-1;this.qd=this.uo=0;this.Fo=this.Do=this.zj=null;for(a=0;a<this.se.length;a++)this.se[a]=null;if(0<this.network.vertexes.count){this.network.Xp();this.cycleRemoveOption!==es&&this.removeCycles();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);this.cycleRemoveOption===es&&this.removeCycles();a=this.network;for(var b=[],c=a.edges.iterator;c.next();){var d=c.value;d.valid=!1;b.push(d)}for(c=0;c<b.length;c++){d=b[c];var e=d.fromVertex,f=d.toVertex;if(!d.valid&&(null!==e.node&&null!==f.node||e.layer!==f.layer)){var g=0,h=0,k=0,l=0;if(null!==d.link){h=d.link;if(null===h)continue;var m=e.node;g=f.node;if(null===m||null===g)continue;var n=h.fromNode;
k=h.toNode;var p=h.fromPort;h=h.toPort;if(d.rev){l=n;var q=p;n=k;p=h;k=l;h=q}var r=e.focus;l=f.focus;var u=d.rev?f.bounds:e.bounds;q=J.alloc();m!==n?u.o()&&n.isVisible()?n.actualBounds.o()?(n.rf(p,qd,q),q.x+=n.actualBounds.x-u.x,q.y+=n.actualBounds.y-u.y):(n.rf(p,qd,q),q.o()||q.assign(r)):q.assign(r):u.o()?(n.rf(p,qd,q),q.o()||q.assign(r)):q.assign(r);n=d.rev?e.bounds:f.bounds;m=J.alloc();g!==k?n.o()&&k.isVisible()?k.actualBounds.o()?(k.rf(h,qd,m),m.x+=k.actualBounds.x-n.x,m.y+=k.actualBounds.y-n.y):
(k.rf(h,qd,m),m.o()||m.assign(l)):m.assign(l):n.o()?(k.rf(h,qd,m),m.o()||m.assign(l)):m.assign(l);90===this.M||270===this.M?(g=Math.round((q.x-r.x)/this.Yb),k=q.x,h=Math.round((m.x-l.x)/this.Yb),l=m.x):(g=Math.round((q.y-r.y)/this.Yb),k=q.y,h=Math.round((m.y-l.y)/this.Yb),l=m.y);J.free(q);J.free(m);d.portFromColOffset=g;d.portFromPos=k;d.portToColOffset=h;d.portToPos=l}else d.portFromColOffset=0,d.portFromPos=0,d.portToColOffset=0,d.portToPos=0;q=e.layer;m=f.layer;n=0;u=d.link;if(null!==u){var x=
u.fromPort,y=u.toPort;if(null!==x&&null!==y){var A=u.fromNode;p=u.toNode;if(null!==A&&null!==p){var C=fs(this,!0),G=fs(this,!1),I=this.setsPortSpots?C:u.computeSpot(!0,x);r=this.setsPortSpots?G:u.computeSpot(!1,y);var O=u.isOrthogonal;I.tf()&&I.sf(G)&&r.tf()&&r.sf(C)?n=0:(C=u.getLinkPoint(A,x,I,!0,O,p,y,J.alloc()),G=u.getLinkDirection(A,x,C,I,!0,O,p,y),J.free(C),I.kq()||G!==gs(this,d,!0)?this.setsPortSpots&&null!==A&&1===A.ports.count&&d.rev&&(n+=1):n+=1,I=u.getLinkPoint(p,y,r,!1,O,A,x,J.alloc()),
u=u.getLinkDirection(p,y,I,r,!1,O,A,x),J.free(I),r.kq()||u!==gs(this,d,!1)?this.setsPortSpots&&null!==p&&1===p.ports.count&&d.rev&&(n+=2):n+=2)}}}p=n;n=1===p||3===p?!0:!1;if(p=2===p||3===p?!0:!1)r=a.createVertex(),r.node=null,r.Uj=1,r.layer=q,r.near=e,a.uh(r),e=a.kk(e,r,d.link),e.valid=!1,e.rev=d.rev,e.portFromColOffset=g,e.portToColOffset=0,e.portFromPos=k,e.portToPos=0,e=r;u=1;n&&u--;if(q-m>u&&0<q){d.valid=!1;r=a.createVertex();r.node=null;r.Uj=2;r.layer=q-1;a.uh(r);e=a.kk(e,r,d.link);e.valid=!0;
e.rev=d.rev;e.portFromColOffset=p?0:g;e.portToColOffset=0;e.portFromPos=p?0:k;e.portToPos=0;e=r;for(q--;q-m>u&&0<q;)r=a.createVertex(),r.node=null,r.Uj=3,r.layer=q-1,a.uh(r),e=a.kk(e,r,d.link),e.valid=!0,e.rev=d.rev,e.portFromColOffset=0,e.portToColOffset=0,e.portFromPos=0,e.portToPos=0,e=r,q--;e=a.kk(r,f,d.link);e.valid=!n;n&&(r.near=f);e.rev=d.rev;e.portFromColOffset=0;e.portToColOffset=h;e.portFromPos=0;e.portToPos=l}else d.valid=!0}}a=this.hc=[];for(b=0;b<=this.Ba;b++)a[b]=0;for(b=this.network.vertexes.iterator;b.next();)b.value.index=
-1;this.initializeIndices();this.Vr=-1;for(c=this.qd=this.uo=0;c<=this.Ba;c++)a[c]>a[this.qd]&&(this.Vr=a[c]-1,this.qd=c),a[c]<a[this.uo]&&(this.uo=c);this.Fo=[];for(c=0;c<a.length;c++)this.Fo[c]=[];for(b.reset();b.next();)a=b.value,this.Fo[a.layer][a.index]=a;this.Ia=-1;for(a=0;a<=this.Ba;a++){b=hs(this,a);c=0;d=this.hc[a];for(f=0;f<d;f++)e=b[f],c+=this.nodeMinColumnSpace(e,!0),e.column=c,c+=1,c+=this.nodeMinColumnSpace(e,!1);this.Ia=Math.max(this.Ia,c-1);is(this,a,b)}this.reduceCrossings();this.straightenAndPack();
this.updateParts()}this.network=null;this.isValidLayout=!0};Zr.prototype.linkMinLength=function(){return 1};function js(a){var b=a.fromVertex.node;a=a.toVertex.node;return null===b&&null===a?8:null===b||null===a?4:1}Zr.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};
Zr.prototype.nodeMinColumnSpace=function(a,b){if(null===a.node)return 0;var c=b?a.xv:a.wv;if(null!==c)return c;c=this.M;return 90===c||270===c?b?a.xv=a.focus.x/this.Yb+1|0:a.wv=(a.bounds.width-a.focus.x)/this.Yb+1|0:b?a.xv=a.focus.y/this.Yb+1|0:a.wv=(a.bounds.height-a.focus.y)/this.Yb+1|0};function ks(a){null===a.zj&&(a.zj=[]);for(var b=0,c=a.network.vertexes.iterator;c.next();){var d=c.value;a.zj[b]=d.layer;b++;a.zj[b]=d.column;b++;a.zj[b]=d.index;b++}return a.zj}
function ls(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 ms(a,b,c){E&&(B(b,Zr,"crossingMatrix:unfixedLayer"),B(c,Zr,"crossingMatrix:direction"));var d=hs(a,b),e=a.hc[b];if(null===a.Do||a.Do.length<e*e)a.Do=[];for(var f=a.Do,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.Uj===l.Uj||h++}else for(m=g-1;m>k;m--)n=d[m],n.near===l&&n.Uj===l.Uj||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 x=r.portToPos;r=r.portFromPos;m<x&&(n>u||n===u&&q>r)&&h++;x<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,x=r.portToPos,r=r.portFromPos,
q<r&&(n>u||n===u&&m>x)&&h++,r<q&&(u>n||u===n&&x>m)&&h++);f[g*e+g]=h;for(k=g+1;k<e;k++){var y=0,A=0;if(0<=c){h=d[g].sourceEdgesArrayAccess;var C=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<C.length;p++)r=C[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)&&y++)}if(0>=c)for(h=d[g].destinationEdgesArrayAccess,C=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<C.length;p++)r=C[p],r.valid&&r.toVertex.layer!==b&&(u=r.toVertex.index,x=r.portToPos,(n<u||n===u&&m<x)&&A++,(u<n||u===n&&x<m)&&y++);f[g*e+k]=y;f[k*e+g]=A}}is(a,b,d);return f}Zr.prototype.countCrossings=function(){for(var a=0,b=0;b<=this.Ba;b++)for(var c=ms(this,b,1),d=this.hc[b],e=0;e<d;e++)for(var f=e;f<d;f++)a+=c[e*d+f];return a};
function ns(a){for(var b=0,c=0;c<=a.Ba;c++){for(var d=a,e=c,f=hs(d,e),g=d.hc[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)*js(n)}}}is(d,e,f);b+=h}return b}
Zr.prototype.normalize=function(){var a=Infinity;this.Ia=-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.Ia=Math.max(this.Ia,c.column+this.nodeMinColumnSpace(c,!1))}for(b.reset();b.next();)b.value.column-=a;this.Ia-=a};
function os(a,b,c){E&&(B(b,Zr,"barycenters:unfixedLayer"),B(c,Zr,"barycenters:direction"));for(var d=hs(a,b),e=a.hc[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}is(a,b,d);return f}
function ps(a,b,c){E&&(B(b,Zr,"medians:unfixedLayer"),B(c,Zr,"medians:direction"));for(var d=hs(a,b),e=a.hc[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)}is(a,b,d);return f}
function qs(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&&qs(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&&qs(a,k,c,d,e,f)}}
function rs(a,b,c,d,e,f){if(b.component===d){b.component=c;if(e)for(var g=b.destinationEdges;g.next();)rs(a,g.value.toVertex,c,d,e,f);if(f)for(b=b.sourceEdges;b.next();)rs(a,b.value.fromVertex,c,d,e,f)}}
Zr.prototype.removeCycles=function(){for(var a=this.network.edges.iterator;a.next();)a.value.rev=!1;switch(this.Pk){default:case ss: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!==ts(a);){for(e=us(a);null!==e;)d[c]=e,c--,e.valid=!1,e=us(a);for(e=vs(a);null!==e;)d[b]=e,b++,e.valid=!1,e=vs(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.ym(b),b.rev=!0);break;case $r:for(d=this.network.vertexes.iterator;d.next();)a=d.value,a.bm=-1,a.finish=-1;for(a=this.network.edges.iterator;a.next();)a.value.forest=!1;this.Eo=0;for(d.reset();d.next();)b=d.value,0===b.sourceEdges.count&&
ws(this,b);for(d.reset();d.next();)b=d.value,-1===b.bm&&ws(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.bm<b.bm&&c<f&&(this.network.ym(d),d.rev=!0));break;case es:a=this.network;b=a.vertexes.iterator;for(d=Infinity;b.next();)d=Math.min(d,b.value.layer);if(Infinity>d){if(0>d)for(b.reset();b.next();)b.value.layer-=d;d=[];for(b.reset();b.next();)c=b.value,e=d[c.layer],void 0===e?d[c.layer]=[c]:e.push(c);for(c=b=0;c<d.length;c++)if(e=d[c],!e||
0===e.length)b++;else if(0<c)for(f=0;f<e.length;f++)e[f].layer-=b;for(d=a.edges.iterator;d.next();)b=d.value,b.fromVertex.layer<b.toVertex.layer&&(a.ym(b),b.rev=!0)}}};function ts(a){for(a=a.vertexes.iterator;a.next();){var b=a.value;if(b.valid)return b}return null}function us(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 vs(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 ws(a,b){b.bm=a.Eo;a.Eo++;for(var c=b.destinationEdges;c.next();){var d=c.value,e=d.toVertex;-1===e.bm&&(d.forest=!0,ws(a,e))}b.finish=a.Eo;a.Eo++}
Zr.prototype.assignLayers=function(){switch(this.ql){case xs:ys(this);break;case zs:for(var a,b=this.network.vertexes.iterator;b.next();)a=As(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 as:ys(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&&Bs(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 ys(a){for(var b=a.network.vertexes.iterator;b.next();){var c=Cs(a,b.value);a.Ba=Math.max(c,a.Ba)}}function Cs(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,Cs(a,f)+e)}b.layer=c}else c=b.layer;return c}
function As(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,As(a,f)+e)}b.layer=c}else c=b.layer;return c}
function Bs(a,b){if(!b.valid){b.valid=!0;for(var c=b.destinationEdges;c.next();)Bs(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&&qs(a,h,0,-1,!0,!1)}for(qs(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(qs(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 gs(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}
Zr.prototype.initializeIndices=function(){switch(this.gl){default:case Ds:for(var a=this.network.vertexes.iterator;a.next();){var b=a.value,c=b.layer;b.index=this.hc[c];this.hc[c]++}break;case bs: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&&Es(this,c);break;case Fs: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&&Gs(this,c)}};
function Es(a,b){var c=b.layer;b.index=a.hc[c];a.hc[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&&Es(a,d))}
function Gs(a,b){var c=b.layer;b.index=a.hc[c];a.hc[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&&Gs(a,d))}
Zr.prototype.reduceCrossings=function(){var a=this.countCrossings(),b=ks(this),c,d;for(c=0;c<this.uj;c++){for(d=0;d<=this.Ba;d++)Hs(this,d,1),Is(this,d,1);var e=this.countCrossings();e<a&&(a=e,b=ks(this));for(d=this.Ba;0<=d;d--)Hs(this,d,-1),Is(this,d,-1);e=this.countCrossings();e<a&&(a=e,b=ks(this))}ls(this,b);for(c=0;c<this.uj;c++){for(d=0;d<=this.Ba;d++)Hs(this,d,0),Is(this,d,0);e=this.countCrossings();e<a&&(a=e,b=ks(this));for(d=this.Ba;0<=d;d--)Hs(this,d,0),Is(this,d,0);e=this.countCrossings();
e<a&&(a=e,b=ks(this))}ls(this,b);var f,g,h;switch(this.Bk){case Js:break;case Ks: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=Is(this,d,-1)||f;e=this.countCrossings();e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Is(this,d,1)||f;e=this.countCrossings();e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Is(this,d,1)||f;e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=
Is(this,d,-1)||f;e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Is(this,d,0)||f;e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Is(this,d,0)||f;e>=a?ls(this,b):(a=e,b=ks(this))}break;default:case cs: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=Is(this,d,-1)||f;e=this.countCrossings();e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Is(this,d,1)||f;e=this.countCrossings();e>=a?ls(this,b):
(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Is(this,d,1)||f;e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Is(this,d,-1)||f;e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Is(this,d,0)||f;e>=a?ls(this,b):(a=e,b=ks(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Is(this,d,0)||f;e>=a?ls(this,b):(a=e,b=ks(this))}}ls(this,b)};
function Hs(a,b,c){E&&(B(b,Zr,"medianBarycenterCrossingReduction:unfixedLayer"),B(c,Zr,"medianBarycenterCrossingReduction:direction"));var d=hs(a,b),e=a.hc[b],f=ps(a,b,c),g=os(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);is(a,b,d)}
function Is(a,b,c){var d=hs(a,b),e=a.hc[b];c=ms(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,x=a.nodeMinColumnSpace(d[f],!0),y=a.nodeMinColumnSpace(d[f],!1),A=a.nodeMinColumnSpace(d[f+1],!0),C=a.nodeMinColumnSpace(d[f+1],!1);x=r-x+A;y=u-y+C;var G=d[f].sourceEdges.iterator;for(G.reset();G.next();)if(A=G.value,C=A.fromVertex,
A.valid&&C.layer===b){for(A=0;d[A]!==C;)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)))}G=d[f].destinationEdges.iterator;for(G.reset();G.next();)if(A=G.value,C=A.toVertex,A.valid&&C.layer===b){for(A=0;d[A]!==C;)A++;A===f+1&&(q+=1)}G=d[f+1].sourceEdges.iterator;for(G.reset();G.next();)if(A=G.value,C=A.fromVertex,A.valid&&C.layer===b){for(A=0;d[A]!==C;)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))}G=d[f+1].destinationEdges.iterator;
for(G.reset();G.next();)if(A=G.value,C=A.toVertex,A.valid&&C.layer===b){for(A=0;d[A]!==C;)A++;A===f&&(p+=1)}A=C=0;G=g[d[f].index];var I=h[d[f].index],O=g[d[f+1].index],R=h[d[f+1].index];-1!==G&&(C+=Math.abs(G-r),A+=Math.abs(G-y));-1!==I&&(C+=Math.abs(I-r),A+=Math.abs(I-y));-1!==O&&(C+=Math.abs(O-u),A+=Math.abs(O-x));-1!==R&&(C+=Math.abs(R-u),A+=Math.abs(R-x));if(q<p-.5||q===p&&n<m-.5||q===p&&n===m&&A<C-.5)l=k=!0,d[f].column=y,d[f+1].column=x,m=d[f],d[f]=d[f+1],d[f+1]=m}for(f=0;f<e;f++)d[f].index=
f;is(a,b,d);return k}
Zr.prototype.straightenAndPack=function(){var a=0!==(this.bg&1);var b=7===this.bg;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.Ia-c[b])>>1)+8*d;this.Ia*=8}if(0!==(this.bg&2))for(c=!0;c;){c=!1;for(b=this.qd+1;b<=this.Ba;b++)c=Ls(this,b,1)||c;for(b=
this.qd-1;0<=b;b--)c=Ls(this,b,-1)||c;c=Ls(this,this.qd,0)||c}if(0!==(this.bg&4)){for(b=this.qd+1;b<=this.Ba;b++)Ms(this,b,1);for(b=this.qd-1;0<=b;b--)Ms(this,b,-1);Ms(this,this.qd,0)}a&&(Ns(this,-1),Ns(this,1));if(0!==(this.bg&2))for(c=!0;c;){c=!1;c=Ls(this,this.qd,0)||c;for(b=this.qd+1;b<=this.Ba;b++)c=Ls(this,b,0)||c;for(b=this.qd-1;0<=b;b--)c=Ls(this,b,0)||c}};
function Ls(a,b,c){E&&(B(b,Zr,"bendStraighten:unfixedLayer"),B(c,Zr,"bendStraighten:direction"));for(var d=!1;Os(a,b,c);)d=!0;return d}
function Os(a,b,c){E&&(B(b,Zr,"shiftbendStraighten:unfixedLayer"),B(c,Zr,"shiftbendStraighten:direction"));var d,e=hs(a,b),f=a.hc[b],g=os(a,b,-1);if(0<c)for(d=0;d<f;d++)g[d]=-1;var h=os(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 x=e[d].sourceEdges.iterator;x.next();){var y=x.value;var A=y.fromVertex;if(y.valid&&A.layer!==b){var C=js(y);var G=y.portFromColOffset;y=y.portToColOffset;A=A.column;p+=(Math.abs(m+y-(A+G))+1)*C;r+=(Math.abs(q+y-(A+G))+1)*C;u+=(Math.abs(n+y-(A+G))+1)*C}}if(0<=c)for(x=e[d].destinationEdges.iterator;x.next();)y=x.value,A=y.toVertex,y.valid&&A.layer!==b&&(C=js(y),G=y.portFromColOffset,y=y.portToColOffset,A=A.column,p+=(Math.abs(m+G-(A+y))+1)*C,r+=(Math.abs(q+G-(A+y))+1)*C,u+=(Math.abs(n+
G-(A+y))+1)*C);y=G=C=0;x=g[e[d].index];A=h[e[d].index];-1!==x&&(C+=Math.abs(x-m),G+=Math.abs(x-q),y+=Math.abs(x-n));-1!==A&&(C+=Math.abs(A-m),G+=Math.abs(A-q),y+=Math.abs(A-n));if(r<p||r===p&&G<C)l=k=!0,e[d].column=q;else if(u<p||u===p&&y<C)l=k=!0,e[d].column=n}is(a,b,e);a.normalize();return k}
function Ms(a,b,c){E&&(B(b,Zr,"medianStraighten:unfixedLayer"),B(c,Zr,"medianStraighten:direction"));var d=hs(a,b),e=a.hc[b],f=ps(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)}is(a,b,
d);a.normalize()}function Ps(a,b){E&&(B(b,Zr,"packAux:column"),B(1,Zr,"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 Qs(a,b){E&&(B(b,Zr,"tightPackAux:column"),B(1,Zr,"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 Ns(a,b){E&&B(b,Zr,"componentPack:direction");for(var c=0;c<=a.Ia;c++)for(;Ps(a,c););a.normalize();for(c=0;c<a.Ia;c++)for(;Qs(a,c););a.normalize();var d;if(0<b)for(c=0;c<=a.Ia;c++){var e=ks(a);var f=ns(a);for(d=f+1;f<d;){d=f;Rs(a,c,1);var g=ns(a);g>f?ls(a,e):g<f&&(f=g,e=ks(a))}}if(0>b)for(c=a.Ia;0<=c;c--)for(e=ks(a),f=ns(a),d=f+1;f<d;)d=f,Rs(a,c,-1),g=ns(a),g>f?ls(a,e):g<f&&(f=g,e=ks(a));a.normalize()}
function Rs(a,b,c){a.Nd=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.Nd)}if(0>c)for(d.reset();d.next();)e=d.value,e.column+a.nodeMinColumnSpace(e,!1)>=b&&(e.component=a.Nd);a.Nd++;for(d.reset();d.next();)b=d.value,-1===b.component&&(rs(a,b,a.Nd,-1,!0,!0),a.Nd++);var f;b=[];for(f=0;f<a.Nd*a.Nd;f++)b[f]=!1;e=[];for(f=0;f<(a.Ba+1)*(a.Ia+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.Ia,f.column+a.nodeMinColumnSpace(f,!1));h<=k;h++)e[g*(a.Ia+1)+h]=f.component}for(f=0;f<=a.Ba;f++){if(0<c)for(g=0;g<a.Ia;g++)-1!==e[f*(a.Ia+1)+g]&&-1!==e[f*(a.Ia+1)+g+1]&&e[f*(a.Ia+1)+g]!==e[f*(a.Ia+1)+g+1]&&(b[e[f*(a.Ia+1)+g]*a.Nd+e[f*(a.Ia+1)+g+1]]=!0);if(0>c)for(g=a.Ia;0<g;g--)-1!==e[f*(a.Ia+1)+g]&&-1!==e[f*(a.Ia+1)+g-1]&&e[f*(a.Ia+1)+g]!==e[f*(a.Ia+1)+g-1]&&(b[e[f*(a.Ia+1)+g]*a.Nd+e[f*(a.Ia+1)+g-1]]=!0)}e=
[];for(f=0;f<a.Nd;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.Nd;f++)b[k*a.Nd+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)}
Zr.prototype.commitLayout=function(){if(this.setsPortSpots)for(var a=fs(this,!0),b=fs(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.Su();this.isRouting&&this.commitLinks()};function fs(a,b){return 270===a.M?b?Vd:de:90===a.M?b?de:Vd:180===a.M?b?Wd:Xd:b?Xd:Wd}
Zr.prototype.commitNodes=function(){this.Jd=[];this.od=[];this.nd=[];this.La=[];for(var a=0;a<=this.Ba;a++)this.Jd[a]=0,this.od[a]=0,this.nd[a]=0,this.La[a]=0;for(a=this.network.vertexes.iterator;a.next();){var b=a.value,c=b.layer;this.Jd[c]=Math.max(this.Jd[c],this.nodeMinLayerSpace(b,!0));this.od[c]=Math.max(this.od[c],this.nodeMinLayerSpace(b,!1))}b=0;c=this.me;for(var d=0;d<=this.Ba;d++){var e=c;0>=this.Jd[d]+this.od[d]&&(e=0);0<d&&(b+=e/2);90===this.M||0===this.M?(b+=this.od[d],this.nd[d]=b,
b+=this.Jd[d]):(b+=this.Jd[d],this.nd[d]=b,b+=this.od[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.nd[d]=b.y+this.nd[d]:90===this.M?(this.nd[d]=b.y+c-this.nd[d],this.La[d]=c-this.La[d]):180===this.M?this.nd[d]=b.x+this.nd[d]:(this.nd[d]=b.x+c-this.nd[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.nd[f]}else h=this.nd[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.ow=new J(d,b);for(a.reset();a.next();)c=a.value,c.x+=d,c.y+=b,c.commit()};
Zr.prototype.Su=function(){for(var a=0,b=this.me,c=0;c<=this.Ba;c++)a+=this.Jd[c],a+=this.od[c];a+=this.Ba*b;b=[];c=this.Yb*this.Ia;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.ow)};Zr.prototype.commitLayers=function(){};
Zr.prototype.commitLinks=function(){for(var a=this.network.edges.iterator,b;a.next();)b=a.value.link,null!==b&&(b.Eh(),b.Yj(),b.nf());for(a.reset();a.next();)b=a.value.link,null!==b&&b.cj();for(a.reset();a.next();){var c=a.value;b=c.link;if(null!==b){b.Eh();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===fh&&4===b.pointsCount)if(p.column===q.column){var r=b.getLinkPoint(e,g,m,!0,!1,f,h),u=b.getLinkPoint(f,h,n,!1,!1,e,g);r.o()||r.set(e.actualBounds.center);u.o()||u.set(f.actualBounds.center);b.Yj();b.mf(r.x,r.y);b.mf((2*r.x+u.x)/3,(2*r.y+u.y)/3);b.mf((r.x+2*u.x)/3,(r.y+2*u.y)/3);b.mf(u.x,u.y)}else{var x=!1,y=!1;null!==g&&m===ed&&(x=!0);null!==h&&n===ed&&(y=!0);if(x||y){var A=b.i(0).x,C=b.i(0).y,G=b.i(3).x,I=b.i(3).y;if(x){if(90===this.M||270===
this.M){var O=A;var R=(C+I)/2}else O=(A+G)/2,R=C;b.N(1,O,R);var U=b.getLinkPoint(e,g,m,!0,!1,f,h);U.o()||U.set(e.actualBounds.center);b.N(0,U.x,U.y)}if(y){if(90===this.M||270===this.M){var ea=G;var Z=(C+I)/2}else ea=(A+G)/2,Z=I;b.N(2,ea,Z);var qa=b.getLinkPoint(f,h,n,!1,!1,e,g);qa.o()||qa.set(f.actualBounds.center);b.N(3,qa.x,qa.y)}}}b.nf()}else if(p.layer===q.layer)b.nf();else{var xa=!1,Q=!1,aa=b.firstPickIndex+1;if(b.isOrthogonal){Q=!0;var Ga=b.pointsCount;4<Ga&&b.points.removeRange(2,Ga-3)}else if(b.curve===
fh)xa=!0,Ga=b.pointsCount,4<Ga&&b.points.removeRange(2,Ga-3),4===Ga&&(aa=2);else{Ga=b.pointsCount;var yb=m===ed,Xa=n===ed;2<Ga&&yb&&Xa?b.points.removeRange(1,Ga-2):3<Ga&&yb&&!Xa?b.points.removeRange(1,Ga-3):3<Ga&&!yb&&Xa?b.points.removeRange(2,Ga-2):4<Ga&&!yb&&!Xa&&b.points.removeRange(2,Ga-3)}var Sa;if(c.rev){for(var Ua;null!==q&&p!==q;){var hb=Sa=null;for(var kc=q.sourceEdges.iterator;kc.next();){var rb=kc.value;if(rb.link===c.link&&(Sa=rb.fromVertex,hb=rb.toVertex,null===Sa.node))break}if(Sa!==
p){var mb=b.i(aa-1).x;var cb=b.i(aa-1).y;var ua=Sa.centerX;var ta=Sa.centerY;if(Q)if(180===this.M||0===this.M)if(aa===b.firstPickIndex+1)b.m(aa++,mb,cb),b.m(aa++,mb,ta);else{if((null!==hb?hb.centerY:cb)!==ta){var wb=this.La[Sa.layer-1];b.m(aa++,wb,cb);b.m(aa++,wb,ta)}}else aa===b.firstPickIndex+1?(b.m(aa++,mb,cb),b.m(aa++,ua,cb)):(null!==hb?hb.centerX:mb)!==ua&&(wb=this.La[Sa.layer-1],b.m(aa++,mb,wb),b.m(aa++,ua,wb));else if(aa===b.firstPickIndex+1){var zb=Math.max(10,this.Jd[q.layer]);var db=Math.max(10,
this.od[q.layer]);if(xa)180===this.M?ua<=q.bounds.x?(Ua=q.bounds.x,b.m(aa++,Ua-zb,ta),b.m(aa++,Ua,ta),b.m(aa++,Ua+db,ta)):(b.m(aa++,ua-zb,ta),b.m(aa++,ua,ta),b.m(aa++,ua+db,ta)):90===this.M?ta>=q.bounds.bottom?(Ua=q.bounds.y+q.bounds.height,b.m(aa++,ua,Ua+db),b.m(aa++,ua,Ua),b.m(aa++,ua,Ua-zb)):(b.m(aa++,ua,ta+db),b.m(aa++,ua,ta),b.m(aa++,ua,ta-zb)):270===this.M?ta<=q.bounds.y?(Ua=q.bounds.y,b.m(aa++,ua,Ua-zb),b.m(aa++,ua,Ua),b.m(aa++,ua,Ua+db)):(b.m(aa++,ua,ta-zb),b.m(aa++,ua,ta),b.m(aa++,ua,ta+
db)):0===this.M&&(ua>=q.bounds.right?(Ua=q.bounds.x+q.bounds.width,b.m(aa++,Ua+db,ta),b.m(aa++,Ua,ta),b.m(aa++,Ua-zb,ta)):(b.m(aa++,ua+db,ta),b.m(aa++,ua,ta),b.m(aa++,ua-zb,ta)));else{b.m(aa++,mb,cb);var qe=0;if(180===this.M||0===this.M){if(180===this.M?ua>=q.bounds.right:ua<=q.bounds.x)qe=(0===this.M?-zb:db)/2;b.m(aa++,mb+qe,ta)}else{if(270===this.M?ta>=q.bounds.bottom:ta<=q.bounds.y)qe=(90===this.M?-zb:db)/2;b.m(aa++,ua,cb+qe)}b.m(aa++,ua,ta)}}else zb=Math.max(10,this.Jd[Sa.layer]),db=Math.max(10,
this.od[Sa.layer]),180===this.M?(xa&&b.m(aa++,ua-zb,ta),b.m(aa++,ua,ta),xa&&b.m(aa++,ua+db,ta)):90===this.M?(xa&&b.m(aa++,ua,ta+db),b.m(aa++,ua,ta),xa&&b.m(aa++,ua,ta-zb)):270===this.M?(xa&&b.m(aa++,ua,ta-zb),b.m(aa++,ua,ta),xa&&b.m(aa++,ua,ta+db)):(xa&&b.m(aa++,ua+db,ta),b.m(aa++,ua,ta),xa&&b.m(aa++,ua-zb,ta))}q=Sa}if(null===h||m!==ed||Q)if(mb=b.i(aa-1).x,cb=b.i(aa-1).y,ua=b.i(aa).x,ta=b.i(aa).y,Q){var Yd=this.od[p.layer];if(180===this.M||0===this.M){var Lb=cb;Lb>=p.bounds.y&&Lb<=p.bounds.bottom&&
(180===this.M?ua>=p.bounds.x:ua<=p.bounds.right)&&(Ua=p.centerX+(180===this.M?-Yd:Yd),Lb<p.bounds.y+p.bounds.height/2?Lb=p.bounds.y-this.Yb/2:Lb=p.bounds.bottom+this.Yb/2,b.m(aa++,Ua,cb),b.m(aa++,Ua,Lb));b.m(aa++,ua,Lb)}else Lb=mb,Lb>=p.bounds.x&&Lb<=p.bounds.right&&(270===this.M?ta>=p.bounds.y:ta<=p.bounds.bottom)&&(Ua=p.centerY+(270===this.M?-Yd:Yd),Lb<p.bounds.x+p.bounds.width/2?Lb=p.bounds.x-this.Yb/2:Lb=p.bounds.right+this.Yb/2,b.m(aa++,mb,Ua),b.m(aa++,Lb,Ua)),b.m(aa++,Lb,ta);b.m(aa++,ua,ta)}else if(xa)zb=
Math.max(10,this.Jd[p.layer]),db=Math.max(10,this.od[p.layer]),180===this.M&&ua>=p.bounds.x?(Ua=p.bounds.x+p.bounds.width,b.N(aa-2,Ua,cb),b.N(aa-1,Ua+db,cb)):90===this.M&&ta<=p.bounds.bottom?(Ua=p.bounds.y,b.N(aa-2,mb,Ua),b.N(aa-1,mb,Ua-zb)):270===this.M&&ta>=p.bounds.y?(Ua=p.bounds.y+p.bounds.height,b.N(aa-2,mb,Ua),b.N(aa-1,mb,Ua+db)):0===this.M&&ua<=p.bounds.right&&(Ua=p.bounds.x,b.N(aa-2,Ua,cb),b.N(aa-1,Ua-zb,cb));else{zb=Math.max(10,this.Jd[p.layer]);db=Math.max(10,this.od[p.layer]);var Pf=0;
if(180===this.M||0===this.M){if(180===this.M?ua<=p.bounds.x:ua>=p.bounds.right)Pf=(0===this.M?db:-zb)/2;b.m(aa++,ua+Pf,cb)}else{if(270===this.M?ta<=p.bounds.y:ta>=p.bounds.bottom)Pf=(90===this.M?db:-zb)/2;b.m(aa++,mb,ta+Pf)}b.m(aa++,ua,ta)}}else{for(;null!==p&&p!==q;){hb=Sa=null;for(var Wb=p.destinationEdges.iterator;Wb.next();){var De=Wb.value;if(De.link===c.link&&(Sa=De.toVertex,hb=De.fromVertex,null!==hb.node&&(hb=null),null===Sa.node))break}Sa!==q&&(mb=b.i(aa-1).x,cb=b.i(aa-1).y,ua=Sa.centerX,
ta=Sa.centerY,Q?180===this.M||0===this.M?(null!==hb?hb.centerY:cb)!==ta&&(wb=this.La[Sa.layer],aa===b.firstPickIndex+1&&(wb=0===this.M?Math.max(wb,mb):Math.min(wb,mb)),b.m(aa++,wb,cb),b.m(aa++,wb,ta)):(null!==hb?hb.centerX:mb)!==ua&&(wb=this.La[Sa.layer],aa===b.firstPickIndex+1&&(wb=90===this.M?Math.max(wb,cb):Math.min(wb,cb)),b.m(aa++,mb,wb),b.m(aa++,ua,wb)):(zb=Math.max(10,this.Jd[Sa.layer]),db=Math.max(10,this.od[Sa.layer]),180===this.M?(b.m(aa++,ua+db,ta),xa&&b.m(aa++,ua,ta),b.m(aa++,ua-zb,ta)):
90===this.M?(b.m(aa++,ua,ta-zb),xa&&b.m(aa++,ua,ta),b.m(aa++,ua,ta+db)):270===this.M?(b.m(aa++,ua,ta+db),xa&&b.m(aa++,ua,ta),b.m(aa++,ua,ta-zb)):(b.m(aa++,ua-zb,ta),xa&&b.m(aa++,ua,ta),b.m(aa++,ua+db,ta))));p=Sa}Q&&(mb=b.i(aa-1).x,cb=b.i(aa-1).y,ua=b.i(aa).x,ta=b.i(aa).y,180===this.M||0===this.M?cb!==ta&&(wb=0===this.M?Math.min(Math.max((ua+mb)/2,this.La[q.layer]),ua):Math.max(Math.min((ua+mb)/2,this.La[q.layer]),ua),b.m(aa++,wb,cb),b.m(aa++,wb,ta)):mb!==ua&&(wb=90===this.M?Math.min(Math.max((ta+
cb)/2,this.La[q.layer]),ta):Math.max(Math.min((ta+cb)/2,this.La[q.layer]),ta),b.m(aa++,mb,wb),b.m(aa++,ua,wb)))}if(null!==d&&xa){if(null!==g){if(m===ed){var id=b.i(0),lc=b.i(2);id.A(lc)||b.N(1,(id.x+lc.x)/2,(id.y+lc.y)/2)}var Zd=b.getLinkPoint(e,g,ed,!0,!1,f,h);Zd.o()||Zd.set(e.actualBounds.center);b.N(0,Zd.x,Zd.y)}if(null!==h){if(n===ed){var Wc=b.i(b.pointsCount-1),Ze=b.i(b.pointsCount-3);Wc.A(Ze)||b.N(b.pointsCount-2,(Wc.x+Ze.x)/2,(Wc.y+Ze.y)/2)}var $e=b.getLinkPoint(f,h,ed,!1,!1,e,g);$e.o()||$e.set(f.actualBounds.center);
b.N(b.pointsCount-1,$e.x,$e.y)}}b.nf();c.commit()}}}for(var Qf=new F,wf=this.network.edges.iterator;wf.next();){var Rf=wf.value.link;null!==Rf&&Rf.isOrthogonal&&!Qf.contains(Rf)&&Qf.add(Rf)}if(0<Qf.count)if(90===this.M||270===this.M){for(var mc=0,ob=[],nb,Nc,Sf=Qf.iterator;Sf.next();){var zc=Sf.value;if(null!==zc&&zc.isOrthogonal)for(var $d=2;$d<zc.pointsCount-3;$d++)if(nb=zc.i($d),Nc=zc.i($d+1),this.B(nb.y,Nc.y)&&!this.B(nb.x,Nc.x)){var Ic=new Ss;Ic.layer=Math.floor(nb.y/2);var ae=zc.i(0),nc=zc.i(zc.pointsCount-
1);Ic.first=ae.x*ae.x+ae.y;Ic.Ub=nc.x*nc.x+nc.y;Ic.Vc=Math.min(nb.x,Nc.x);Ic.uc=Math.max(nb.x,Nc.x);Ic.index=$d;Ic.link=zc;if($d+2<zc.pointsCount){var Zh=zc.i($d-1),$h=zc.i($d+2),af=0;Zh.y<nb.y?af=$h.y<nb.y?3:nb.x<Nc.x?2:1:Zh.y>nb.y&&(af=$h.y>nb.y?0:Nc.x<nb.x?2:1);Ic.l=af}ob.push(Ic)}}if(1<ob.length){ob.sort(this.Jx);for(var Fb=0;Fb<ob.length;){for(var Tf=ob[Fb].layer,bf=Fb+1;bf<ob.length&&ob[bf].layer===Tf;)bf++;if(1<bf-Fb)for(var oc=Fb;oc<bf;){for(var cf=ob[oc].uc,ad=Fb+1;ad<bf&&ob[ad].Vc<cf;)cf=
Math.max(cf,ob[ad].uc),ad++;var vb=ad-oc;if(1<vb){this.$i(ob,this.xt,oc,oc+vb);for(var df=1,Ib=ob[oc].Ub,Jc=oc;Jc<ad;Jc++){var Ab=ob[Jc];Ab.Ub!==Ib&&(df++,Ib=Ab.Ub)}this.$i(ob,this.Ix,oc,oc+vb);var jd=1;Ib=ob[oc].first;for(var kd=oc;kd<ad;kd++){var Jd=ob[kd];Jd.first!==Ib&&(jd++,Ib=Jd.first)}var Vg=!0,Uf=jd;df<jd?(Vg=!1,Uf=df,Ib=ob[oc].Ub,this.$i(ob,this.xt,oc,oc+vb)):Ib=ob[oc].first;for(var Vf=0,xf=oc;xf<ad;xf++){var xd=ob[xf];(Vg?xd.first:xd.Ub)!==Ib&&(Vf++,Ib=Vg?xd.first:xd.Ub);var Kd=xd.link;
nb=Kd.i(xd.index);Nc=Kd.i(xd.index+1);var bd=this.linkSpacing*(Vf-(Uf-1)/2);if(!Kd.isAvoiding||Ts(nb.x,nb.y+bd,Nc.x,Nc.y+bd))mc++,Kd.Eh(),Kd.N(xd.index,nb.x,nb.y+bd),Kd.N(xd.index+1,Nc.x,Nc.y+bd),Kd.nf()}}oc=ad}Fb=bf}}}else{for(var yd=0,Bb=[],pb,cd,ld=Qf.iterator;ld.next();){var zd=ld.value;if(null!==zd&&zd.isOrthogonal)for(var Oc=2;Oc<zd.pointsCount-3;Oc++)if(pb=zd.i(Oc),cd=zd.i(Oc+1),this.B(pb.x,cd.x)&&!this.B(pb.y,cd.y)){var Pa=new Ss;Pa.layer=Math.floor(pb.x/2);var md=zd.i(0),pc=zd.i(zd.pointsCount-
1);Pa.first=md.x+md.y*md.y;Pa.Ub=pc.x+pc.y*pc.y;Pa.Vc=Math.min(pb.y,cd.y);Pa.uc=Math.max(pb.y,cd.y);Pa.index=Oc;Pa.link=zd;if(Oc+2<zd.pointsCount){var re=zd.i(Oc-1),ef=zd.i(Oc+2),se=0;re.x<pb.x?se=ef.x<pb.x?3:pb.y<cd.y?2:1:re.x>pb.x&&(se=ef.x>pb.x?0:cd.y<pb.y?2:1);Pa.l=se}Bb.push(Pa)}}if(1<Bb.length){Bb.sort(this.Jx);for(var Pc=0;Pc<Bb.length;){for(var Ee=Bb[Pc].layer,nd=Pc+1;nd<Bb.length&&Bb[nd].layer===Ee;)nd++;if(1<nd-Pc)for(var Mb=Pc;Mb<nd;){for(var be=Bb[Mb].uc,bc=Pc+1;bc<nd&&Bb[bc].Vc<be;)be=
Math.max(be,Bb[bc].uc),bc++;var Fe=bc-Mb;if(1<Fe){this.$i(Bb,this.xt,Mb,Mb+Fe);for(var Ld=1,te=Bb[Mb].Ub,Wg=Mb;Wg<bc;Wg++){var od=Bb[Wg];od.Ub!==te&&(Ld++,te=od.Ub)}this.$i(Bb,this.Ix,Mb,Mb+Fe);var ff=1;te=Bb[Mb].first;for(var Wf=Mb;Wf<bc;Wf++){var Xf=Bb[Wf];Xf.first!==te&&(ff++,te=Xf.first)}var gf=!0,Xg=ff;Ld<ff?(gf=!1,Xg=Ld,te=Bb[Mb].Ub,this.$i(Bb,this.xt,Mb,Mb+Fe)):te=Bb[Mb].first;for(var rg=0,$i=Mb;$i<bc;$i++){var hf=Bb[$i];(gf?hf.first:hf.Ub)!==te&&(rg++,te=gf?hf.first:hf.Ub);var Ge=hf.link;
pb=Ge.i(hf.index);cd=Ge.i(hf.index+1);var sg=this.linkSpacing*(rg-(Xg-1)/2);if(!Ge.isAvoiding||Ts(pb.x+sg,pb.y,cd.x+sg,cd.y))yd++,Ge.Eh(),Ge.N(hf.index,pb.x+sg,pb.y),Ge.N(hf.index+1,cd.x+sg,cd.y),Ge.nf()}}Mb=bc}Pc=nd}}}};t=Zr.prototype;t.Jx=function(a,b){return a instanceof Ss&&b instanceof Ss&&a!==b?a.layer<b.layer?-1:a.layer>b.layer?1:a.Vc<b.Vc?-1:a.Vc>b.Vc?1:a.uc<b.uc?-1:a.uc>b.uc?1:0:0};
t.Ix=function(a,b){return a instanceof Ss&&b instanceof Ss&&a!==b?a.first<b.first?-1:a.first>b.first||a.l<b.l?1:a.l>b.l||a.Vc<b.Vc?-1:a.Vc>b.Vc?1:a.uc<b.uc?-1:a.uc>b.uc?1:0:0};t.xt=function(a,b){return a instanceof Ss&&b instanceof Ss&&a!==b?a.Ub<b.Ub?-1:a.Ub>b.Ub||a.l<b.l?1:a.l>b.l||a.Vc<b.Vc?-1:a.Vc>b.Vc?1:a.uc<b.uc?-1:a.uc>b.uc?1:0:0};t.B=function(a,b){E&&(B(a,Zr,"isApprox:a"),B(b,Zr,"isApprox:b"));a-=b;return-1<a&&1>a};
t.$i=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 Ts(a,b,c,d){E&&(B(a,Zr,"isUnoccupied2:px"),B(b,Zr,"isUnoccupied2:py"),B(c,Zr,"isUnoccupied2:qx"),B(d,Zr,"isUnoccupied2:qy"));return!0}function hs(a,b){var c=a.hc[b];if(c>=a.se.length){var d=[];for(var e=0;e<a.se.length;e++)d[e]=a.se[e];a.se=d}void 0===a.se[c]||null===a.se[c]?d=[]:(d=a.se[c],a.se[c]=null);a=a.Fo[b];for(b=0;b<a.length;b++)c=a[b],d[c.index]=c;return d}function is(a,b,c){a.se[a.hc[b]]=c}
na.Object.defineProperties(Zr.prototype,{layerSpacing:{configurable:!0,get:function(){return this.me},set:function(a){this.me!==a&&(z(a,"number",Zr,"layerSpacing"),0<=a&&(this.me=a,this.C()))}},columnSpacing:{configurable:!0,get:function(){return this.Yb},set:function(a){this.Yb!==a&&(z(a,"number",Zr,"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",Zr,"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.Pk},set:function(a){this.Pk!==a&&(tb(a,Zr,Zr,"cycleRemoveOption"),a===ss||a===$r||a===es)&&(this.Pk=a,this.C())}},layeringOption:{configurable:!0,get:function(){return this.ql},set:function(a){this.ql!==a&&(tb(a,Zr,Zr,"layeringOption"),a===as||a===xs||a===zs)&&(this.ql=a,this.C())}},initializeOption:{configurable:!0,
enumerable:!0,get:function(){return this.gl},set:function(a){this.gl!==a&&(tb(a,Zr,Zr,"initializeOption"),a===bs||a===Fs||a===Ds)&&(this.gl=a,this.C())}},iterations:{configurable:!0,get:function(){return this.uj},set:function(a){this.uj!==a&&(B(a,ds,"iterations"),0<=a&&(this.uj=a,this.C()))}},aggressiveOption:{configurable:!0,get:function(){return this.Bk},set:function(a){this.Bk!==a&&(tb(a,Zr,Zr,"aggressiveOption"),a===Js||a===cs||a===Ks)&&(this.Bk=a,this.C())}},packOption:{configurable:!0,
enumerable:!0,get:function(){return this.bg},set:function(a){this.bg!==a&&(z(a,"number",Zr,"packOption"),0<=a&&8>a&&(this.bg=a,this.C()))}},setsPortSpots:{configurable:!0,get:function(){return this.af},set:function(a){this.af!==a&&(z(a,"boolean",Zr,"setsPortSpots"),this.af=a,this.C())}},linkSpacing:{configurable:!0,get:function(){return this.ko},set:function(a){this.ko!==a&&(z(a,"number",Zr,"linkSpacing"),0<=a&&(this.ko=a,this.C()))}},maxLayer:{configurable:!0,
get:function(){return this.Ba}},maxIndex:{configurable:!0,get:function(){return this.Vr}},maxColumn:{configurable:!0,get:function(){return this.Ia}},minIndexLayer:{configurable:!0,get:function(){return this.uo}},maxIndexLayer:{configurable:!0,get:function(){return this.qd}}});
var $r=new D(Zr,"CycleDepthFirst",0),ss=new D(Zr,"CycleGreedy",1),es=new D(Zr,"CycleFromLayers",2),as=new D(Zr,"LayerOptimalLinkLength",0),xs=new D(Zr,"LayerLongestPathSink",1),zs=new D(Zr,"LayerLongestPathSource",2),bs=new D(Zr,"InitDepthFirstOut",0),Fs=new D(Zr,"InitDepthFirstIn",1),Ds=new D(Zr,"InitNaive",2),Js=new D(Zr,"AggressiveNone",0),cs=new D(Zr,"AggressiveLess",1),Ks=new D(Zr,"AggressiveMore",2);Zr.className="LayeredDigraphLayout";Zr.CycleDepthFirst=$r;Zr.CycleGreedy=ss;
Zr.CycleFromLayers=es;Zr.LayerOptimalLinkLength=as;Zr.LayerLongestPathSink=xs;Zr.LayerLongestPathSource=zs;Zr.InitDepthFirstOut=bs;Zr.InitDepthFirstIn=Fs;Zr.InitNaive=Ds;Zr.AggressiveNone=Js;Zr.AggressiveLess=cs;Zr.AggressiveMore=Ks;Zr.PackNone=0;Zr.PackExpand=1;Zr.PackStraighten=2;Zr.PackMedian=4;Zr.PackAll=7;function Ss(){this.index=this.uc=this.Vc=this.Ub=this.first=this.layer=0;this.link=null;this.l=0}Ss.className="SegInfo";function ds(a){Rp.call(this,a)}ma(ds,Rp);ds.prototype.createVertex=function(){return new Us(this)};
ds.prototype.createEdge=function(){return new Vs(this)};ds.className="LayeredDigraphNetwork";function Us(a){Up.call(this,a);this.Ua=this.Gg=this.ii=-1;this.L=NaN;this.ca=null;this.valid=!1;this.finish=this.bm=NaN;this.Uj=0;this.wv=this.xv=null}ma(Us,Up);
na.Object.defineProperties(Us.prototype,{layer:{configurable:!0,get:function(){return this.ii},set:function(a){this.ii!==a&&(z(a,"number",Us,"layer"),this.ii=a)}},column:{configurable:!0,get:function(){return this.Gg},set:function(a){this.Gg!==a&&(z(a,"number",Us,"column"),this.Gg=a)}},index:{configurable:!0,get:function(){return this.Ua},set:function(a){this.Ua!==a&&(z(a,"number",Us,"index"),this.Ua=a)}},component:{configurable:!0,get:function(){return this.L},
set:function(a){this.L!==a&&(z(a,"number",Us,"component"),this.L=a)}},near:{configurable:!0,get:function(){return this.ca},set:function(a){this.ca!==a&&(E&&null!==a&&w(a,Us,Us,"near"),this.ca=a)}}});Us.className="LayeredDigraphVertex";function Vs(a){Vp.call(this,a);this.l=this.Na=this.Wb=!1;this.Ma=this.L=NaN;this.ca=this.w=0}ma(Vs,Vp);
na.Object.defineProperties(Vs.prototype,{valid:{configurable:!0,get:function(){return this.Wb},set:function(a){this.Wb!==a&&(z(a,"boolean",Vs,"valid"),this.Wb=a)}},rev:{configurable:!0,get:function(){return this.Na},set:function(a){this.Na!==a&&(z(a,"boolean",Vs,"rev"),this.Na=a)}},forest:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(z(a,"boolean",Vs,"forest"),this.l=a)}},portFromPos:{configurable:!0,get:function(){return this.L},
set:function(a){this.L!==a&&(z(a,"number",Vs,"portFromPos"),this.L=a)}},portToPos:{configurable:!0,get:function(){return this.Ma},set:function(a){this.Ma!==a&&(z(a,"number",Vs,"portToPos"),this.Ma=a)}},portFromColOffset:{configurable:!0,get:function(){return this.w},set:function(a){this.w!==a&&(z(a,"number",Vs,"portFromColOffset"),this.w=a)}},portToColOffset:{configurable:!0,get:function(){return this.ca},set:function(a){this.ca!==a&&(z(a,"number",Vs,"portToColOffset"),
this.ca=a)}}});Vs.className="LayeredDigraphEdge";function Y(){0<arguments.length&&Da(Y);Ni.call(this);this.Ib=new H;this.To=Ws;this.ad=Xs;this.Kp=Ys;this.Tr=Zs;this.nw=[];this.Zc=!0;this.Db=$s;this.yd=(new Zb(10,10)).freeze();var a=new at(this);this.V=new bt(a);this.W=new bt(a);this.Cu=[]}ma(Y,Ni);
Y.prototype.cloneProtected=function(a){Ni.prototype.cloneProtected.call(this,a);a.To=this.To;a.Kp=this.Kp;a.Tr=this.Tr;a.Zc=this.Zc;a.Db=this.Db;a.yd.assign(this.yd);a.V.copyInheritedPropertiesFrom(this.V);a.W.copyInheritedPropertiesFrom(this.W)};
Y.prototype.hb=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):Ni.prototype.hb.call(this,a)};Y.prototype.createNetwork=function(){return new at(this)};
Y.prototype.makeNetwork=function(a){function b(a){if(a instanceof V)return!a.isLinkLabel&&"Comment"!==a.category;if(a instanceof S){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.ng(a.nodes,!0,b),c.ng(a.links,!0,b)):a instanceof xg?c.ng(a.memberParts,!1,b):c.ng(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!==ct&&(this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin));var b=this.diagram;null===b&&a instanceof P&&(b=a);this.path===Ws&&null!==b?this.ad=b.isTreePathToChildren?Xs:dt:this.ad=this.path===Ws?Xs:this.path;if(0<this.network.vertexes.count){this.network.Xp();
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.Ib.count){a=new H;for(b=this.Ib.iterator;b.next();){var c=b.value;c instanceof V?(c=this.network.Ni(c),null!==c&&a.add(c)):c instanceof bt&&a.add(c)}this.Ib=a}0===this.Ib.count&&this.findRoots();for(a=this.Ib.copy().iterator;a.next();)b=a.value,b.initialized||(b.initialized=!0,et(this,b));b=this.network.vertexes;for(a=null;a=ft(b),0<a.count;)b=gt(this,a),null!==b&&this.Ib.add(b),
b.initialized=!0,et(this,b),b=a;for(a=this.Ib.iterator;a.next();)b=a.value,b instanceof bt&&ht(this,b);for(a=this.Ib.iterator;a.next();)b=a.value,b instanceof bt&&it(this,b);for(a=this.Ib.iterator;a.next();)b=a.value,b instanceof bt&&jt(this,b);this.Nu();if(this.layerStyle===kt){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.nw=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===lt)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.Ib.iterator;a.next();)b=a.value,b instanceof bt&&this.layoutTree(b);this.arrangeTrees();this.updateParts()}this.network=null;this.Ib=new H;this.isValidLayout=!0};function ft(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.ad){case Xs:0===c.sourceEdges.count&&this.Ib.add(c);break;case dt:0===c.destinationEdges.count&&this.Ib.add(c);break;default:v("Unhandled path value "+this.ad.toString())}}0===this.Ib.count&&(a=gt(this,a),null!==a&&this.Ib.add(a))};
function gt(a,b){var c=999999,d=null;for(b=b.iterator;b.next();){var e=b.value;switch(a.ad){case Xs:e.sourceEdges.count<c&&(c=e.sourceEdges.count,d=e);break;case dt:e.destinationEdges.count<c&&(c=e.destinationEdges.count,d=e);break;default:v("Unhandled path value "+a.ad.toString())}}return d}
function et(a,b){if(null!==b){E&&w(b,bt,Y,"walkTree:v");switch(a.ad){case Xs:if(0<b.destinationEdges.count){for(var c=new F,d=b.destinationVertexes;d.next();){var e=d.value;mt(a,b,e)&&c.add(e)}0<c.count&&(b.children=c.Oa())}break;case dt:if(0<b.sourceEdges.count){c=new F;for(d=b.sourceVertexes;d.next();)e=d.value,mt(a,b,e)&&c.add(e);0<c.count&&(b.children=c.Oa())}break;default:v("Unhandled path value"+a.ad.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.Ib.remove(f)}for(b=0;b<d;b++)et(a,c[b])}}function mt(a,b,c){E&&w(b,bt,Y,"walkOK:v");E&&w(c,bt,Y,"walkOK:c");if(c.initialized){if(null===b)var d=!1;else{E&&w(c,bt,Y,"isAncestor:a");E&&w(b,bt,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,bt,Y,"removeChild:p");E&&w(b,bt,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 ht(a,b){if(null!==b){E&&w(b,bt,Y,"initializeTree:v");a.initializeTreeVertexValues(b);b.alignment===nt&&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];ht(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 ot(a,b){E&&w(b,bt,Y,"mom:v");switch(a.Kp){default:case Ys:return null!==b.parent?b.parent:a.V;case pt:return null===b.parent?a.V:null===b.parent.parent?a.W:b.parent;case qt:return null!==b.parent?null!==b.parent.parent?b.parent.parent:a.W:a.V;case rt: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.W:null!==b.parent?b.parent:a.V}}
Y.prototype.initializeTreeVertexValues=function(a){E&&w(a,bt,Y,"initializeTreeVertexValues:v");var b=ot(this,a);a.copyInheritedPropertiesFrom(b);if(null!==a.parent&&a.parent.alignment===nt){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 it(a,b){if(null!==b){E&&w(b,bt,Y,"assignTree:v");a.assignTreeVertexValues(b);b=b.children;for(var c=b.length,d=0;d<c;d++)it(a,b[d])}}Y.prototype.assignTreeVertexValues=function(){};function jt(a,b){if(null!==b){E&&w(b,bt,Y,"sortTree:v");b.alignment!==nt&&a.sortTreeVertexChildren(b);b=b.children;for(var c=b.length,d=0;d<c;d++)jt(a,b[d])}}
Y.prototype.sortTreeVertexChildren=function(a){E&&w(a,bt,Y,"sortTreeVertexChildren:v");switch(a.sorting){case st:break;case tt:a.children.reverse();break;case ut:a.children.sort(a.comparer);break;case vt:a.children.sort(a.comparer);a.children.reverse();break;default:v("Unhandled sorting value "+a.sorting.toString())}};Y.prototype.Nu=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,bt,Y,"addComments:v");var b=a.angle,c=a.parent,d=0;var e=!1;null!==c&&(d=c.angle,e=c.alignment,e=wt(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.ev();l.next();){var m=l.value;"Comment"===m.category&&m.canLayout()&&(null===a.comments&&(a.comments=[]),a.comments.push(m),m.bc(),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 wt(a){return a===xt||a===nt||a===yt||a===zt}function At(a){return a===xt||a===nt}
function Bt(a){E&&w(a,bt,Y,"isLeftSideBus:v");var b=a.parent;if(null!==b){var c=b.alignment;if(wt(c)){if(At(c)){b=b.children;for(c=0;c<b.length&&a!==b[c];)c++;return 0===c%2}if(c===yt)return!0}}return!1}
Y.prototype.layoutComments=function(a){E&&w(a,bt,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=wt(f));d=90===d||270===d;c=90===e||270===e;for(var g=0===a.childrenCount,h=Bt(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.ud();q.next();){var u=
q.value;u.fromSpot=Wd;u.toSpot=Xd}else for(n.h(a.bounds.x+2*a.focus.x-a.commentMargin,a.bounds.y+k),q.move(n),q=q.ud();q.next();)u=q.value,u.fromSpot=Xd,u.toSpot=Wd;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.ud();q.next();)u=q.value,u.fromSpot=Xd,u.toSpot=Wd;else for(n.h(a.bounds.x+a.commentMargin-r.width,a.bounds.y+k),q.move(n),q=q.ud();q.next();)u=q.value,u.fromSpot=Wd,u.toSpot=Xd;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.ud();q.next();)u=q.value,u.fromSpot=Vd,u.toSpot=de;else for(n.h(a.bounds.x+k,a.bounds.y+2*a.focus.y-a.commentMargin),q.move(n),q=q.ud();q.next();)u=q.value,u.fromSpot=de,u.toSpot=Vd;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.ud();q.next();)u=q.value,u.fromSpot=de,u.toSpot=Vd;else for(n.h(a.bounds.x+k,a.bounds.y+
a.commentMargin-r.height),q.move(n),q=q.ud();q.next();)u=q.value,u.fromSpot=Vd,u.toSpot=de;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.ad===Xs)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,bt,Y,"layoutTree:v");for(var b=a.children,c=b.length,d=0;d<c;d++)this.layoutTree(b[d]);switch(a.compaction){case Ct:Dt(this,a);break;case Et:if(a.alignment===nt)Dt(this,a);else if(E&&w(a,bt,Y,"layoutTreeBlock:v"),0===a.childrenCount)d=a.parent,c=!1,b=0,null!==d&&(b=d.angle,c=d.alignment,c=wt(c)),d=Bt(a),a.U.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.mq=null,a.yq=null;else{var e=Ft(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===Gt;var l=k===Ht,m=wt(k),n=Math.max(0,a.breadthLimit);c=It(a);var p=a.nodeSpacing,q=Lt(a),r=a.rowSpacing,u=0;if(d||l||a.zm||a.Am&&1===a.maxGenerationCount)u=Math.max(0,a.rowIndent);d=a.width;var x=a.height,y=0,A=0,C=0,G=null,I=null,O=0,R=0,U=0,ea=0,Z=0,qa=0,xa=0,Q=0;
m&&!At(k)&&135<e&&g.reverse();if(At(k))if(1<h)for(var aa=0;aa<h;aa++)0===aa%2&&aa!==h-1&&(Q=Math.max(Q,b?g[aa].xa.width:g[aa].xa.height));else 1===h&&(Q=b?g[0].xa.width:g[0].xa.height);if(m){switch(k){case xt:A=135>e?Mt(a,g,Q,y,A):Nt(a,g,Q,y,A);Q=A.x;y=A.width;A=A.height;break;case yt:for(G=0;G<h;G++)I=g[G],n=I.xa,C=0===qa?0:r,b?(I.U.h(f-n.width,ea+C),y=Math.max(y,n.width),A=Math.max(A,ea+C+n.height),ea+=C+n.height):(I.U.h(U+C,f-n.height),y=Math.max(y,U+C+n.width),A=Math.max(A,n.height),U+=C+n.width),
qa++;break;case zt:for(G=0;G<h;G++)I=g[G],f=I.xa,n=0===qa?0:r,b?(I.U.h(p/2+a.focus.x,ea+n),y=Math.max(y,f.width),A=Math.max(A,ea+n+f.height),ea+=n+f.height):(I.U.h(U+n,p/2+a.focus.y),y=Math.max(y,U+n+f.width),A=Math.max(A,f.height),U+=n+f.width),qa++}G=Ot(this,2);I=Ot(this,2);b?(G[0].h(0,0),G[1].h(0,A),I[0].h(y,0)):(G[0].h(0,0),G[1].h(y,0),I[0].h(0,A));I[1].h(y,A)}else for(aa=0;aa<h;aa++){var Ga=g[aa],yb=Ga.xa;if(b){0<n&&0<qa&&U+p+yb.width>n&&(U<f&&Pt(a,k,f-U,0,xa,aa-1),Z++,qa=0,xa=aa,C=A,U=0,ea=
135<e?-A-r:A+r);Qt(this,Ga,0,ea);var Xa=0;if(0===qa){if(G=Ga.mq,I=Ga.yq,O=yb.width,R=yb.height,null===G||null===I||e!==Ft(Ga))G=Ot(this,2),I=Ot(this,2),G[0].h(0,0),G[1].h(0,R),I[0].h(O,0),I[1].h(O,R)}else{var Sa=Qa();R=Rt(this,a,Ga,G,I,O,R,Sa);Xa=R.x;G=Sa[0];I=Sa[1];O=R.width;R=R.height;Ta(Sa);U<yb.width&&0>Xa&&(St(a,-Xa,0,xa,aa-1),Tt(G,-Xa,0),Tt(I,-Xa,0),Xa=0)}Ga.U.h(Xa,ea);y=Math.max(y,O);A=Math.max(A,C+(0===Z?0:r)+yb.height);U=O}else{0<n&&0<qa&&ea+p+yb.height>n&&(ea<f&&Pt(a,k,0,f-ea,xa,aa-1),Z++,
qa=0,xa=aa,C=y,ea=0,U=135<e?-y-r:y+r);Qt(this,Ga,U,0);Xa=0;if(0===qa){if(G=Ga.mq,I=Ga.yq,O=yb.width,R=yb.height,null===G||null===I||e!==Ft(Ga))G=Ot(this,2),I=Ot(this,2),G[0].h(0,0),G[1].h(O,0),I[0].h(0,R),I[1].h(O,R)}else Sa=Qa(),R=Rt(this,a,Ga,G,I,O,R,Sa),Xa=R.x,G=Sa[0],I=Sa[1],O=R.width,R=R.height,Ta(Sa),ea<yb.height&&0>Xa&&(St(a,0,-Xa,xa,aa-1),Tt(G,0,-Xa),Tt(I,0,-Xa),Xa=0);Ga.U.h(U,Xa);A=Math.max(A,R);y=Math.max(y,C+(0===Z?0:r)+yb.width);ea=R}qa++}0<Z&&(b?(A+=Math.max(0,c),U<y&&Pt(a,k,y-U,0,xa,
h-1),0<u&&(l||St(a,u,0,0,h-1),y+=u)):(y+=Math.max(0,c),ea<A&&Pt(a,k,0,A-ea,xa,h-1),0<u&&(l||St(a,0,u,0,h-1),A+=u)));u=l=0;switch(k){case Ut:b?l+=y/2-a.focus.x-q/2:u+=A/2-a.focus.y-q/2;break;case Vt:0<Z?b?l+=y/2-a.focus.x-q/2:u+=A/2-a.focus.y-q/2:b?(Q=g[0].U.x+g[0].ka.x,l+=Q+(g[h-1].U.x+g[h-1].ka.x+2*g[h-1].focus.x-Q)/2-a.focus.x-q/2):(Q=g[0].U.y+g[0].ka.y,u+=Q+(g[h-1].U.y+g[h-1].ka.y+2*g[h-1].focus.y-Q)/2-a.focus.y-q/2);break;case Gt:b?(l-=q,y+=q):(u-=q,A+=q);break;case Ht:b?(l+=y-a.width+q,y+=q):
(u+=A-a.height+q,A+=q);break;case xt:b?1<h?l+=Q+p/2-a.focus.x:l+=g[0].focus.x-a.focus.x+g[0].ka.x:1<h?u+=Q+p/2-a.focus.y:u+=g[0].focus.y-a.focus.y+g[0].ka.y;break;case yt:b?l+=y+p/2-a.focus.x:u+=A+p/2-a.focus.y;break;case zt:break;default:v("Unhandled alignment value "+k.toString())}for(q=0;q<h;q++)Q=g[q],b?Q.U.h(Q.U.x+Q.ka.x-l,Q.U.y+(135<e?(m?-A:-Q.xa.height)+Q.ka.y-c:x+c+Q.ka.y)):Q.U.h(Q.U.x+(135<e?(m?-y:-Q.xa.width)+Q.ka.x-c:d+c+Q.ka.x),Q.U.y+Q.ka.y-u);h=g=0;m?b?(y=Wt(a,y,l),0>l&&(l=0),135<e&&
(u+=A+c),A+=x+c,k===zt&&(g+=p/2+a.focus.x),h+=x+c):(135<e&&(l+=y+c),y+=d+c,A=Xt(a,A,u),0>u&&(u=0),k===zt&&(h+=p/2+a.focus.y),g+=d+c):b?(null===a.comments?d>y&&(y=Yt(k,d-y,0),g=y.x,h=y.y,y=d,l=0):y=Wt(a,y,l),0>l&&(g-=l,l=0),135<e&&(u+=A+c),A=Math.max(Math.max(A,x),A+x+c),h+=x+c):(135<e&&(l+=y+c),y=Math.max(Math.max(y,d),y+d+c),null===a.comments?x>A&&(A=Yt(k,0,x-A),g=A.x,h=A.y,A=x,u=0):A=Xt(a,A,u),0>u&&(h-=u,u=0),g+=d+c);if(0<Z)e=Ot(this,4),Z=Ot(this,4),b?(e[2].h(0,x+c),e[3].h(e[2].x,A),Z[2].h(y,e[2].y),
Z[3].h(Z[2].x,e[3].y)):(e[2].h(d+c,0),e[3].h(y,e[2].y),Z[2].h(e[2].x,A),Z[3].h(e[3].x,Z[2].y));else{e=Ot(this,G.length+2);Z=Ot(this,I.length+2);for(k=0;k<G.length;k++)m=G[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,x),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,x),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+x),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);Zt(this,G);Zt(this,I);a.mq=e;a.yq=Z;a.ka.h(l,u);a.xa.h(y,
A)}break;default:v("Unhandled compaction value "+a.compaction.toString())}}};
function Dt(a,b){E&&w(b,bt,Y,"layoutTreeNone:v");if(0===b.childrenCount){var c=!1,d=0;null!==b.parent&&(d=b.parent.angle,c=b.parent.alignment,c=wt(c));var e=Bt(b);b.U.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=Ft(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===Gt,n=l===Ht;h=wt(l);var p=Math.max(0,b.breadthLimit);k=It(b);var q=b.nodeSpacing,r=Lt(b),u=m||n?0:r/2,x=b.rowSpacing,y=0;if(m||n||b.zm||b.Am&&1===b.maxGenerationCount)y=Math.max(0,b.rowIndent);m=b.width;var A=b.height,C=0,G=0,I=0,O=0,R=0,U=0,ea=0,Z=0,qa=0,xa=0;h&&!At(l)&&135<d&&e.reverse();if(At(l))if(1<g)for(var Q=0;Q<g;Q++){var aa=e[Q],Ga=aa.xa;0===Q%2&&Q!==g-1?qa=Math.max(qa,(c?Ga.width:Ga.height)+$t(aa)-q):0!==Q%2&&(xa=Math.max(xa,(c?Ga.width:Ga.height)+$t(aa)-q))}else 1===g&&
(qa=c?e[0].xa.width:e[0].xa.height);if(h)switch(l){case xt:case nt:G=135>d?Mt(b,e,qa,C,G):Nt(b,e,qa,C,G);qa=G.x;C=G.width;G=G.height;break;case yt:for(a=0;a<g;a++)p=e[a],u=p.xa,I=0===ea?0:x,c?(p.U.h(f-u.width,R+I),C=Math.max(C,u.width),G=Math.max(G,R+I+u.height),R+=I+u.height):(p.U.h(O+I,f-u.height),C=Math.max(C,O+I+u.width),G=Math.max(G,u.height),O+=I+u.width),ea++;break;case zt:for(f=0;f<g;f++)a=e[f],p=a.xa,u=0===ea?0:x,c?(a.U.h(q/2+b.focus.x,R+u),C=Math.max(C,p.width),G=Math.max(G,R+u+p.height),
R+=u+p.height):(a.U.h(O+u,q/2+b.focus.y),C=Math.max(C,O+u+p.width),G=Math.max(G,p.height),O+=u+p.width),ea++}else for(xa=0;xa<g;xa++)Q=e[xa],aa=Q.xa,c?(0<p&&0<ea&&O+q+aa.width>p&&(O<f&&Pt(b,l,f-O,0,Z,xa-1),U++,ea=0,Z=xa,I=G,O=0,R=135<d?-G-x:G+x),Ga=0===ea?u:q,Qt(a,Q,0,R),Q.U.h(O+Ga,R),C=Math.max(C,O+Ga+aa.width),G=Math.max(G,I+(0===U?0:x)+aa.height),O+=Ga+aa.width):(0<p&&0<ea&&R+q+aa.height>p&&(R<f&&Pt(b,l,0,f-R,Z,xa-1),U++,ea=0,Z=xa,I=C,R=0,O=135<d?-C-x:C+x),Ga=0===ea?u:q,Qt(a,Q,O,0),Q.U.h(O,R+Ga),
G=Math.max(G,R+Ga+aa.height),C=Math.max(C,I+(0===U?0:x)+aa.width),R+=Ga+aa.height),ea++;0<U&&(c?(G+=Math.max(0,k),O<C&&Pt(b,l,C-O,0,Z,g-1),0<y&&(n||St(b,y,0,0,g-1),C+=y)):(C+=Math.max(0,k),R<G&&Pt(b,l,0,G-R,Z,g-1),0<y&&(n||St(b,0,y,0,g-1),G+=y)));y=n=0;switch(l){case Ut:c?n+=C/2-b.focus.x-r/2:y+=G/2-b.focus.y-r/2;break;case Vt:0<U?c?n+=C/2-b.focus.x-r/2:y+=G/2-b.focus.y-r/2:c?(l=e[0].U.x+e[0].ka.x,n+=l+(e[g-1].U.x+e[g-1].ka.x+2*e[g-1].focus.x-l)/2-b.focus.x-r/2):(l=e[0].U.y+e[0].ka.y,y+=l+(e[g-1].U.y+
e[g-1].ka.y+2*e[g-1].focus.y-l)/2-b.focus.y-r/2);break;case Gt:c?(n-=r,C+=r):(y-=r,G+=r);break;case Ht:c?(n+=C-b.width+r,C+=r):(y+=G-b.height+r,G+=r);break;case xt:case nt:c?1<g?n+=qa+q/2-b.focus.x:n+=e[0].focus.x-b.focus.x+e[0].ka.x:1<g?y+=qa+q/2-b.focus.y:y+=e[0].focus.y-b.focus.y+e[0].ka.y;break;case yt:c?n+=C+q/2-b.focus.x:y+=G+q/2-b.focus.y;break;case zt:break;default:v("Unhandled alignment value "+l.toString())}for(r=0;r<g;r++)l=e[r],c?l.U.h(l.U.x+l.ka.x-n,l.U.y+(135<d?(h?-G:-l.xa.height)+l.ka.y-
k:A+k+l.ka.y)):l.U.h(l.U.x+(135<d?(h?-C:-l.xa.width)+l.ka.x-k:m+k+l.ka.x),l.U.y+l.ka.y-y);c?(C=Wt(b,C,n),0>n&&(n=0),135<d&&(y+=G+k),G+=A+k):(135<d&&(n+=C+k),C+=m+k,G=Xt(b,G,y),0>y&&(y=0));b.ka.h(n,y);b.xa.h(C,G)}}
function Mt(a,b,c,d,e){E&&w(a,bt,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===Ft(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 x=$t(q)-g;q.U.h(c-(r.width+x),n+u);d=Math.max(d,r.width+x);e=Math.max(e,n+u+r.height);n+=u+r.height}else x=$t(q)-g,q.U.h(m+u,c-(r.height+x)),e=Math.max(e,r.height+x),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];x=u.xa;var y=0===l?0:h;if(k){var A=$t(u)-g;u.U.h(m+A,n+y);d=Math.max(d,m+x.width+A);e=Math.max(e,n+y+x.height);n+=y+x.height}else A=$t(u)-g,u.U.h(m+y,n+A),d=Math.max(d,m+y+x.width),e=Math.max(e,n+x.height+A),m+=y+x.width;l++}1<f&&1===f%2&&(b=b[f-1],f=b.xa,h=au(b),k?(b.U.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.U.x&&(c=bu(a,b.U.x,!1,c,g))):(b.U.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.U.y&&(c=bu(a,b.U.y,!0,c,g))));return new L(c,0,d,e)}
function Nt(a,b,c,d,e){E&&w(a,bt,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===Ft(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 x=$t(q)-g;n-=u+r.height;q.U.h(c-(r.width+x),n);d=Math.max(d,r.width+x);e=Math.max(e,Math.abs(n))}else x=$t(q)-g,m-=u+r.width,q.U.h(m,c-(r.height+x)),e=Math.max(e,r.height+x),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];x=u.xa;var y=0===l?0:h;if(k){var A=$t(u)-g;n-=y+x.height;u.U.h(m+A,n);d=Math.max(d,m+x.width+A);e=Math.max(e,Math.abs(n))}else A=$t(u)-g,m-=y+x.width,u.U.h(m,n+A),e=Math.max(e,n+x.height+A),d=Math.max(d,Math.abs(m));l++}1<f&&1===f%2&&(h=b[f-1],l=h.xa,r=au(h),k?(h.U.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.U.x&&(c=bu(a,h.U.x,!1,c,g))):(h.U.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.U.y&&(c=bu(a,h.U.y,!0,c,g))));for(a=0;a<f;a++)g=b[a],k?g.U.h(g.U.x,g.U.y+e):g.U.h(g.U.x+d,g.U.y);return new L(c,0,d,e)}function $t(a){E&&w(a,bt,Y,"fixRelativePostions:child");return null===a.parent?0:a.parent.nodeSpacing}
function au(a){E&&w(a,bt,Y,"fixRelativePostions:lastchild");return null===a.parent?0:a.parent.rowSpacing}function bu(a,b,c,d,e){E&&w(a,bt,Y,"fixRelativePostions:v");a=a.children;for(var f=a.length,g=0;g<f;g++)c?a[g].U.h(a[g].U.x,a[g].U.y-b):a[g].U.h(a[g].U.x-b,a[g].U.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 Wt(a,b,c){E&&w(a,bt,Y,"calculateSubwidth:v");switch(a.alignment){case Vt:case Ut:return c+a.width>b&&(b=c+a.width),0>c&&(b-=c),b;case Gt:return a.width>b?a.width:b;case Ht:return 2*a.focus.x>b?a.width:b+a.width-2*a.focus.x;case xt:case nt:return Math.max(a.width,Math.max(b,c+a.width)-Math.min(0,c));case yt:return a.width-a.focus.x+a.nodeSpacing/2+b;case zt:return Math.max(a.width,a.focus.x+a.nodeSpacing/2+b);default:return b}}
function Xt(a,b,c){E&&w(a,bt,Y,"calculateSubheight:v");switch(a.alignment){case Vt:case Ut:return c+a.height>b&&(b=c+a.height),0>c&&(b-=c),b;case Gt:return a.height>b?a.height:b;case Ht:return 2*a.focus.y>b?a.height:b+a.height-2*a.focus.y;case xt:case nt:return Math.max(a.height,Math.max(b,c+a.height)-Math.min(0,c));case yt:return a.height-a.focus.y+a.nodeSpacing/2+b;case zt:return Math.max(a.height,a.focus.y+a.nodeSpacing/2+b);default:return b}}
function Yt(a,b,c){E&&w(a,D,Y,"alignOffset:align");switch(a){case Ut:b/=2;c/=2;break;case Vt:b/=2;c/=2;break;case Gt:c=b=0;break;case Ht:break;default:v("Unhandled alignment value "+a.toString())}return new J(b,c)}function Pt(a,b,c,d,e,f){E&&w(a,bt,Y,"shiftRelPosAlign:v");E&&w(b,D,Y,"shiftRelPosAlign:align");b=Yt(b,c,d);St(a,b.x,b.y,e,f)}function St(a,b,c,d,e){E&&w(a,bt,Y,"shiftRelPos:v");if(0!==b||0!==c)for(a=a.children;d<=e;d++){var f=a[d].U;f.x+=b;f.y+=c}}
function Qt(a,b,c,d){E&&(w(b,bt,Y,"recordMidPoints:v"),z(c,"number",Y,"recordMidPoints:x"),z(d,"number",Y,"recordMidPoints:y"));var e=b.parent;switch(a.ad){case Xs:for(a=b.sourceEdges;a.next();)b=a.value,b.fromVertex===e&&b.relativePoint.h(c,d);break;case dt:for(a=b.destinationEdges;a.next();)b=a.value,b.toVertex===e&&b.relativePoint.h(c,d);break;default:v("Unhandled path value "+a.ad.toString())}}function Tt(a,b,c){for(var d=0;d<a.length;d++){var e=a[d];e.x+=b;e.y+=c}}
function Rt(a,b,c,d,e,f,g,h){E&&w(b,bt,Y,"mergeFringes:parent");E&&w(c,bt,Y,"mergeFringes:child");var k=Ft(b),l=90===k||270===k,m=b.nodeSpacing;b=d;var n=e;d=f;var p=g,q=c.mq,r=c.yq;g=c.xa;var u=l?Math.max(p,g.height):Math.max(d,g.width);if(null===q||k!==Ft(c))q=Ot(a,2),r=Ot(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 x=q[e];k=x.x;l=x.y;k+=d;var y=f;c+1<n.length&&(y=n[c+1]);var A=x;x=A.x;A=A.y;e+1<q.length&&(A=q[e+1],x=A.x,A=A.y,x+=d);var C=p;f.y===l?C=k-f.x:f.y>l&&f.y<A?C=k+(f.y-l)/(A-l)*(x-k)-f.x:l>f.y&&l<y.y&&(C=k-(f.x+(l-f.y)/(y.y-f.y)*(y.x-f.x)));C<p&&(p=C);y.y<=f.y?c++:A<=l?e++:(y.y<=A&&c++,A<=y.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=Ot(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=Ot(a,d);for(k=0;k<d;k++)c[k].assign(m[k]);Zt(a,m);d=c}f=r;k=p;if(null===n||2>n.length||null===f||2>f.length)e=null;else{m=Ot(a,n.length+f.length);for(e=l=c=0;c<n.length&&n[c].y<f[0].y;)y=n[c++],m[e++].h(y.x,y.y);for(;l<f.length;)y=f[l++],m[e++].h(y.x+k,y.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=Ot(a,e);for(c=0;c<e;c++)f[c].assign(m[c]);Zt(a,m);e=f}f=Math.max(0,p)+g.width;g=u;Zt(a,b);Zt(a,q);Zt(a,n);Zt(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],x=q[e],k=x.x,l=x.y,l+=p,y=f,c+1<n.length&&(y=n[c+1]),A=x,x=A.x,A=A.y,e+1<q.length&&(A=q[e+1],x=A.x,A=A.y,A+=p),C=d,f.x===k?C=l-f.y:f.x>k&&f.x<x?C=l+(f.x-k)/(x-k)*(A-l)-f.y:k>f.x&&k<y.x&&(C=l-(f.y+(k-f.x)/(y.x-f.x)*(y.y-f.y))),C<d&&(d=C),y.x<=f.x?
c++:x<=k?e++:(y.x<=x&&c++,x<=y.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=Ot(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=Ot(a,d);for(k=0;k<d;k++)c[k].assign(m[k]);Zt(a,m);d=c}f=r;k=p;if(null===n||2>n.length||null===f||2>f.length)e=null;else{m=Ot(a,n.length+f.length);
for(e=l=c=0;c<n.length&&n[c].x<f[0].x;)y=n[c++],m[e++].h(y.x,y.y);for(;l<f.length;)y=f[l++],m[e++].h(y.x,y.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=Ot(a,e);for(c=0;c<e;c++)f[c].assign(m[c]);Zt(a,m);e=f}f=u;g=Math.max(0,p)+g.height;Zt(a,b);Zt(a,q);Zt(a,n);Zt(a,r);h[0]=d;h[1]=e;return new L(p,0,f,g)}function Ot(a,b){a=a.Cu[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 Zt(a,b){var c=b.length,d=a.Cu[c];void 0===d&&(d=[],a.Cu[c]=d);d.push(b)}
Y.prototype.arrangeTrees=function(){if(this.Db===ct)for(var a=this.Ib.iterator;a.next();){var b=a.value;if(b instanceof bt){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);cu(this,b,c,d)}}}else{a=[];for(b=this.Ib.iterator;b.next();)c=b.value,c instanceof bt&&a.push(c);switch(this.sorting){case st:break;case tt:a.reverse();break;case ut:a.sort(this.comparer);break;case vt: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];cu(this,e,b+e.ka.x,c+e.ka.y);switch(this.Db){case $s:c+=e.xa.height+this.yd.height;break;case du:b+=e.xa.width+this.yd.width;break;default:v("Unhandled arrangement value "+this.Db.toString())}}}};function cu(a,b,c,d){if(null!==b){E&&w(b,bt,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];cu(a,g,c+g.U.x,d+g.U.y)}}}
Y.prototype.commitLayout=function(){this.Qv();this.commitNodes();this.Su();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.Su=function(){if(this.layerStyle===kt){for(var a=this.nw,b=[],c=null,d=this.network.vertexes.iterator;d.next();){var e=d.value;null===c?c=e.bounds.copy():c.Lc(e.bounds);var f=b[e.level];void 0===f?f=It(e):f=Math.max(f,It(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.Xc(this.nodeSpacing/2,this.layerSpacing),d=new J(-this.nodeSpacing/2,-this.layerSpacing/2)):(c.Xc(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.Qv=function(){for(var a=this.Ib.iterator;a.next();){var b=a.value;b instanceof bt&&eu(this,b)}};function eu(a,b){if(null!==b){E&&w(b,bt,Y,"setPortSpotsTree:v");a.setPortSpots(b);b=b.children;for(var c=b.length,d=0;d<c;d++)eu(a,b[d])}}
Y.prototype.setPortSpots=function(a){E&&w(a,bt,Y,"setPortSpots:v");var b=a.alignment;if(wt(b)){E&&w(a,bt,Y,"setPortSpotsBus:v");E&&w(b,D,Y,"setPortSpots:align");var c=this.ad===Xs,d=Ft(a);switch(d){case 0:var e=Xd;break;case 90:e=de;break;case 180:e=Wd;break;default:e=Vd}var f=a.children,g=f.length;switch(b){case xt:case nt: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?Wd:Vd;if(1===g||b===g-1&&1===g%2)switch(d){case 0:k=
Wd;break;case 90:k=Vd;break;case 180:k=Xd;break;default:k=de}else 0===b%2&&(k=90===d||270===d?Xd:de);c?(a.setsPortSpot&&(h.fromSpot=e),a.setsChildPortSpot&&(h.toSpot=k)):(a.setsPortSpot&&(h.fromSpot=k),a.setsChildPortSpot&&(h.toSpot=e))}}break;case yt:d=90===d||270===d?Xd:de;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 zt:for(d=
90===d||270===d?Wd:Vd,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=Ft(a),this.ad===Xs)for(e=a.destinationEdges;e.next();){if(d=e.value.link,null!==d){if(a.setsPortSpot)if(a.portSpot.Cb())switch(c){case 0:d.fromSpot=Xd;break;case 90:d.fromSpot=de;break;case 180:d.fromSpot=Wd;break;default:d.fromSpot=Vd}else d.fromSpot=a.portSpot;
if(a.setsChildPortSpot)if(a.childPortSpot.Cb())switch(c){case 0:d.toSpot=Wd;break;case 90:d.toSpot=Vd;break;case 180:d.toSpot=Xd;break;default:d.toSpot=de}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.Cb())switch(c){case 0:d.toSpot=Xd;break;case 90:d.toSpot=de;break;case 180:d.toSpot=Wd;break;default:d.toSpot=Vd}else d.toSpot=a.portSpot;if(a.setsChildPortSpot)if(a.childPortSpot.Cb())switch(c){case 0:d.fromSpot=Wd;break;
case 90:d.fromSpot=Vd;break;case 180:d.fromSpot=Xd;break;default:d.fromSpot=de}else d.fromSpot=a.childPortSpot}};function Ft(a){a=a.angle;return 45>=a?0:135>=a?90:225>=a?180:315>=a?270:0}function It(a){E&&w(a,bt,Y,"computeLayerSpacing:v");var b=Ft(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 Lt(a){E&&w(a,bt,Y,"computeNodeIndent:v");var b=Ft(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.Ib},set:function(a){this.Ib!==a&&(w(a,H,Y,"roots"),this.Ib=a,this.C())}},path:{configurable:!0,get:function(){return this.To},set:function(a){this.To!==a&&(tb(a,Y,Y,"path"),this.To=a,this.C())}},treeStyle:{configurable:!0,get:function(){return this.Kp},set:function(a){this.Db!==a&&(tb(a,Y,Y,"treeStyle"),a===Ys||a===qt||a===rt||a===pt)&&(this.Kp=a,this.C())}},layerStyle:{configurable:!0,
enumerable:!0,get:function(){return this.Tr},set:function(a){this.Db!==a&&(tb(a,Y,Y,"layerStyle"),a===Zs||a===lt||a===kt)&&(this.Tr=a,this.C())}},comments:{configurable:!0,get:function(){return this.Zc},set:function(a){this.Zc!==a&&(z(a,"boolean",Y,"comments"),this.Zc=a,this.C())}},arrangement:{configurable:!0,get:function(){return this.Db},set:function(a){this.Db!==a&&(tb(a,Y,Y,"arrangement"),a===$s||a===du||a===ct)&&(this.Db=a,this.C())}},arrangementSpacing:{configurable:!0,
enumerable:!0,get:function(){return this.yd},set:function(a){w(a,Zb,Y,"arrangementSpacing");this.yd.A(a)||(this.yd.assign(a),this.C())}},rootDefaults:{configurable:!0,get:function(){return this.V},set:function(a){this.V!==a&&(w(a,bt,Y,"rootDefaults"),this.V=a,this.C())}},alternateDefaults:{configurable:!0,get:function(){return this.W},set:function(a){this.W!==a&&(w(a,bt,Y,"alternateDefaults"),this.W=a,this.C())}},sorting:{configurable:!0,get:function(){return this.V.sorting},
set:function(a){this.V.sorting!==a&&(tb(a,Y,Y,"sorting"),a===st||a===tt||a===ut||vt)&&(this.V.sorting=a,this.C())}},comparer:{configurable:!0,get:function(){return this.V.comparer},set:function(a){this.V.comparer!==a&&(z(a,"function",Y,"comparer"),this.V.comparer=a,this.C())}},angle:{configurable:!0,get:function(){return this.V.angle},set:function(a){this.V.angle!==a&&(z(a,"number",Y,"angle"),0===a||90===a||180===a||270===a?(this.V.angle=a,this.C()):v("TreeLayout.angle must be 0, 90, 180, or 270"))}},
alignment:{configurable:!0,get:function(){return this.V.alignment},set:function(a){this.V.alignment!==a&&(tb(a,Y,Y,"alignment"),this.V.alignment=a,this.C())}},nodeIndent:{configurable:!0,get:function(){return this.V.nodeIndent},set:function(a){this.V.nodeIndent!==a&&(z(a,"number",Y,"nodeIndent"),0<=a&&(this.V.nodeIndent=a,this.C()))}},nodeIndentPastParent:{configurable:!0,get:function(){return this.V.nodeIndentPastParent},set:function(a){this.V.nodeIndentPastParent!==
a&&(z(a,"number",Y,"nodeIndentPastParent"),0<=a&&1>=a&&(this.V.nodeIndentPastParent=a,this.C()))}},nodeSpacing:{configurable:!0,get:function(){return this.V.nodeSpacing},set:function(a){this.V.nodeSpacing!==a&&(z(a,"number",Y,"nodeSpacing"),this.V.nodeSpacing=a,this.C())}},layerSpacing:{configurable:!0,get:function(){return this.V.layerSpacing},set:function(a){this.V.layerSpacing!==a&&(z(a,"number",Y,"layerSpacing"),this.V.layerSpacing=a,this.C())}},layerSpacingParentOverlap:{configurable:!0,
enumerable:!0,get:function(){return this.V.layerSpacingParentOverlap},set:function(a){this.V.layerSpacingParentOverlap!==a&&(z(a,"number",Y,"layerSpacingParentOverlap"),0<=a&&1>=a&&(this.V.layerSpacingParentOverlap=a,this.C()))}},compaction:{configurable:!0,get:function(){return this.V.compaction},set:function(a){this.V.compaction!==a&&(tb(a,Y,Y,"compaction"),a===Ct||a===Et)&&(this.V.compaction=a,this.C())}},breadthLimit:{configurable:!0,get:function(){return this.V.breadthLimit},
set:function(a){this.V.breadthLimit!==a&&(z(a,"number",Y,"breadthLimit"),0<=a&&(this.V.breadthLimit=a,this.C()))}},rowSpacing:{configurable:!0,get:function(){return this.V.rowSpacing},set:function(a){this.V.rowSpacing!==a&&(z(a,"number",Y,"rowSpacing"),this.V.rowSpacing=a,this.C())}},rowIndent:{configurable:!0,get:function(){return this.V.rowIndent},set:function(a){this.V.rowIndent!==a&&(z(a,"number",Y,"rowIndent"),0<=a&&(this.V.rowIndent=a,this.C()))}},commentSpacing:{configurable:!0,
enumerable:!0,get:function(){return this.V.commentSpacing},set:function(a){this.V.commentSpacing!==a&&(z(a,"number",Y,"commentSpacing"),this.V.commentSpacing=a,this.C())}},commentMargin:{configurable:!0,get:function(){return this.V.commentMargin},set:function(a){this.V.commentMargin!==a&&(z(a,"number",Y,"commentMargin"),this.V.commentMargin=a,this.C())}},setsPortSpot:{configurable:!0,get:function(){return this.V.setsPortSpot},set:function(a){this.V.setsPortSpot!==a&&(z(a,
"boolean",Y,"setsPortSpot"),this.V.setsPortSpot=a,this.C())}},portSpot:{configurable:!0,get:function(){return this.V.portSpot},set:function(a){w(a,M,Y,"portSpot");this.V.portSpot.A(a)||(this.V.portSpot=a,this.C())}},setsChildPortSpot:{configurable:!0,get:function(){return this.V.setsChildPortSpot},set:function(a){this.V.setsChildPortSpot!==a&&(z(a,"boolean",Y,"setsChildPortSpot"),this.V.setsChildPortSpot=a,this.C())}},childPortSpot:{configurable:!0,get:function(){return this.V.childPortSpot},
set:function(a){w(a,M,Y,"childPortSpot");this.V.childPortSpot.A(a)||(this.V.childPortSpot=a,this.C())}},alternateSorting:{configurable:!0,get:function(){return this.W.sorting},set:function(a){this.W.sorting!==a&&(tb(a,Y,Y,"alternateSorting"),a===st||a===tt||a===ut||vt)&&(this.W.sorting=a,this.C())}},alternateComparer:{configurable:!0,get:function(){return this.W.comparer},set:function(a){this.W.comparer!==a&&(z(a,"function",Y,"alternateComparer"),this.W.comparer=a,this.C())}},
alternateAngle:{configurable:!0,get:function(){return this.W.angle},set:function(a){this.W.angle!==a&&(z(a,"number",Y,"alternateAngle"),0===a||90===a||180===a||270===a)&&(this.W.angle=a,this.C())}},alternateAlignment:{configurable:!0,get:function(){return this.W.alignment},set:function(a){this.W.alignment!==a&&(tb(a,Y,Y,"alternateAlignment"),this.W.alignment=a,this.C())}},alternateNodeIndent:{configurable:!0,get:function(){return this.W.nodeIndent},set:function(a){this.W.nodeIndent!==
a&&(z(a,"number",Y,"alternateNodeIndent"),0<=a&&(this.W.nodeIndent=a,this.C()))}},alternateNodeIndentPastParent:{configurable:!0,get:function(){return this.W.nodeIndentPastParent},set:function(a){this.W.nodeIndentPastParent!==a&&(z(a,"number",Y,"alternateNodeIndentPastParent"),0<=a&&1>=a&&(this.W.nodeIndentPastParent=a,this.C()))}},alternateNodeSpacing:{configurable:!0,get:function(){return this.W.nodeSpacing},set:function(a){this.W.nodeSpacing!==a&&(z(a,"number",Y,"alternateNodeSpacing"),
this.W.nodeSpacing=a,this.C())}},alternateLayerSpacing:{configurable:!0,get:function(){return this.W.layerSpacing},set:function(a){this.W.layerSpacing!==a&&(z(a,"number",Y,"alternateLayerSpacing"),this.W.layerSpacing=a,this.C())}},alternateLayerSpacingParentOverlap:{configurable:!0,get:function(){return this.W.layerSpacingParentOverlap},set:function(a){this.W.layerSpacingParentOverlap!==a&&(z(a,"number",Y,"alternateLayerSpacingParentOverlap"),0<=a&&1>=a&&(this.W.layerSpacingParentOverlap=
a,this.C()))}},alternateCompaction:{configurable:!0,get:function(){return this.W.compaction},set:function(a){this.W.compaction!==a&&(tb(a,Y,Y,"alternateCompaction"),a===Ct||a===Et)&&(this.W.compaction=a,this.C())}},alternateBreadthLimit:{configurable:!0,get:function(){return this.W.breadthLimit},set:function(a){this.W.breadthLimit!==a&&(z(a,"number",Y,"alternateBreadthLimit"),0<=a&&(this.W.breadthLimit=a,this.C()))}},alternateRowSpacing:{configurable:!0,get:function(){return this.W.rowSpacing},
set:function(a){this.W.rowSpacing!==a&&(z(a,"number",Y,"alternateRowSpacing"),this.W.rowSpacing=a,this.C())}},alternateRowIndent:{configurable:!0,get:function(){return this.W.rowIndent},set:function(a){this.W.rowIndent!==a&&(z(a,"number",Y,"alternateRowIndent"),0<=a&&(this.W.rowIndent=a,this.C()))}},alternateCommentSpacing:{configurable:!0,get:function(){return this.W.commentSpacing},set:function(a){this.W.commentSpacing!==a&&(z(a,"number",Y,"alternateCommentSpacing"),
this.W.commentSpacing=a,this.C())}},alternateCommentMargin:{configurable:!0,get:function(){return this.W.commentMargin},set:function(a){this.W.commentMargin!==a&&(z(a,"number",Y,"alternateCommentMargin"),this.W.commentMargin=a,this.C())}},alternateSetsPortSpot:{configurable:!0,get:function(){return this.W.setsPortSpot},set:function(a){this.W.setsPortSpot!==a&&(z(a,"boolean",Y,"alternateSetsPortSpot"),this.W.setsPortSpot=a,this.C())}},alternatePortSpot:{configurable:!0,
enumerable:!0,get:function(){return this.W.portSpot},set:function(a){w(a,M,Y,"alternatePortSpot");this.W.portSpot.A(a)||(this.W.portSpot=a,this.C())}},alternateSetsChildPortSpot:{configurable:!0,get:function(){return this.W.setsChildPortSpot},set:function(a){this.W.setsChildPortSpot!==a&&(z(a,"boolean",Y,"alternateSetsChildPortSpot"),this.W.setsChildPortSpot=a,this.C())}},alternateChildPortSpot:{configurable:!0,get:function(){return this.W.childPortSpot},set:function(a){w(a,
M,Y,"alternateChildPortSpot");this.W.childPortSpot.A(a)||(this.W.childPortSpot=a,this.C())}}});
var Ws=new D(Y,"PathDefault",-1),Xs=new D(Y,"PathDestination",0),dt=new D(Y,"PathSource",1),st=new D(Y,"SortingForwards",10),tt=new D(Y,"SortingReverse",11),ut=new D(Y,"SortingAscending",12),vt=new D(Y,"SortingDescending",13),Ut=new D(Y,"AlignmentCenterSubtrees",20),Vt=new D(Y,"AlignmentCenterChildren",21),Gt=new D(Y,"AlignmentStart",22),Ht=new D(Y,"AlignmentEnd",23),xt=new D(Y,"AlignmentBus",24),nt=new D(Y,"AlignmentBusBranching",25),yt=new D(Y,"AlignmentTopLeftBus",26),zt=new D(Y,"AlignmentBottomRightBus",
27),Ct=new D(Y,"CompactionNone",30),Et=new D(Y,"CompactionBlock",31),Ys=new D(Y,"StyleLayered",40),rt=new D(Y,"StyleLastParents",41),qt=new D(Y,"StyleAlternating",42),pt=new D(Y,"StyleRootOnly",43),$s=new D(Y,"ArrangementVertical",50),du=new D(Y,"ArrangementHorizontal",51),ct=new D(Y,"ArrangementFixedRoots",52),Zs=new D(Y,"LayerIndividual",60),lt=new D(Y,"LayerSiblings",61),kt=new D(Y,"LayerUniform",62);Y.className="TreeLayout";Y.PathDefault=Ws;Y.PathDestination=Xs;Y.PathSource=dt;
Y.SortingForwards=st;Y.SortingReverse=tt;Y.SortingAscending=ut;Y.SortingDescending=vt;Y.AlignmentCenterSubtrees=Ut;Y.AlignmentCenterChildren=Vt;Y.AlignmentStart=Gt;Y.AlignmentEnd=Ht;Y.AlignmentBus=xt;Y.AlignmentBusBranching=nt;Y.AlignmentTopLeftBus=yt;Y.AlignmentBottomRightBus=zt;Y.CompactionNone=Ct;Y.CompactionBlock=Et;Y.StyleLayered=Ys;Y.StyleLastParents=rt;Y.StyleAlternating=qt;Y.StyleRootOnly=pt;Y.ArrangementVertical=$s;Y.ArrangementHorizontal=du;Y.ArrangementFixedRoots=ct;Y.LayerIndividual=Zs;
Y.LayerSiblings=lt;Y.LayerUniform=kt;function at(a){Rp.call(this,a)}ma(at,Rp);at.prototype.createVertex=function(){return new bt(this)};at.prototype.createEdge=function(){return new fu(this)};at.className="TreeNetwork";
function bt(a){Up.call(this,a);this.Ma=!1;this.Nc=null;this.L=[];this.Xb=this.Wb=this.ca=this.Na=0;this.Zc=null;this.U=new J(0,0);this.xa=new Zb(0,0);this.ka=new J(0,0);this.Am=this.zm=this.$z=!1;this.yq=this.mq=null;this.Tc=st;this.Pc=$p;this.Bc=0;this.xb=Vt;this.es=this.ds=0;this.gs=20;this.me=50;this.Sr=0;this.ar=Et;this.Uq=0;this.ss=25;this.$q=this.rs=10;this.Zq=20;this.Bs=!0;this.os=Qd;this.As=!0;this.Xq=Qd}ma(bt,Up);
bt.prototype.copyInheritedPropertiesFrom=function(a){null!==a&&(this.Tc=a.sorting,this.Pc=a.comparer,this.Bc=a.angle,this.xb=a.alignment,this.ds=a.nodeIndent,this.es=a.nodeIndentPastParent,this.gs=a.nodeSpacing,this.me=a.layerSpacing,this.Sr=a.layerSpacingParentOverlap,this.ar=a.compaction,this.Uq=a.breadthLimit,this.ss=a.rowSpacing,this.rs=a.rowIndent,this.$q=a.commentSpacing,this.Zq=a.commentMargin,this.Bs=a.setsPortSpot,this.os=a.portSpot,this.As=a.setsChildPortSpot,this.Xq=a.childPortSpot)};
na.Object.defineProperties(bt.prototype,{initialized:{configurable:!0,get:function(){return this.Ma},set:function(a){this.Ma!==a&&(z(a,"boolean",bt,"initialized"),this.Ma=a)}},parent:{configurable:!0,get:function(){return this.Nc},set:function(a){this.Nc!==a&&(E&&null!==a&&w(a,bt,bt,"parent"),this.Nc=a)}},children:{configurable:!0,get:function(){return this.L},set:function(a){if(this.L!==a){null===a||Array.isArray(a)||Ba(a,"Array",bt,"children:value");if(null!==
a)for(var b=a.length,c=0;c<b;c++){var d=a[c];E&&w(d,bt,bt,"children")}this.L=a}}},level:{configurable:!0,get:function(){return this.Na},set:function(a){this.Na!==a&&(z(a,"number",bt,"level"),this.Na=a)}},descendantCount:{configurable:!0,get:function(){return this.ca},set:function(a){this.ca!==a&&(z(a,"number",bt,"descendantCount"),this.ca=a)}},maxChildrenCount:{configurable:!0,get:function(){return this.Wb},set:function(a){this.Wb!==a&&(z(a,"number",bt,"maxChildrenCount"),
this.Wb=a)}},maxGenerationCount:{configurable:!0,get:function(){return this.Xb},set:function(a){this.Xb!==a&&(z(a,"number",bt,"maxGenerationCount"),this.Xb=a)}},comments:{configurable:!0,get:function(){return this.Zc},set:function(a){if(this.Zc!==a){null===a||Array.isArray(a)||Ba(a,"Array",bt,"comments:value");if(null!==a)for(var b=a.length,c=0;c<b;c++){var d=a[c];E&&w(d,V,bt,"comments")}this.Zc=a}}},sorting:{configurable:!0,get:function(){return this.Tc},
set:function(a){this.Tc!==a&&(tb(a,Y,bt,"sorting"),this.Tc=a)}},comparer:{configurable:!0,get:function(){return this.Pc},set:function(a){this.Pc!==a&&(z(a,"function",bt,"comparer"),this.Pc=a)}},angle:{configurable:!0,get:function(){return this.Bc},set:function(a){this.Bc!==a&&(z(a,"number",bt,"angle"),this.Bc=a)}},alignment:{configurable:!0,get:function(){return this.xb},set:function(a){this.xb!==a&&(tb(a,Y,bt,"alignment"),this.xb=a)}},nodeIndent:{configurable:!0,
enumerable:!0,get:function(){return this.ds},set:function(a){this.ds!==a&&(z(a,"number",bt,"nodeIndent"),this.ds=a)}},nodeIndentPastParent:{configurable:!0,get:function(){return this.es},set:function(a){this.es!==a&&(z(a,"number",bt,"nodeIndentPastParent"),this.es=a)}},nodeSpacing:{configurable:!0,get:function(){return this.gs},set:function(a){this.gs!==a&&(z(a,"number",bt,"nodeSpacing"),this.gs=a)}},layerSpacing:{configurable:!0,get:function(){return this.me},
set:function(a){this.me!==a&&(z(a,"number",bt,"layerSpacing"),this.me=a)}},layerSpacingParentOverlap:{configurable:!0,get:function(){return this.Sr},set:function(a){this.Sr!==a&&(z(a,"number",bt,"layerSpacingParentOverlap"),this.Sr=a)}},compaction:{configurable:!0,get:function(){return this.ar},set:function(a){this.ar!==a&&(tb(a,Y,bt,"compaction"),this.ar=a)}},breadthLimit:{configurable:!0,get:function(){return this.Uq},set:function(a){this.Uq!==a&&(z(a,"number",
bt,"breadthLimit"),this.Uq=a)}},rowSpacing:{configurable:!0,get:function(){return this.ss},set:function(a){this.ss!==a&&(z(a,"number",bt,"rowSpacing"),this.ss=a)}},rowIndent:{configurable:!0,get:function(){return this.rs},set:function(a){this.rs!==a&&(z(a,"number",bt,"rowIndent"),this.rs=a)}},commentSpacing:{configurable:!0,get:function(){return this.$q},set:function(a){this.$q!==a&&(z(a,"number",bt,"commentSpacing"),this.$q=a)}},commentMargin:{configurable:!0,
enumerable:!0,get:function(){return this.Zq},set:function(a){this.Zq!==a&&(z(a,"number",bt,"commentMargin"),this.Zq=a)}},setsPortSpot:{configurable:!0,get:function(){return this.Bs},set:function(a){this.Bs!==a&&(z(a,"boolean",bt,"setsPortSpot"),this.Bs=a)}},portSpot:{configurable:!0,get:function(){return this.os},set:function(a){w(a,M,bt,"portSpot");this.os.A(a)||(this.os=a)}},setsChildPortSpot:{configurable:!0,get:function(){return this.As},set:function(a){this.As!==
a&&(z(a,"boolean",bt,"setsChildPortSpot"),this.As=a)}},childPortSpot:{configurable:!0,get:function(){return this.Xq},set:function(a){w(a,M,bt,"childPortSpot");this.Xq.A(a)||(this.Xq=a)}},childrenCount:{configurable:!0,get:function(){return this.children.length}},relativePosition:{configurable:!0,get:function(){return this.U},set:function(a){this.U.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)}}});bt.className="TreeVertex";function fu(a){Vp.call(this,a);this.tu=new J(0,0)}ma(fu,Vp);
fu.prototype.commit=function(){var a=this.link;if(null!==a&&!a.isAvoiding){var b=this.network.layout,c=null,d=null;switch(b.ad){case Xs:c=this.fromVertex;d=this.toVertex;break;case dt:c=this.toVertex;d=this.fromVertex;break;default:v("Unhandled path value "+b.ad.toString())}if(null!==c&&null!==d)if(b=this.tu,0!==b.x||0!==b.y||c.$z){d=c.bounds;var e=Ft(c),f=It(c),g=c.rowSpacing;a.cj();var h=a.curve===fh,k=a.isOrthogonal,l;a.Eh();if(k||h){for(l=2;4<a.pointsCount;)a.Gv(2);var m=a.i(1);var n=a.i(2)}else{for(l=
1;3<a.pointsCount;)a.Gv(1);m=a.i(0);n=a.i(a.pointsCount-1)}var p=a.i(a.pointsCount-1);0===e?(c.alignment===Ht?(e=d.bottom+b.y,0===b.y&&m.y>p.y+c.rowIndent&&(e=Math.min(e,Math.max(m.y,e-Lt(c))))):c.alignment===Gt?(e=d.top+b.y,0===b.y&&m.y<p.y-c.rowIndent&&(e=Math.max(e,Math.min(m.y,e+Lt(c))))):e=c.zm||c.Am&&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===Ht?(e=d.right+b.x,0===b.x&&m.x>p.x+c.rowIndent&&(e=Math.min(e,Math.max(m.x,e-Lt(c))))):c.alignment===Gt?(e=d.left+b.x,0===b.x&&m.x<p.x-c.rowIndent&&(e=Math.max(e,Math.min(m.x,e+Lt(c))))):e=c.zm||c.Am&&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===Ht?(e=d.bottom+b.y,0===b.y&&m.y>p.y+c.rowIndent&&(e=Math.min(e,Math.max(m.y,e-Lt(c))))):c.alignment===Gt?(e=d.top+b.y,0===b.y&&m.y<p.y-c.rowIndent&&(e=Math.max(e,Math.min(m.y,e+Lt(c))))):e=c.zm||c.Am&&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===Ht?(e=d.right+b.x,0===b.x&&m.x>p.x+c.rowIndent&&(e=Math.min(e,Math.max(m.x,e-Lt(c))))):c.alignment===Gt?(e=d.left+b.x,0===b.x&&m.x<p.x-c.rowIndent&&(e=Math.max(e,Math.min(m.x,e+Lt(c))))):e=c.zm||c.Am&&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.nf()}else b=d,E&&w(c,bt,fu,"adjustRouteForAngleChange:parent"),E&&w(b,bt,fu,"adjustRouteForAngleChange:child"),a=this.link,f=Ft(c),f!==Ft(b)&&(g=It(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.cj(),c=a.curve===fh,b=a.isOrthogonal,d=wt(this.fromVertex.alignment),a.Eh(),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.nf()))}};
na.Object.defineProperties(fu.prototype,{relativePoint:{configurable:!0,get:function(){return this.tu},set:function(a){this.tu.set(a)}}});fu.className="TreeEdge";
$a.prototype.initializeStandardTools=function(){If(this,"Action",new sh,this.mouseDownTools);If(this,"Relinking",new ag,this.mouseDownTools);If(this,"LinkReshaping",new dh,this.mouseDownTools);If(this,"Rotating",new qh,this.mouseDownTools);If(this,"Resizing",new kh,this.mouseDownTools);If(this,"Linking",new Sg,this.mouseMoveTools);If(this,"Dragging",new Kf,this.mouseMoveTools);If(this,"DragSelecting",new vh,this.mouseMoveTools);If(this,"Panning",new wh,this.mouseMoveTools);If(this,"ContextMenu",new yh,
this.mouseUpTools);If(this,"TextEditing",new Jh,this.mouseUpTools);If(this,"ClickCreating",new th,this.mouseUpTools);If(this,"ClickSelecting",new rh,this.mouseUpTools)};yn("Horizontal",new Em);yn("Spot",new Gm);yn("Table",new Km);yn("Viewbox",new Pm);yn("TableRow",new Nm);yn("TableColumn",new Om);yn("Graduated",new Ym);Hi.add(Zq.type,sq);Hi.add(br.type,Gq);
var gu=ra.go,hu={get licenseKey(){return P.licenseKey},set licenseKey(a){P.licenseKey=a},get version(){return P.version},Group:xg,EnumValue:D,List:F,Set:H,Map:Ub,Point:J,Size:Zb,Rect:L,Margin:Hc,Spot:M,Geometry:me,PathFigure:Xe,PathSegment:Ye,InputEvent:kf,DiagramEvent:mf,ChangedEvent:nf,Model:X,GraphLinksModel:Zq,TreeModel:br,Binding:Ti,Transaction:sf,UndoManager:tf,CommandHandler:Wk,Tool:vf,DraggingTool:Kf,DraggingInfo:bg,LinkingBaseTool:Gg,LinkingTool:Sg,RelinkingTool:ag,LinkReshapingTool:dh,ResizingTool:kh,
RotatingTool:qh,ClickSelectingTool:rh,ActionTool:sh,ClickCreatingTool:th,HTMLInfo:Hf,ContextMenuTool:yh,DragSelectingTool:vh,PanningTool:wh,TextEditingTool:Jh,ToolManager:$a,AnimationManager:bi,Layer:ui,Diagram:P,Palette:Qk,Overview:Sk,Brush:yl,GraphObject:N,Panel:W,RowColumnDefinition:ek,Shape:Hg,TextBlock:Kh,TextBlockMetrics:$m,Picture:kk,Part:T,Adornment:Cf,Node:V,Link:S,Placeholder:lh,Layout:Ni,LayoutNetwork:Rp,LayoutVertex:Up,LayoutEdge:Vp,GridLayout:Rk,PanelLayout:Sl,CircularLayout:cr,CircularNetwork:ur,
CircularVertex:Hr,CircularEdge:Ir,ForceDirectedLayout:Jr,ForceDirectedNetwork:Kr,ForceDirectedVertex:Ur,ForceDirectedEdge:Yr,LayeredDigraphLayout:Zr,LayeredDigraphNetwork:ds,LayeredDigraphVertex:Us,LayeredDigraphEdge:Vs,TreeLayout:Y,TreeNetwork:at,TreeVertex:bt,TreeEdge:fu};gu&&gu.version!==hu.version&&v("WARNING: a `go` object on the root object is already defined with a version mismatch."+gu.version+". Replaced with version: "+hu.version);ra.go=hu;
("undefined"===typeof ra||"undefined"===typeof ra.module||"object"!==typeof ra.module.exports)&&ra.define&&"function"===typeof ra.define&&ra.define.amd&&ra.define(hu);hu.Debug=E;E.uy(hu); 'undefined'!==typeof module&&'object'===typeof module.exports&&(module.exports='undefined'!==typeof global?global.go:self.go); })();
|
var TupleDictionary = require(__dirname + '/../../src/utils/TupleDictionary');
exports.construct = function(test){
var dict = new TupleDictionary();
test.done();
};
exports.getKey = function(test){
var dict = new TupleDictionary();
var key = dict.getKey(1, 2);
test.ok(typeof key === 'number');
test.done();
};
exports.get = function(test){
var dict = new TupleDictionary();
var a = { id: 1 };
var b = { id: 2 };
var c = { id: 3 };
dict.set(a.id, b.id, c);
var obj = dict.get(a.id, b.id);
test.deepEqual(obj, c, 'could not get by keys');
obj = dict.get(b.id, a.id);
test.deepEqual(obj, c, 'could not get by flipped keys');
obj = dict.get(3, 4, c);
test.equal(obj, undefined, 'could not get unset');
test.done();
};
exports.set = function(test){
var dict = new TupleDictionary();
dict.set(1, 2, 3);
var key = dict.getKey(1,2);
test.deepEqual(dict.keys, [key]);
test.equal(dict.data[key], 3);
dict.set(2, 1, 3);
test.deepEqual(dict.keys, [key]);
dict.set(2, 1, 3);
test.deepEqual(dict.keys, [key]);
test.done();
};
exports.reset = function(test){
var dict = new TupleDictionary();
dict.set(1, 2, 1);
dict.set(3, 4, 1);
dict.reset();
test.equal(dict.keys.length, 0);
test.done();
};
exports.copy = function(test){
var dict1 = new TupleDictionary();
var dict2 = new TupleDictionary();
dict1.set(1, 2, 1);
dict1.set(2, 3, 2);
dict1.set(4, 3, 3);
dict2.copy(dict1);
test.deepEqual(dict1, dict2);
test.done();
}; |
var _ = require('./utils');
var errors = module.exports;
var canCapture = (typeof Error.captureStackTrace === 'function');
var canStack = !!(new Error()).stack;
function ErrorAbstract(msg, constructor) {
this.message = msg;
Error.call(this, this.message);
if (canCapture) {
Error.captureStackTrace(this, constructor);
}
else if (canStack) {
this.stack = (new Error()).stack;
}
else {
this.stack = '';
}
}
errors._Abstract = ErrorAbstract;
_.inherits(ErrorAbstract, Error);
/**
* Connection Error
* @param {String} [msg] - An error message that will probably end up in a log.
*/
errors.ConnectionFault = function ConnectionFault(msg) {
ErrorAbstract.call(this, msg || 'Connection Failure', errors.ConnectionFault);
};
_.inherits(errors.ConnectionFault, ErrorAbstract);
/**
* No Living Connections
* @param {String} [msg] - An error message that will probably end up in a log.
*/
errors.NoConnections = function NoConnections(msg) {
ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections);
};
_.inherits(errors.NoConnections, ErrorAbstract);
/**
* Generic Error
* @param {String} [msg] - An error message that will probably end up in a log.
*/
errors.Generic = function Generic(msg) {
ErrorAbstract.call(this, msg || 'Generic Error', errors.Generic);
};
_.inherits(errors.Generic, ErrorAbstract);
/**
* Request Timeout Error
* @param {String} [msg] - An error message that will probably end up in a log.
*/
errors.RequestTimeout = function RequestTimeout(msg) {
ErrorAbstract.call(this, msg || 'Request Timeout', errors.RequestTimeout);
};
_.inherits(errors.RequestTimeout, ErrorAbstract);
/**
* Request Body could not be parsed
* @param {String} [msg] - An error message that will probably end up in a log.
*/
errors.Serialization = function Serialization(msg) {
ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization);
};
_.inherits(errors.Serialization, ErrorAbstract);
/**
* Thrown when a browser compatability issue is detected (cough, IE, cough)
*/
errors.RequestTypeError = function RequestTypeError(feature) {
ErrorAbstract.call(this, 'Cross-domain AJAX requests ' + feature + ' are not supported', errors.RequestTypeError);
};
_.inherits(errors.RequestTypeError, ErrorAbstract);
var statusCodes = {
/**
* GatewayTimeout
* @param {String} [msg] - An error message that will probably end up in a log.
*/
504: 'Gateway Timeout',
/**
* ServiceUnavailable
* @param {String} [msg] - An error message that will probably end up in a log.
*/
503: 'Service Unavailable',
/**
* InternalServerError
* @param {String} [msg] - An error message that will probably end up in a log.
*/
500: 'Internal Server Error',
/**
* PreconditionFailed
* @param {String} [msg] - An error message that will probably end up in a log.
*/
412: 'Precondition Failed',
/**
* Conflict
* @param {String} [msg] - An error message that will probably end up in a log.
*/
409: 'Conflict',
/**
* AuthorizationException
* @param {String} [msg] - An error message that will probably end up in a log.
*/
403: 'Authorization Exception',
/**
* NotFound
* @param {String} [msg] - An error message that will probably end up in a log.
*/
404: 'Not Found',
/**
* AuthenticationException
* @param {String} [msg] - An error message that will probably end up in a log.
*/
401: 'Authentication Exception',
/**
* BadRequest
* @param {String} [msg] - An error message that will probably end up in a log.
*/
400: 'Bad Request',
/**
* MovedPermanently
* @param {String} [msg] - An error message that will probably end up in a log.
*/
301: 'Moved Permanently'
};
_.each(statusCodes, function (name, status) {
var className = _.studlyCase(name);
function StatusCodeError(msg) {
ErrorAbstract.call(this, msg || name, StatusCodeError);
}
_.inherits(StatusCodeError, ErrorAbstract);
errors[className] = StatusCodeError;
errors[status] = StatusCodeError;
}); |
import React from 'react'
export default React.createClass({
render() {
return <div className="browser-component--dev-panel">
{this.props.children}
</div>
}
})
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { elementTypeAcceptingRef } from '@material-ui/utils';
import capitalize from '../utils/capitalize';
import withStyles from '../styles/withStyles';
import useIsFocusVisible from '../utils/useIsFocusVisible';
import useForkRef from '../utils/useForkRef';
import Typography from '../Typography';
export var styles = {
/* Styles applied to the root element. */
root: {},
/* Styles applied to the root element if `underline="none"`. */
underlineNone: {
textDecoration: 'none'
},
/* Styles applied to the root element if `underline="hover"`. */
underlineHover: {
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline'
}
},
/* Styles applied to the root element if `underline="always"`. */
underlineAlways: {
textDecoration: 'underline'
},
// Same reset as ButtonBase.root
/* Styles applied to the root element if `component="button"`. */
button: {
position: 'relative',
WebkitTapHighlightColor: 'transparent',
backgroundColor: 'transparent',
// Reset default value
// We disable the focus ring for mouse, touch and keyboard users.
outline: 0,
border: 0,
margin: 0,
// Remove the margin in Safari
borderRadius: 0,
padding: 0,
// Remove the padding in Firefox
cursor: 'pointer',
userSelect: 'none',
verticalAlign: 'middle',
'-moz-appearance': 'none',
// Reset
'-webkit-appearance': 'none',
// Reset
'&::-moz-focus-inner': {
borderStyle: 'none' // Remove Firefox dotted outline.
},
'&$focusVisible': {
outline: 'auto'
}
},
/* Pseudo-class applied to the root element if the link is keyboard focused. */
focusVisible: {}
};
var Link = /*#__PURE__*/React.forwardRef(function Link(props, ref) {
var classes = props.classes,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'primary' : _props$color,
_props$component = props.component,
component = _props$component === void 0 ? 'a' : _props$component,
onBlur = props.onBlur,
onFocus = props.onFocus,
TypographyClasses = props.TypographyClasses,
_props$underline = props.underline,
underline = _props$underline === void 0 ? 'hover' : _props$underline,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'inherit' : _props$variant,
other = _objectWithoutProperties(props, ["classes", "className", "color", "component", "onBlur", "onFocus", "TypographyClasses", "underline", "variant"]);
var _useIsFocusVisible = useIsFocusVisible(),
isFocusVisibleRef = _useIsFocusVisible.isFocusVisibleRef,
handleBlurVisible = _useIsFocusVisible.onBlur,
handleFocusVisible = _useIsFocusVisible.onFocus,
focusVisibleRef = _useIsFocusVisible.ref;
var _React$useState = React.useState(false),
focusVisible = _React$useState[0],
setFocusVisible = _React$useState[1];
var handlerRef = useForkRef(ref, focusVisibleRef);
var handleBlur = function handleBlur(event) {
handleBlurVisible(event);
if (isFocusVisibleRef.current === false) {
setFocusVisible(false);
}
if (onBlur) {
onBlur(event);
}
};
var handleFocus = function handleFocus(event) {
handleFocusVisible(event);
if (isFocusVisibleRef.current === true) {
setFocusVisible(true);
}
if (onFocus) {
onFocus(event);
}
};
return /*#__PURE__*/React.createElement(Typography, _extends({
className: clsx(classes.root, classes["underline".concat(capitalize(underline))], className, focusVisible && classes.focusVisible, component === 'button' && classes.button),
classes: TypographyClasses,
color: color,
component: component,
onBlur: handleBlur,
onFocus: handleFocus,
ref: handlerRef,
variant: variant
}, other));
});
process.env.NODE_ENV !== "production" ? Link.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the link.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the link.
* @default 'primary'
*/
color: PropTypes.oneOf(['error', 'inherit', 'initial', 'primary', 'secondary', 'textPrimary', 'textSecondary']),
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: elementTypeAcceptingRef,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* `classes` prop applied to the [`Typography`](/api/typography/) element.
*/
TypographyClasses: PropTypes.object,
/**
* Controls when the link should have an underline.
* @default 'hover'
*/
underline: PropTypes.oneOf(['always', 'hover', 'none']),
/**
* Applies the theme typography styles.
* @default 'inherit'
*/
variant: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['body1', 'body2', 'button', 'caption', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'inherit', 'overline', 'subtitle1', 'subtitle2']), PropTypes.string])
} : void 0;
export default withStyles(styles, {
name: 'MuiLink'
})(Link); |
// Convert straight quotation marks to typographic ones
//
'use strict';
var isWhiteSpace = require('../common/utils').isWhiteSpace;
var isPunctChar = require('../common/utils').isPunctChar;
var isMdAsciiPunct = require('../common/utils').isMdAsciiPunct;
var QUOTE_TEST_RE = /['"]/;
var QUOTE_RE = /['"]/g;
var APOSTROPHE = '\u2019'; /* ’ */
function replaceAt(str, index, ch) {
return str.substr(0, index) + ch + str.substr(index + 1);
}
function process_inlines(tokens, state) {
var i, token, text, t, pos, max, thisLevel, item, lastChar, nextChar,
isLastPunctChar, isNextPunctChar, isLastWhiteSpace, isNextWhiteSpace,
canOpen, canClose, j, isSingle, stack;
stack = [];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
thisLevel = tokens[i].level;
for (j = stack.length - 1; j >= 0; j--) {
if (stack[j].level <= thisLevel) { break; }
}
stack.length = j + 1;
if (token.type !== 'text') { continue; }
text = token.content;
pos = 0;
max = text.length;
/*eslint no-labels:0,block-scoped-var:0*/
OUTER:
while (pos < max) {
QUOTE_RE.lastIndex = pos;
t = QUOTE_RE.exec(text);
if (!t) { break; }
canOpen = canClose = true;
pos = t.index + 1;
isSingle = (t[0] === "'");
// treat begin/end of the line as a whitespace
lastChar = t.index - 1 >= 0 ? text.charCodeAt(t.index - 1) : 0x20;
nextChar = pos < max ? text.charCodeAt(pos) : 0x20;
isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
isLastWhiteSpace = isWhiteSpace(lastChar);
isNextWhiteSpace = isWhiteSpace(nextChar);
if (isNextWhiteSpace) {
canOpen = false;
} else if (isNextPunctChar) {
if (!(isLastWhiteSpace || isLastPunctChar)) {
canOpen = false;
}
}
if (isLastWhiteSpace) {
canClose = false;
} else if (isLastPunctChar) {
if (!(isNextWhiteSpace || isNextPunctChar)) {
canClose = false;
}
}
if (nextChar === 0x22 /* " */ && t[0] === '"') {
if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) {
// special case: 1"" - count first quote as an inch
canClose = canOpen = false;
}
}
if (canOpen && canClose) {
// treat this as the middle of the word
canOpen = false;
canClose = isNextPunctChar;
}
if (!canOpen && !canClose) {
// middle of word
if (isSingle) {
token.content = replaceAt(token.content, t.index, APOSTROPHE);
}
continue;
}
if (canClose) {
// this could be a closing quote, rewind the stack to get a match
for (j = stack.length - 1; j >= 0; j--) {
item = stack[j];
if (stack[j].level < thisLevel) { break; }
if (item.single === isSingle && stack[j].level === thisLevel) {
item = stack[j];
if (isSingle) {
tokens[item.token].content = replaceAt(
tokens[item.token].content, item.pos, state.md.options.quotes[2]);
token.content = replaceAt(
token.content, t.index, state.md.options.quotes[3]);
} else {
tokens[item.token].content = replaceAt(
tokens[item.token].content, item.pos, state.md.options.quotes[0]);
token.content = replaceAt(token.content, t.index, state.md.options.quotes[1]);
}
stack.length = j;
continue OUTER;
}
}
}
if (canOpen) {
stack.push({
token: i,
pos: t.index,
single: isSingle,
level: thisLevel
});
} else if (canClose && isSingle) {
token.content = replaceAt(token.content, t.index, APOSTROPHE);
}
}
}
}
module.exports = function smartquotes(state) {
/*eslint max-depth:0*/
var blkIdx;
if (!state.md.options.typographer) { return; }
for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
if (state.tokens[blkIdx].type !== 'inline' ||
!QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
continue;
}
process_inlines(state.tokens[blkIdx].children, state);
}
};
|
/* DOM Level2 Events implemented as described here:
*
* http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html
*
*/
var core = require("./core").dom.level2.core,
utils = require("../utils"),
defineGetter = utils.defineGetter,
defineSetter = utils.defineSetter,
inheritFrom = utils.inheritFrom;
// modify cloned instance for more info check: https://github.com/tmpvar/jsdom/issues/325
core = Object.create(core);
var events = {};
events.EventException = function() {
if (arguments.length > 0) {
this._code = arguments[0];
} else {
this._code = 0;
}
if (arguments.length > 1) {
this._message = arguments[1];
} else {
this._message = "Unspecified event type";
}
Error.call(this, this._message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, events.EventException);
}
};
inheritFrom(Error, events.EventException, {
UNSPECIFIED_EVENT_TYPE_ERR : 0,
get code() { return this._code;}
});
events.Event = function(eventType) {
this._eventType = eventType;
this._type = null;
this._bubbles = null;
this._cancelable = null;
this._target = null;
this._currentTarget = null;
this._eventPhase = null;
this._timeStamp = null;
this._preventDefault = false;
this._stopPropagation = false;
};
events.Event.prototype = {
initEvent: function(type, bubbles, cancelable) {
this._type = type;
this._bubbles = bubbles;
this._cancelable = cancelable;
},
preventDefault: function() {
if (this._cancelable) {
this._preventDefault = true;
}
},
stopPropagation: function() {
this._stopPropagation = true;
},
CAPTURING_PHASE : 1,
AT_TARGET : 2,
BUBBLING_PHASE : 3,
get eventType() { return this._eventType; },
get type() { return this._type; },
get bubbles() { return this._bubbles; },
get cancelable() { return this._cancelable; },
get target() { return this._target; },
get currentTarget() { return this._currentTarget; },
get eventPhase() { return this._eventPhase; },
get timeStamp() { return this._timeStamp; }
};
events.UIEvent = function(eventType) {
events.Event.call(this, eventType);
this.view = null;
this.detail = null;
};
inheritFrom(events.Event, events.UIEvent, {
initUIEvent: function(type, bubbles, cancelable, view, detail) {
this.initEvent(type, bubbles, cancelable);
this.view = view;
this.detail = detail;
},
});
events.MouseEvent = function(eventType) {
events.UIEvent.call(this, eventType);
this.screenX = null;
this.screenY = null;
this.clientX = null;
this.clientY = null;
this.ctrlKey = null;
this.shiftKey = null;
this.altKey = null;
this.metaKey = null;
this.button = null;
this.relatedTarget = null;
};
inheritFrom(events.UIEvent, events.MouseEvent, {
initMouseEvent: function(type,
bubbles,
cancelable,
view,
detail,
screenX,
screenY,
clientX,
clientY,
ctrlKey,
altKey,
shiftKey,
metaKey,
button,
relatedTarget) {
this.initUIEvent(type, bubbles, cancelable, view, detail);
this.screenX = screenX
this.screenY = screenY
this.clientX = clientX
this.clientY = clientY
this.ctrlKey = ctrlKey
this.shiftKey = shiftKey
this.altKey = altKey
this.metaKey = metaKey
this.button = button
this.relatedTarget = relatedTarget
}
});
events.MutationEvent = function(eventType) {
events.Event.call(this, eventType);
this.relatedNode = null;
this.prevValue = null;
this.newValue = null;
this.attrName = null;
this.attrChange = null;
};
inheritFrom(events.Event, events.MutationEvent, {
initMutationEvent: function(type,
bubbles,
cancelable,
relatedNode,
prevValue,
newValue,
attrName,
attrChange) {
this.initEvent(type, bubbles, cancelable);
this.relatedNode = relatedNode;
this.prevValue = prevValue;
this.newValue = newValue;
this.attrName = attrName;
this.attrChange = attrChange;
},
MODIFICATION : 1,
ADDITION : 2,
REMOVAL : 3
});
events.EventTarget = function() {};
events.EventTarget.getListeners = function getListeners(target, type, capturing) {
var listeners = target._listeners
&& target._listeners[type]
&& target._listeners[type][capturing] || [];
if (!capturing) {
var traditionalHandler = target['on' + type];
if (traditionalHandler) {
var implementation = (target._ownerDocument ? target._ownerDocument.implementation
: target.document.implementation);
if (implementation.hasFeature('ProcessExternalResources', 'script')) {
listeners.push(traditionalHandler);
}
}
}
return listeners;
};
events.EventTarget.dispatch = function dispatch(event, iterator, capturing) {
var listeners,
currentListener,
target = iterator();
while (target && !event._stopPropagation) {
listeners = events.EventTarget.getListeners(target, event._type, capturing);
currentListener = listeners.length;
while (currentListener--) {
event._currentTarget = target;
try {
listeners[currentListener].call(target, event);
} catch (e) {
target.raise(
'error', "Dispatching event '" + event._type + "' failed",
{error: e, event: event}
);
}
}
target = iterator();
}
return !event._stopPropagation;
};
events.EventTarget.forwardIterator = function forwardIterator(list) {
var i = 0, len = list.length;
return function iterator() { return i < len ? list[i++] : null };
};
events.EventTarget.backwardIterator = function backwardIterator(list) {
var i = list.length;
return function iterator() { return i >=0 ? list[--i] : null };
};
events.EventTarget.singleIterator = function singleIterator(obj) {
var i = 1;
return function iterator() { return i-- ? obj : null };
};
events.EventTarget.prototype = {
addEventListener: function(type, listener, capturing) {
this._listeners = this._listeners || {};
var listeners = this._listeners[type] || {};
capturing = (capturing === true);
var capturingListeners = listeners[capturing] || [];
for (var i=0; i < capturingListeners.length; i++) {
if (capturingListeners[i] === listener) {
return;
}
}
capturingListeners.push(listener);
listeners[capturing] = capturingListeners;
this._listeners[type] = listeners;
},
removeEventListener: function(type, listener, capturing) {
var listeners = this._listeners && this._listeners[type];
if (!listeners) return;
var capturingListeners = listeners[(capturing === true)];
if (!capturingListeners) return;
for (var i=0; i < capturingListeners.length; i++) {
if (capturingListeners[i] === listener) {
capturingListeners.splice(i, 1);
return;
}
}
},
dispatchEvent: function(event) {
if (event == null) {
throw new events.EventException(0, "Null event");
}
if (event._type == null || event._type == "") {
throw new events.EventException(0, "Uninitialized event");
}
var targetList = [];
event._target = this;
//per the spec we gather the list of targets first to ensure
//against dom modifications during actual event dispatch
var target = this,
targetParent = target._parentNode;
while (targetParent) {
targetList.push(targetParent);
target = targetParent;
targetParent = target._parentNode;
}
targetParent = target._parentWindow;
if (targetParent) {
targetList.push(targetParent);
}
var iterator = events.EventTarget.backwardIterator(targetList);
event._eventPhase = event.CAPTURING_PHASE;
if (!events.EventTarget.dispatch(event, iterator, true)) return event._preventDefault;
iterator = events.EventTarget.singleIterator(event._target);
event._eventPhase = event.AT_TARGET;
if (!events.EventTarget.dispatch(event, iterator, false)) return event._preventDefault;
if (event._bubbles && !event._stopPropagation) {
var i = 0;
iterator = events.EventTarget.forwardIterator(targetList);
event._eventPhase = event.BUBBLING_PHASE;
events.EventTarget.dispatch(event, iterator, false);
}
return event._preventDefault;
}
};
// Reinherit class heirarchy with EventTarget at its root
inheritFrom(events.EventTarget, core.Node, core.Node.prototype);
// Node
inheritFrom(core.Node, core.Attr, core.Attr.prototype);
inheritFrom(core.Node, core.CharacterData, core.CharacterData.prototype);
inheritFrom(core.Node, core.Document, core.Document.prototype);
inheritFrom(core.Node, core.DocumentFragment, core.DocumentFragment.prototype);
inheritFrom(core.Node, core.DocumentType, core.DocumentType.prototype);
inheritFrom(core.Node, core.Element, core.Element.prototype);
inheritFrom(core.Node, core.Entity, core.Entity.prototype);
inheritFrom(core.Node, core.EntityReference, core.EntityReference.prototype);
inheritFrom(core.Node, core.Notation, core.Notation.prototype);
inheritFrom(core.Node, core.ProcessingInstruction, core.ProcessingInstruction.prototype);
// CharacterData
inheritFrom(core.CharacterData, core.Text, core.Text.prototype);
// Text
inheritFrom(core.Text, core.CDATASection, core.CDATASection.prototype);
inheritFrom(core.Text, core.Comment, core.Comment.prototype);
function getDocument(el) {
return el.nodeType == core.Node.DOCUMENT_NODE ? el : el._ownerDocument;
}
function mutationEventsEnabled(el) {
return el.nodeType != core.Node.ATTRIBUTE_NODE &&
getDocument(el).implementation.hasFeature('MutationEvents');
}
utils.intercept(core.Node, 'insertBefore', function(_super, args, newChild, refChild) {
var ret = _super.apply(this, args);
if (mutationEventsEnabled(this)) {
var doc = getDocument(this),
ev = doc.createEvent("MutationEvents");
ev.initMutationEvent("DOMNodeInserted", true, false, this, null, null, null, null);
newChild.dispatchEvent(ev);
if (this.nodeType == core.Node.DOCUMENT_NODE || this._attachedToDocument) {
ev = doc.createEvent("MutationEvents");
ev.initMutationEvent("DOMNodeInsertedIntoDocument", false, false, null, null, null, null, null);
core.visitTree(newChild, function(el) {
if (el.nodeType == core.Node.ELEMENT_NODE) {
el.dispatchEvent(ev);
el._attachedToDocument = true;
}
});
}
}
return ret;
});
utils.intercept(core.Node, 'removeChild', function (_super, args, oldChild) {
if (mutationEventsEnabled(this)) {
var doc = getDocument(this),
ev = doc.createEvent("MutationEvents");
ev.initMutationEvent("DOMNodeRemoved", true, false, this, null, null, null, null);
oldChild.dispatchEvent(ev);
ev = doc.createEvent("MutationEvents");
ev.initMutationEvent("DOMNodeRemovedFromDocument", false, false, null, null, null, null, null);
core.visitTree(oldChild, function(el) {
if (el.nodeType == core.Node.ELEMENT_NODE) {
el.dispatchEvent(ev);
el._attachedToDocument = false;
}
});
}
return _super.apply(this, args);
});
function dispatchAttrEvent(change) {
return function(_super, args, node) {
var target = this._parentNode,
prev = _super.apply(this, args);
if (mutationEventsEnabled(target)) {
var doc = target._ownerDocument,
attrChange = events.MutationEvent.prototype[change],
attrName = prev && prev.name || node.name,
prevVal = prev && prev.value || null,
newVal = change == 'ADDITION' ? node.value : null,
ev;
if (!newVal || newVal != prevVal) {
ev = doc.createEvent("MutationEvents");
ev.initMutationEvent("DOMAttrModified", true, false, target, prevVal, newVal, attrName, attrChange);
target.dispatchEvent(ev);
}
}
return prev;
}
}
utils.intercept(core.AttrNodeMap, 'removeNamedItem', dispatchAttrEvent('REMOVAL'));
utils.intercept(core.AttrNodeMap, 'setNamedItem', dispatchAttrEvent('ADDITION'));
defineGetter(core.CharacterData.prototype, "_nodeValue", function() {
return this.__nodeValue;
});
defineSetter(core.CharacterData.prototype, "_nodeValue", function(value) {
var oldValue = this.__nodeValue;
this.__nodeValue = value;
if (this._ownerDocument && this._parentNode && mutationEventsEnabled(this)) {
var ev = this._ownerDocument.createEvent("MutationEvents")
ev.initMutationEvent("DOMCharacterDataModified", true, false, this, oldValue, value, null, null);
this.dispatchEvent(ev);
}
});
core.Document.prototype.createEvent = function(eventType) {
switch (eventType) {
case "MutationEvents": return new events.MutationEvent(eventType);
case "UIEvents": return new events.UIEvent(eventType);
case "MouseEvents": return new events.MouseEvent(eventType);
case "HTMLEvents": return new events.Event(eventType);
}
return new events.Event(eventType);
};
exports.dom =
{
level2 : {
core : core,
events : events
}
};
|
(function () {
/**
* Threshold Filter. Pushes any value above the mid point to
* the max and any value below the mid point to the min.
* This affects the alpha channel.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Threshold = function (imageData) {
var level = this.threshold() * 255,
data = imageData.data,
len = data.length,
i;
for (i = 0; i < len; i += 1) {
data[i] = data[i] < level ? 0 : 255;
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'threshold', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set threshold. Must be a value between 0 and 1
* @name threshold
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} threshold
* @returns {Number}
*/
})(); |
// MobileInit.js
// -------------
// Include Mobile Specific JavaScript files here (or inside of your Mobile router)
require(["jquery", "backbone", "routers/MobileRouter", "jquerymobile", "backbone.validateAll"],
function($, Backbone, MobileRouter) {
// Prevents all anchor click handling
$.mobile.linkBindingEnabled = false;
// Disabling this will prevent jQuery Mobile from handling hash changes
$.mobile.hashListeningEnabled = false;
// Instantiates a new Mobile Router instance
new MobileRouter();
}
); |
var expect = require('expect.js');
var config = require('./config');
var API = require('../');
describe('api_menu.js', function () {
var api = new API(config.appid, config.appsecret);
before(function (done) {
api.getAccessToken(done);
});
it('createMenu should ok', function (done) {
var menu = JSON.stringify(require('./fixture/menu.json'));
api.createMenu(menu, function (err, result) {
expect(err).not.to.be.ok();
expect(result).to.have.property('errcode', 0);
expect(result).to.have.property('errmsg', 'ok');
done();
});
});
it('getMenu should ok', function (done) {
api.getMenu(function (err, menu) {
expect(err).not.to.be.ok();
expect(menu).to.have.property('menu');
expect(menu.menu).to.have.property('button');
expect(menu.menu.button).to.have.length(3);
done();
});
});
it('removeMenu should ok', function (done) {
api.removeMenu(function (err, result) {
expect(err).not.to.be.ok();
expect(result).to.have.property('errcode', 0);
expect(result).to.have.property('errmsg', 'ok');
done();
});
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:c396b8ab912daec2b9125dfe8d8e8ec31c25561f4f693fe5c162dbfe735c8c31
size 15266
|
import { for } from "iteration"
|
//! moment.js locale configuration
//! locale : Spanish (United States) [es-us]
//! author : bustta : https://github.com/bustta
//! author : chrisrodz : https://github.com/chrisrodz
import moment from '../moment';
var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split(
'_'
),
monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),
monthsParse = [
/^ene/i,
/^feb/i,
/^mar/i,
/^abr/i,
/^may/i,
/^jun/i,
/^jul/i,
/^ago/i,
/^sep/i,
/^oct/i,
/^nov/i,
/^dic/i,
],
monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;
export default moment.defineLocale('es-us', {
months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split(
'_'
),
monthsShort: function (m, format) {
if (!m) {
return monthsShortDot;
} else if (/-MMM-/.test(format)) {
return monthsShort[m.month()];
} else {
return monthsShortDot[m.month()];
}
},
monthsRegex: monthsRegex,
monthsShortRegex: monthsRegex,
monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
monthsParse: monthsParse,
longMonthsParse: monthsParse,
shortMonthsParse: monthsParse,
weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'h:mm A',
LTS: 'h:mm:ss A',
L: 'MM/DD/YYYY',
LL: 'D [de] MMMM [de] YYYY',
LLL: 'D [de] MMMM [de] YYYY h:mm A',
LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A',
},
calendar: {
sameDay: function () {
return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
nextDay: function () {
return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
nextWeek: function () {
return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
lastDay: function () {
return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
lastWeek: function () {
return (
'[el] dddd [pasado a la' +
(this.hours() !== 1 ? 's' : '') +
'] LT'
);
},
sameElse: 'L',
},
relativeTime: {
future: 'en %s',
past: 'hace %s',
s: 'unos segundos',
ss: '%d segundos',
m: 'un minuto',
mm: '%d minutos',
h: 'una hora',
hh: '%d horas',
d: 'un día',
dd: '%d días',
M: 'un mes',
MM: '%d meses',
y: 'un año',
yy: '%d años',
},
dayOfMonthOrdinalParse: /\d{1,2}º/,
ordinal: '%dº',
week: {
dow: 0, // Sunday is the first day of the week.
doy: 6, // The week that contains Jan 6th is the first week of the year.
},
});
|
// Range nearables screen.
;(function(app)
{
app.startRangingNearables = function()
{
function onRange(nearables)
{
displayNearablesInfo(nearables);
}
function onError(errorMessage)
{
console.log('Range error: ' + errorMessage);
}
function displayNearablesInfo(nearables)
{
// Clear HTML list.
$('#id-screen-range-nearables .style-item-list').empty();
// Generate HTML for nearables.
$.each(nearables, function(i, nearable)
{
var element = $(createNearableHTML(nearable));
$('#id-screen-range-nearables .style-item-list').append(element);
});
};
function createNearableHTML(nearable)
{
var colorClasses = 'style-color-blueberry-dark style-color-blueberry-dark-text';
var htm = '<div class="' + colorClasses + '">'
+ '<table><tr><td>Type</td><td>' + nearable.nameForType
+ '</td></tr><tr><td>Identifier</td><td>' + nearable.identifier
+ '</td><tr><td>Color</td><td>' + nearable.nameForColor
+ '</td></tr><tr><td>Zone</td><td>' + nearable.zone
+ '</td></tr><tr><td>RSSI</td><td>' + nearable.rssi
+ '</td></tr><tr><td>Temperature</td><td>' + nearable.temperature
+ '</td></tr><tr><td>Is moving</td><td>' + (nearable.isMoving ? 'Yes' : 'No')
+ '</td></tr><tr><td>xAcceleration</td><td>' + nearable.xAcceleration
+ '</td></tr><tr><td>yAcceleration</td><td>' + nearable.yAcceleration
+ '</td></tr><tr><td>zAcceleration</td><td>' + nearable.zAcceleration
+ '</td></tr></table></div>';
return htm;
};
// Show screen.
app.showScreen('id-screen-range-nearables');
$('#id-screen-range-nearables .style-item-list').empty();
// Start ranging.
estimote.nearables.startRangingForType(
estimote.nearables.NearableTypeAll,
onRange,
onError);
};
app.stopRangingNearables = function()
{
estimote.nearables.stopRanging();
app.showHomeScreen();
};
})(app);
|
import TrackedArray from "ember-runtime/system/tracked_array";
var trackedArray;
var RETAIN = TrackedArray.RETAIN;
var INSERT = TrackedArray.INSERT;
var DELETE = TrackedArray.DELETE;
QUnit.module('Ember.TrackedArray');
QUnit.test("operations for a tracked array of length n are initially retain:n", function() {
trackedArray = new TrackedArray([1,2,3,4]);
equal("r:4", trackedArray.toString(), "initial mutation is retain n");
});
QUnit.test("insert zero items is a no-op", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(2, []);
equal(trackedArray.toString(), "r:4", "insert:0 is a no-op");
deepEqual(trackedArray._operations[0].items, [1,2,3,4], "after a no-op, existing operation has right items");
});
QUnit.test("inserts can split retains", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(2, ['a']);
equal(trackedArray.toString(), "r:2 i:1 r:2", "inserts can split retains");
deepEqual(trackedArray._operations[0].items, [1,2], "split retains have the right items");
deepEqual(trackedArray._operations[1].items, ['a'], "inserts have the right items");
deepEqual(trackedArray._operations[2].items, [3,4], "split retains have the right items");
});
QUnit.test("inserts can expand (split/compose) inserts", function() {
trackedArray = new TrackedArray([]);
trackedArray.addItems(0, [1,2,3,4]);
trackedArray.addItems(2, ['a']);
equal(trackedArray.toString(), "i:5", "inserts can expand inserts");
deepEqual(trackedArray._operations[0].items, [1,2,'a',3,4], "expanded inserts have the right items");
});
QUnit.test("inserts left of inserts compose", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(2, ['b']);
trackedArray.addItems(2, ['a']);
equal(trackedArray.toString(), "r:2 i:2 r:2", "inserts left of inserts compose");
deepEqual(trackedArray._operations[0].items, [1,2], "split retains have the right items");
deepEqual(trackedArray._operations[1].items, ['a', 'b'], "composed inserts have the right items");
deepEqual(trackedArray._operations[2].items, [3,4], "split retains have the right items");
});
QUnit.test("inserts right of inserts compose", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(2, ['a']);
trackedArray.addItems(3, ['b']);
equal(trackedArray.toString(), "r:2 i:2 r:2", "inserts right of inserts compose");
deepEqual(trackedArray._operations[0].items, [1,2], "split retains have the right items");
deepEqual(trackedArray._operations[1].items, ['a', 'b'], "composed inserts have the right items");
deepEqual(trackedArray._operations[2].items, [3,4], "split retains have the right items");
});
QUnit.test("delete zero items is a no-op", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(2, []);
equal(trackedArray.toString(), "r:4", "insert:0 is a no-op");
deepEqual(trackedArray._operations[0].items, [1,2,3,4], "after a no-op, existing operation has right items");
});
QUnit.test("deletes compose with several inserts and retains", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(4, ['e']);
trackedArray.addItems(3, ['d']);
trackedArray.addItems(2, ['c']);
trackedArray.addItems(1, ['b']);
trackedArray.addItems(0, ['a']); // a1b2c3d4e i1r1i1r1i1r1i1r1i1
trackedArray.removeItems(0, 9);
equal(trackedArray.toString(), "d:4", "deletes compose with several inserts and retains");
});
QUnit.test("deletes compose with several inserts and retains and an adjacent delete", function() {
trackedArray = new TrackedArray([1,2,3,4,5]);
trackedArray.removeItems(0, 1);
trackedArray.addItems(4, ['e']);
trackedArray.addItems(3, ['d']);
trackedArray.addItems(2, ['c']);
trackedArray.addItems(1, ['b']);
trackedArray.addItems(0, ['a']); // a2b3c4d5e d1i1r1i1r1i1r1i1r1i1
trackedArray.removeItems(0, 9);
equal(trackedArray.toString(), "d:5", "deletes compose with several inserts, retains, and a single prior delete");
});
QUnit.test("deletes compose with several inserts and retains and can reduce the last one", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(4, ['e', 'f']);
trackedArray.addItems(3, ['d']);
trackedArray.addItems(2, ['c']);
trackedArray.addItems(1, ['b']);
trackedArray.addItems(0, ['a']); // a1b2c3d4e i1r1i1r1i1r1i1r1i2
trackedArray.removeItems(0, 9);
equal(trackedArray.toString(), "d:4 i:1", "deletes compose with several inserts and retains, reducing the last one");
deepEqual(trackedArray._operations[1].items, ['f'], "last mutation's items is correct");
});
QUnit.test("deletes can split retains", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.removeItems(0, 2);
equal(trackedArray.toString(), "d:2 r:2", "deletes can split retains");
deepEqual(trackedArray._operations[1].items, [3,4], "retains reduced by delete have the right items");
});
QUnit.test("deletes can trim retains on the right", function() {
trackedArray = new TrackedArray([1,2,3]);
trackedArray.removeItems(2, 1);
equal(trackedArray.toString(), "r:2 d:1", "deletes can trim retains on the right");
deepEqual(trackedArray._operations[0].items, [1,2], "retains reduced by delete have the right items");
});
QUnit.test("deletes can trim retains on the left", function() {
trackedArray = new TrackedArray([1,2,3]);
trackedArray.removeItems(0, 1);
equal(trackedArray.toString(), "d:1 r:2", "deletes can trim retains on the left");
deepEqual(trackedArray._operations[1].items, [2,3], "retains reduced by delete have the right items");
});
QUnit.test("deletes can split inserts", function() {
trackedArray = new TrackedArray([]);
trackedArray.addItems(0, ['a','b','c']);
trackedArray.removeItems(0, 1);
equal(trackedArray.toString(), "i:2", "deletes can split inserts");
deepEqual(trackedArray._operations[0].items, ['b', 'c'], "inserts reduced by delete have the right items");
});
QUnit.test("deletes can trim inserts on the right", function() {
trackedArray = new TrackedArray([]);
trackedArray.addItems(0, ['a','b','c']);
trackedArray.removeItems(2, 1);
equal(trackedArray.toString(), "i:2", "deletes can trim inserts on the right");
deepEqual(trackedArray._operations[0].items, ['a', 'b'], "inserts reduced by delete have the right items");
});
QUnit.test("deletes can trim inserts on the left", function() {
trackedArray = new TrackedArray([]);
trackedArray.addItems(0, ['a','b','c']);
trackedArray.removeItems(0, 1);
equal(trackedArray.toString(), "i:2", "deletes can trim inserts on the right");
deepEqual(trackedArray._operations[0].items, ['b', 'c'], "inserts reduced by delete have the right items");
});
QUnit.test("deletes can trim inserts on the left while composing with a delete on the left", function() {
trackedArray = new TrackedArray(['a']);
trackedArray.removeItems(0, 1);
trackedArray.addItems(0, ['b', 'c']);
trackedArray.removeItems(0, 1);
equal(trackedArray.toString(), "d:1 i:1", "deletes can trim inserts and compose with a delete on the left");
deepEqual(trackedArray._operations[1].items, ['c'], "inserts reduced by delete have the right items");
});
QUnit.test("deletes can reduce an insert or retain, compose with several mutations of different types and reduce the last mutation if it is non-delete", function() {
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(4, ['e', 'f']); // 1234ef
trackedArray.addItems(3, ['d']); // 123d4ef
trackedArray.addItems(2, ['c']); // 12c3d4ef
trackedArray.addItems(1, ['b']); // 1b2c3d4ef
trackedArray.addItems(0, ['a','a','a']); // aaa1b2c3d4ef i3r1i1r1i1r1i1r1i2
trackedArray.removeItems(1, 10);
equal(trackedArray.toString(), "i:1 d:4 i:1", "deletes reduce an insert, compose with several inserts and retains, reducing the last one");
deepEqual(trackedArray._operations[0].items, ['a'], "first reduced mutation's items is correct");
deepEqual(trackedArray._operations[2].items, ['f'], "last reduced mutation's items is correct");
});
QUnit.test("removeItems returns the removed items", function() {
trackedArray = new TrackedArray([1,2,3,4]);
deepEqual(trackedArray.removeItems(1, 2), [2,3], "`removeItems` returns the removed items");
});
QUnit.test("apply invokes the callback with each group of items and the mutation's calculated offset", function() {
var i = 0;
trackedArray = new TrackedArray([1,2,3,4]);
trackedArray.addItems(2, ['a','b','c']); // 12abc34
trackedArray.removeItems(4, 2); // 12ab4
trackedArray.addItems(1, ['d']); // 1d2ab4 r1 i1 r1 i2 d1 r1
equal(trackedArray.toString(), "r:1 i:1 r:1 i:2 d:1 r:1", "precond - trackedArray is in expected state");
trackedArray.apply(function (items, offset, operation) {
switch (i++) {
case 0:
deepEqual(items, [1], "callback passed right items");
equal(offset, 0, "callback passed right offset");
equal(operation, RETAIN, "callback passed right operation");
break;
case 1:
deepEqual(items, ['d'], "callback passed right items");
equal(offset, 1, "callback passed right offset");
equal(operation, INSERT, "callback passed right operation");
break;
case 2:
deepEqual(items, [2], "callback passed right items");
equal(offset, 2, "callback passed right offset");
equal(operation, RETAIN, "callback passed right operation");
break;
case 3:
deepEqual(items, ['a','b'], "callback passed right items");
equal(offset, 3, "callback passed right offset");
equal(operation, INSERT, "callback passed right operation");
break;
case 4:
// deletes not passed items at the moment; that might need to be added
// if TrackedArray is used more widely
equal(offset, 5, "callback passed right offset");
equal(operation, DELETE, "callback passed right operation");
break;
case 5:
deepEqual(items, [4], "callback passed right items");
equal(offset, 5, "callback passed right offset");
equal(operation, RETAIN, "callback passed right operation");
break;
}
});
equal(i, 6, "`apply` invoked callback right number of times");
equal(trackedArray.toString(), "r:6", "after `apply` operations become retain:n");
});
|
'use strict';
/**
* Module dependencies.
*/
var mean = require('meanio'),
compression = require('compression'),
morgan = require('morgan'),
consolidate = require('consolidate'),
cookieParser = require('cookie-parser'),
expressValidator = require('express-validator'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
assetmanager = require('assetmanager'),
session = require('express-session'),
mongoStore = require('connect-mongo')(session),
helpers = require('view-helpers'),
flash = require('connect-flash'),
config = mean.loadConfig();
module.exports = function(app, passport, db) {
app.set('showStackError', true);
// Prettify HTML
app.locals.pretty = true;
// cache=memory or swig dies in NODE_ENV=production
app.locals.cache = 'memory';
// Should be placed before express.static
// To ensure that all assets and data are compressed (utilize bandwidth)
app.use(compression({
// Levels are specified in a range of 0 to 9, where-as 0 is
// no compression and 9 is best compression, but slowest
level: 9
}));
// Only use logger for development environment
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// assign the template engine to .html files
app.engine('html', consolidate[config.templateEngine]);
// set .html as the default extension
app.set('view engine', 'html');
// The cookieParser should be above session
app.use(cookieParser());
// Request body parsing middleware should be above methodOverride
app.use(expressValidator());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(methodOverride());
// Import the assets file and add to locals
var assets = assetmanager.process({
assets: require('./assets.json'),
debug: process.env.NODE_ENV !== 'production',
webroot: /public\/|packages\//g
});
// Add assets to local variables
app.use(function(req, res, next) {
res.locals.assets = assets;
mean.aggregated('js', 'header', function(data) {
res.locals.headerJs = data;
next();
});
});
// Express/Mongo session storage
app.use(session({
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
}),
cookie: config.sessionCookie,
name: config.sessionName,
resave: true,
saveUninitialized: true
}));
// Dynamic helpers
app.use(helpers(config.app.name));
// Use passport session
app.use(passport.initialize());
app.use(passport.session());
//mean middleware from modules before routes
app.use(mean.chainware.before);
// Connect flash for flash messages
app.use(flash());
};
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/Neo-Euler/fontdata.js
*
* Initializes the HTML-CSS OutputJax to use the Neo-Euler fonts
* Copyright (c) 2013-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 (HTMLCSS,MML,AJAX) {
var VERSION = "2.7.0";
var ALPHABETS = "NeoEulerMathJax_Alphabets",
ARROWS = "NeoEulerMathJax_Arrows",
FRAKTUR = "NeoEulerMathJax_Fraktur",
MAIN = "NeoEulerMathJax_Main",
MARKS = "NeoEulerMathJax_Marks",
NONUNICODE = "NeoEulerMathJax_NonUnicode",
NORMAL = "NeoEulerMathJax_Normal",
OPERATORS = "NeoEulerMathJax_Operators",
SCRIPT = "NeoEulerMathJax_Script",
SHAPES = "NeoEulerMathJax_Shapes",
SIZE1 = "NeoEulerMathJax_Size1",
SIZE2 = "NeoEulerMathJax_Size2",
SIZE3 = "NeoEulerMathJax_Size3",
SIZE4 = "NeoEulerMathJax_Size4",
SIZE5 = "NeoEulerMathJax_Size5",
SYMBOLS = "NeoEulerMathJax_Symbols",
VARIANTS = "NeoEulerMathJax_Variants",
DOUBLESTRUCK = "NeoEulerMathJax_Normal",
SANSSERIF = "NeoEulerMathJax_Normal",
MONOSPACE = "NeoEulerMathJax_Normal";
var H = "H", V = "V", EXTRAH = {load:"extra", dir:H}, EXTRAV = {load:"extra", dir:V};
HTMLCSS.Augment({
FONTDATA: {
version: VERSION,
TeX_factor: 0.958,
baselineskip: 1.200,
lineH: 0.800, lineD: 0.200,
hasStyleChar: true, // char 0xEFFD encodes font style
FONTS: {
"NeoEulerMathJax_Alphabets": "Alphabets/Regular/Main.js",
"NeoEulerMathJax_Arrows": "Arrows/Regular/Main.js",
"NeoEulerMathJax_Fraktur": "Fraktur/Regular/Main.js",
"NeoEulerMathJax_Main": "Main/Regular/Main.js",
"NeoEulerMathJax_Marks": "Marks/Regular/Main.js",
"NeoEulerMathJax_NonUnicode": "NonUnicode/Regular/Main.js",
"NeoEulerMathJax_Normal": "Normal/Regular/Main.js",
"NeoEulerMathJax_Operators": "Operators/Regular/Main.js",
"NeoEulerMathJax_Script": "Script/Regular/Main.js",
"NeoEulerMathJax_Shapes": "Shapes/Regular/Main.js",
"NeoEulerMathJax_Size1": "Size1/Regular/Main.js",
"NeoEulerMathJax_Size2": "Size2/Regular/Main.js",
"NeoEulerMathJax_Size3": "Size3/Regular/Main.js",
"NeoEulerMathJax_Size4": "Size4/Regular/Main.js",
"NeoEulerMathJax_Size5": "Size5/Regular/Main.js",
"NeoEulerMathJax_Symbols": "Symbols/Regular/Main.js",
"NeoEulerMathJax_Variants": "Variants/Regular/Main.js"
},
VARIANT: {
"normal": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1]},
"bold": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1], bold:true
, offsetA: 0x1D400, offsetG: 0x1D6A8, offsetN: 0x1D7CE},
"italic": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1], italic:true},
"bold-italic": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1], bold: true, italic:true},
"double-struck": {
fonts: [DOUBLESTRUCK],
offsetA: 0x1D538,
offsetN: 0x1D7D8,
remap: {0x1D53A: 0x2102, 0x1D53F: 0x210D, 0x1D545: 0x2115, 0x1D547: 0x2119, 0x1D548: 0x211A, 0x1D549: 0x211D, 0x1D551: 0x2124}
},
"fraktur": {
fonts: [FRAKTUR],
offsetA: 0x1D504,
remap: {0x1D506: 0x212D, 0x1D50B: 0x210C, 0x1D50C: 0x2111, 0x1D515: 0x211C, 0x1D51D: 0x2128}
},
"bold-fraktur": {
fonts: [FRAKTUR], bold:true,
offsetA: 0x1D56C
},
"script": {
fonts: [SCRIPT], italic:true,
offsetA: 0x1D49C,
remap: {0x1D49D: 0x212C, 0x1D4A0: 0x2130, 0x1D4A1: 0x2131, 0x1D4A3: 0x210B, 0x1D4A4: 0x2110, 0x1D4A7: 0x2112, 0x1D4A8: 0x2133, 0x1D4AD: 0x211B, 0x1D4BA: 0x212F, 0x1D4BC: 0x210A, 0x1D4C4: 0x2134}
},
"bold-script": {
fonts: [SCRIPT], bold:true, italic:true,
offsetA: 0x1D4D0
},
"sans-serif": {
fonts: [SANSSERIF],
offsetA: 0x1D5A0,
offsetN: 0x1D7E2
},
"bold-sans-serif": {
fonts: [SANSSERIF], bold:true,
offsetA: 0x1D5D4,
offsetN: 0x1D7EC,
offsetG: 0x1D756
},
"sans-serif-italic": {
fonts: [SANSSERIF], italic: true,
offsetA: 0x1D608
},
"sans-serif-bold-italic": {
fonts: [SANSSERIF], bold:true, italic: true,
offsetA: 0x1D63C,
offsetG: 0x1D790
},
"monospace": {
fonts: [MONOSPACE],
offsetA: 0x1D670,
offsetN: 0x1D7F6
},
"-Neo-Euler-variant": {fonts: [VARIANTS,MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,NONUNICODE,SIZE1]},
"-tex-caligraphic": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1], italic: true},
"-tex-oldstyle": {offsetN: 0xE200, fonts: [VARIANTS,MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,NONUNICODE,SIZE1]},
"-tex-caligraphic-bold": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1], italic: true, bold: true},
"-tex-oldstyle-bold": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1], bold: true},
"-tex-mathit": {fonts: [MAIN,NORMAL,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,VARIANTS,NONUNICODE,SIZE1], italic:true, noIC:true},
"-largeOp": {fonts:[SIZE1,MAIN]},
"-smallOp": {}
},
RANGES: [
{name: "alpha", low: 0x61, high: 0x7A, offset: "A", add: 26},
{name: "Alpha", low: 0x41, high: 0x5A, offset: "A"},
{name: "number", low: 0x30, high: 0x39, offset: "N"},
{name: "greek", low: 0x03B1, high: 0x03C9, offset: "G", add: 26},
{name: "Greek", low: 0x0391, high: 0x03F6, offset: "G",
remap: {0x03F5: 52, 0x03D1: 53, 0x03F0: 54, 0x03D5: 55, 0x03F1: 56, 0x03D6: 57, 0x03F4: 17}}
],
RULECHAR: 0x2212,
REMAP: {
0x20F0: 0x002A,
0x2022: 0x2219,
0x22E3: "\u2292\u0338",
0x22E2: "\u2291\u0338",
0x3008: 0x27E8,
0x02C9: 0x00AF,
0x2017: 0x005F,
0x20EC: 0x21C1,
0x20ED: 0x21BD,
0x2A2F: 0x00D7,
0x20D0: 0x21BC,
0x20D1: 0x21C0,
0x03D2: 0x03A5,
0x2014: 0x00AF,
0x2015: 0x00AF,
0x3009: 0x27E9,
0xFE37: 0x23DE,
0xFE38: 0x23DF,
0x02B9: 0x2032,
0x2758: 0x2223,
0x203E: 0x00AF
},
REMAPACCENT: {
"\u007E": "\u0303",
"\u2192": "\u20D7",
"\u0060": "\u0300",
"\u005E": "\u0302",
"\u00B4": "\u0301",
"\u2032": "\u0301",
"\u2035": "\u0300"
},
REMAPACCENTUNDER: {
},
DELIMITERS: {
0x28:
{
dir: V,
HW: [[0.925,MAIN], [1.198,SIZE1], [1.798,SIZE2], [1.961,SIZE2,1.091], [2.398,SIZE3], [2.998,SIZE4]],
stretch: {bot:[0x239D,SYMBOLS], ext:[0x239C,SYMBOLS], top:[0x239B,SYMBOLS]}
},
0x29:
{
dir: V,
HW: [[0.925,MAIN], [1.198,SIZE1], [1.798,SIZE2], [1.961,SIZE2,1.091], [2.398,SIZE3], [2.998,SIZE4]],
stretch: {bot:[0x23A0,SYMBOLS], ext:[0x239F,SYMBOLS], top:[0x239E,SYMBOLS]}
},
0x2D: {alias: 0xAF, dir: H},
0x2F:
{
dir: V,
HW: [[0.912,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]]
},
0x3D:
{
dir: H,
HW: [[0.668,MAIN]],
stretch: {rep:[0x3D,MAIN]}
},
0x5B:
{
dir: V,
HW: [[0.866,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {bot:[0x23A3,SYMBOLS], ext:[0x23A2,SYMBOLS], top:[0x23A1,SYMBOLS]}
},
0x5C:
{
dir: V,
HW: [[0.914,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]]
},
0x5D:
{
dir: V,
HW: [[0.866,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {bot:[0x23A6,SYMBOLS], ext:[0x23A5,SYMBOLS], top:[0x23A4,SYMBOLS]}
},
0x5F: {alias: 0xAF, dir: H},
0x7B:
{
dir: V,
HW: [[0.908,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {bot:[0x23A9,SYMBOLS], ext:[0x23AA,SYMBOLS], mid:[0x23A8,SYMBOLS], top:[0x23A7,SYMBOLS]}
},
0x7C:
{
dir: V,
HW: [[0.905,MAIN], [1.505,SIZE1], [2.105,SIZE2], [2.706,SIZE3], [3.306,SIZE4]],
stretch: {bot:[0xE000,SIZE5], ext:[0xE001,SIZE5]}
},
0x7D:
{
dir: V,
HW: [[0.908,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {bot:[0x23AD,SYMBOLS], ext:[0x23AA,SYMBOLS], mid:[0x23AC,SYMBOLS], top:[0x23AB,SYMBOLS]}
},
0xAF:
{
dir: H,
HW: [[0.312,MAIN]],
stretch: {rep:[0xAF,MAIN]}
},
0xC9: {alias: 0xAF, dir: H},
0x332: {alias: 0xAF, dir: H},
0x2015: {alias: 0xAF, dir: H},
0x2016:
{
dir: V,
HW: [[0.905,MAIN], [1.505,SIZE1], [2.105,SIZE2], [2.706,SIZE3], [3.306,SIZE4]],
stretch: {bot:[0xE002,SIZE5], ext:[0xE003,SIZE5]}
},
0x2017: {alias: 0xAF, dir: H},
0x203E: {alias: 0xAF, dir: H},
0x2044: EXTRAV,
0x20D6:
{
dir: H,
HW: [[0.418,MARKS]],
stretch: {left:[0x20D6,MARKS], rep:[0xE004,SIZE5]}
},
0x20D7:
{
dir: H,
HW: [[0.418,MAIN]],
stretch: {rep:[0xE004,SIZE5], right:[0x20D7,MAIN]}
},
0x20E1: EXTRAH,
0x20EE: EXTRAH,
0x20EF: EXTRAH,
0x2190: {alias: 0x20D6, dir: H},
0x2191:
{
dir: V,
HW: [[0.887,MAIN]],
stretch: {top:[0x2191,MAIN], ext:[0x7C,MAIN]}
},
0x2192: {alias: 0x20D7, dir: H},
0x2193:
{
dir: V,
HW: [[0.867,MAIN]],
stretch: {ext:[0x7C,MAIN], bot:[0x2193,MAIN]}
},
0x2194: {alias: 0x20E1, dir: H},
0x2195:
{
dir: V,
HW: [[1.042,MAIN]],
stretch: {top:[0x2191,MAIN], ext:[0x7C,MAIN], bot:[0x2193,MAIN]}
},
0x21D0:
{
dir: H,
HW: [[0.867,MAIN], [1.567,SIZE1]]
},
0x21D1:
{
dir: H,
HW: [[0.640,MAIN]],
stretch: {top:[0x21D1,MAIN], ext:[0x2016,MAIN]}
},
0x21D2:
{
dir: H,
HW: [[0.867,MAIN], [1.567,SIZE1]]
},
0x21D3:
{
dir: H,
HW: [[0.640,MAIN]],
stretch: {ext:[0x2016,MAIN], bot:[0x21D3,MAIN]}
},
0x21D4:
{
dir: H,
HW: [[0.867,MAIN,null,0x21D0], [1.632,SIZE1]]
},
0x21D5:
{
dir: H,
HW: [[0.640,MAIN]],
stretch: {top:[0x21D1,MAIN], ext:[0x2016,MAIN], bot:[0x21D3,MAIN]}
},
0x220F: EXTRAV,
0x2210: EXTRAV,
0x2211: EXTRAV,
0x2212: {
dir: H,
HW: [],
stretch: {rep:[0x2212,MAIN,0,0,0,-.31,-.31]}
},
0x2215:
{
dir: V,
HW: [[0.912,MAIN], [1.199,SIZE1], [1.799,SIZE2], [2.399,SIZE3], [2.999,SIZE4]]
},
0x221A:
{
dir: V,
HW: [[0.989,MAIN], [1.209,SIZE1], [1.801,SIZE2], [2.403,SIZE3], [3.003,SIZE4]],
stretch: {bot:[0xE006,SIZE5], ext:[0xE007,SIZE5], top:[0xE008,SIZE5]}
},
0x2223:
{
dir: V,
HW: [[0.795,MAIN], [1.505,SIZE1], [2.105,SIZE2], [2.706,SIZE3], [3.306,SIZE4]]
},
0x2225:
{
dir: V,
HW: [[0.905,MAIN], [0.905,SIZE1], [1.505,SIZE2], [2.105,SIZE3], [2.706,SIZE4], [3.306,SIZE5]],
stretch: {bot:[0xE002,SIZE5], ext:[0xE003,SIZE5]}
},
0x2227: EXTRAV,
0x2228: EXTRAV,
0x2229: EXTRAV,
0x222A: EXTRAV,
0x222B: EXTRAV,
0x222C: EXTRAV,
0x222D: EXTRAV,
0x222E: EXTRAV,
0x228E: EXTRAV,
0x22C0: EXTRAV,
0x22C1: EXTRAV,
0x22C2: EXTRAV,
0x22C3: EXTRAV,
0x2308:
{
dir: V,
HW: [[0.980,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {ext:[0x23A2,SYMBOLS], top:[0x23A1,SYMBOLS]}
},
0x2309:
{
dir: V,
HW: [[0.980,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {ext:[0x23A5,SYMBOLS], top:[0x23A4,SYMBOLS]}
},
0x230A:
{
dir: V,
HW: [[0.980,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {bot:[0x23A3,SYMBOLS], ext:[0x23A2,SYMBOLS]}
},
0x230B:
{
dir: V,
HW: [[0.980,MAIN], [1.199,SIZE1], [1.799,SIZE2], [1.961,SIZE2,1.090], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {bot:[0x23A6,SYMBOLS], ext:[0x23A5,SYMBOLS]}
},
0x2312: {alias: 0x23DC, dir:H},
0x2322: {alias: 0x23DC, dir:H},
0x2323: {alias: 0x23DD, dir:H},
0x2329:
{
dir: V,
HW: [[0.974,SYMBOLS], [1.176,SIZE1], [1.770,SIZE2], [2.366,SIZE3], [2.958,SIZE4]]
},
0x232A:
{
dir: V,
HW: [[0.974,SYMBOLS], [1.176,SIZE1], [1.770,SIZE2], [2.366,SIZE3], [2.958,SIZE4]]
},
0x23AA:
{
dir: V,
HW: [[0.320,SYMBOLS]],
stretch: {ext:[0x23AA,SYMBOLS]}
},
0x23AF: {alias: 0xAF, dir: H},
0x23B0:
{
dir: V,
HW: [[0.909,SYMBOLS,null,0x23A7]],
stretch: {top:[0x23A7,SYMBOLS], ext:[0x23AA,SYMBOLS], bot:[0x23AD,SYMBOLS]}
},
0x23B1:
{
dir: V,
HW: [[0.909,SYMBOLS,null,0x23AB]],
stretch: {top:[0x23AB,SYMBOLS], ext:[0x23AA,SYMBOLS], bot:[0x23A9,SYMBOLS]}
},
0x23D0:
{
dir: V,
HW: [[0.905,MAIN,null,0x7C], [1.150,MAIN,1.271,0x7C], [1.556,MAIN,1.719,0x7C], [1.961,MAIN,2.167,0x7C], [2.367,MAIN,2.615,0x7C]],
stretch: {ext:[0x7C,MAIN]}
},
0x23DC: EXTRAH,
0x23DD: EXTRAH,
0x23DE:
{
dir: H,
HW: [[0.908,MAIN], [1.199,SIZE1], [1.799,SIZE2], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {left:[0xE00F,SIZE5], rep:[0xE010,SIZE5], mid:[0xE011,SIZE5], right:[0xE012,SIZE5]}
},
0x23DF:
{
dir: H,
HW: [[0.908,MAIN], [1.199,SIZE1], [1.799,SIZE2], [2.399,SIZE3], [2.999,SIZE4]],
stretch: {left:[0xE013,SIZE5], rep:[0xE014,SIZE5], mid:[0xE015,SIZE5], right:[0xE016,SIZE5]}
},
0x2500: {alias: 0xAF, dir: H},
0x2758: {alias: 0x23D0, dir: V},
0x27E8:
{
dir: V,
HW: [[0.974,MAIN], [0.974,SIZE1], [1.176,SIZE2], [1.770,SIZE3], [2.366,SIZE4], [2.958,SIZE5]]
},
0x27E9:
{
dir: V,
HW: [[0.974,MAIN], [0.974,SIZE1], [1.176,SIZE2], [1.770,SIZE3], [2.366,SIZE4], [2.958,SIZE5]]
},
0x27EE: {alias: 0x28, dir: V},
0x27EF: {alias: 0x29, dir: V},
0x27F5: {alias: 0x20D6, dir: H},
0x27F6: {alias: 0x20D7, dir: H},
0x27F7: {alias: 0x20E1, dir: H},
0x27F8: {alias: 0x21D0, dir: H},
0x27F9: {alias: 0x21D2, dir: H},
0x27FA: {alias: 0x21D4, dir: H},
0x27FB: {alias: 0x20D6, dir: H},
0x27FC: {alias: 0x20D7, dir: H},
0x27FD: {alias: 0x21D0, dir: H},
0x27FE: {alias: 0x21D2, dir: H},
0x2A0C: EXTRAV,
0x3008: {alias: 0x27E8, dir: V},
0x3009: {alias: 0x27E9, dir: V},
0xFE37: {alias: 0x23DE, dir: H},
0xFE38: {alias: 0x23DF, dir: H}
}
}
});
MathJax.Hub.Register.LoadHook(HTMLCSS.fontDir+"/Main/Regular/Main.js",function () {
HTMLCSS.FONTDATA.FONTS[MAIN][0x2212][0] = HTMLCSS.FONTDATA.FONTS[MAIN][0x002B][0]; // - needs height and depth of +
HTMLCSS.FONTDATA.FONTS[MAIN][0x2212][1] = HTMLCSS.FONTDATA.FONTS[MAIN][0x002B][1]; // - needs height and depth of +
});
MathJax.Hub.Register.LoadHook(HTMLCSS.fontDir+"/Size5/Regular/Main.js",function () {
var u;
u = HTMLCSS.FONTDATA.DELIMITERS[0x23DE].stretch.rep[0];
HTMLCSS.FONTDATA.FONTS[SIZE5][u][0] += 200; // adjust height for brace extender
HTMLCSS.FONTDATA.FONTS[SIZE5][u][1] += 200; // adjust depth for brace extender
u = HTMLCSS.FONTDATA.DELIMITERS[0x23DF].stretch.rep[0];
HTMLCSS.FONTDATA.FONTS[SIZE5][u][0] += 200; // adjust height for brace extender
HTMLCSS.FONTDATA.FONTS[SIZE5][u][1] += 200; // adjust depth for brace extender
});
AJAX.loadComplete(HTMLCSS.fontDir + "/fontdata.js");
})(MathJax.OutputJax["HTML-CSS"],MathJax.ElementJax.mml,MathJax.Ajax);
|
/**
* @license Angular v4.3.6
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
import { ResourceLoader, platformCoreDynamic } from '@angular/compiler';
import { COMPILER_OPTIONS, Injectable, PLATFORM_ID, Version, createPlatformFactory, ɵglobal } from '@angular/core';
import { ɵPLATFORM_BROWSER_ID } from '@angular/common';
import { ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS } from '@angular/platform-browser';
/**
* @license
* Copyright Google Inc. 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
*/
class ResourceLoaderImpl extends ResourceLoader {
get(url) {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'text';
xhr.onload = function () {
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in ResourceLoader Level2 spec (supported
// by IE10)
const response = xhr.response || xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
let status = xhr.status === 1223 ? 204 : xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : 0;
}
if (200 <= status && status <= 300) {
resolve(response);
}
else {
reject(`Failed to load ${url}`);
}
};
xhr.onerror = function () { reject(`Failed to load ${url}`); };
xhr.send();
return promise;
}
}
ResourceLoaderImpl.decorators = [
{ type: Injectable },
];
/** @nocollapse */
ResourceLoaderImpl.ctorParameters = () => [];
/**
* @license
* Copyright Google Inc. 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
*/
const INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS = [
ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS,
{
provide: COMPILER_OPTIONS,
useValue: { providers: [{ provide: ResourceLoader, useClass: ResourceLoaderImpl }] },
multi: true
},
{ provide: PLATFORM_ID, useValue: ɵPLATFORM_BROWSER_ID },
];
/**
* @license
* Copyright Google Inc. 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
*/
/**
* An implementation of ResourceLoader that uses a template cache to avoid doing an actual
* ResourceLoader.
*
* The template cache needs to be built and loaded into window.$templateCache
* via a separate mechanism.
*/
class CachedResourceLoader extends ResourceLoader {
constructor() {
super();
this._cache = ɵglobal.$templateCache;
if (this._cache == null) {
throw new Error('CachedResourceLoader: Template cache was not found in $templateCache.');
}
}
get(url) {
if (this._cache.hasOwnProperty(url)) {
return Promise.resolve(this._cache[url]);
}
else {
return Promise.reject('CachedResourceLoader: Did not find cached template for ' + url);
}
}
}
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* @stable
*/
const VERSION = new Version('4.3.6');
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @experimental
*/
const RESOURCE_CACHE_PROVIDER = [{ provide: ResourceLoader, useClass: CachedResourceLoader }];
/**
* @stable
*/
const platformBrowserDynamic = createPlatformFactory(platformCoreDynamic, 'browserDynamic', INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS);
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @module
* @description
* Entry point for all public APIs of the platform-browser-dynamic package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
export { RESOURCE_CACHE_PROVIDER, platformBrowserDynamic, VERSION, INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS as ɵINTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, ResourceLoaderImpl as ɵResourceLoaderImpl };
//# sourceMappingURL=platform-browser-dynamic.js.map
|
function hasValue(e){return null!=e&&!(Array.isArray(e)&&0===e.length)}function isFilled(e){var a=1<arguments.length&&void 0!==arguments[1]&&arguments[1];return e&&(hasValue(e.value)&&""!==e.value||a&&hasValue(e.defaultValue)&&""!==e.defaultValue)}function isAdornedStart(e){return e.startAdornment}export{hasValue,isFilled,isAdornedStart}; |
var searchData=
[
['pauseprofiler',['PauseProfiler',['../classv8_1_1_v8.html#a5fefebea0cd37105837a9d267baf2e5c',1,'v8::V8']]],
['persistent',['Persistent',['../classv8_1_1_persistent.html',1,'v8']]],
['persistent',['Persistent',['../classv8_1_1_persistent.html#aff7516636baaf209885220f7cff34463',1,'v8::Persistent::Persistent()'],['../classv8_1_1_persistent.html#aea24de4ad0e6cd8e102411e11fbc3948',1,'v8::Persistent::Persistent(Persistent< S > that)'],['../classv8_1_1_persistent.html#a89b49f1b1903a2d625d5c3100238276e',1,'v8::Persistent::Persistent(Handle< S > that)']]],
['precompile',['PreCompile',['../classv8_1_1_script_data.html#a4bb3cdd4abbde99a000a0c25b6357520',1,'v8::ScriptData::PreCompile(const char *input, int length)'],['../classv8_1_1_script_data.html#ad1e46f2a1e84ae151b295f3c74c71787',1,'v8::ScriptData::PreCompile(Handle< String > source)']]],
['preparestressrun',['PrepareStressRun',['../classv8_1_1_testing.html#ab9da044b18b9d05770b655bed27ed7f4',1,'v8::Testing']]],
['preparserdata',['PreParserData',['../classv8_1_1_pre_parser_data.html',1,'v8']]],
['primitive',['Primitive',['../classv8_1_1_primitive.html',1,'v8']]],
['processdebugmessages',['ProcessDebugMessages',['../classv8_1_1_debug.html#a888e06766caee0380c6aa010b00e1a54',1,'v8::Debug']]],
['prototypetemplate',['PrototypeTemplate',['../classv8_1_1_function_template.html#aa2bcc2652b5f0fdbc666d943ccf72021',1,'v8::FunctionTemplate']]],
['pushheapobjectsstats',['PushHeapObjectsStats',['../classv8_1_1_heap_profiler.html#a62189d7a17f33bf6b33d7f550f906d24',1,'v8::HeapProfiler']]]
];
|
$( document ).ready(function() {
var i = -1;
var toastCount = 0;
var $toastlast;
var getMessage = function () {
var msgs = ['My name is Inigo Montoya. You killed my father. Prepare to die!',
'<div><input class="input-small" value="textbox"/> <a href="http://johnpapa.net" target="_blank">This is a hyperlink</a></div><div><button type="button" id="okBtn" class="btn btn-primary">Close me</button><button type="button" id="surpriseBtn" class="btn" style="margin: 0 8px 0 8px">Surprise me</button></div>',
'Are you the six fingered man?',
'Inconceivable!',
'I do not think that means what you think it means.',
'Have fun storming the castle!'
];
i++;
if (i === msgs.length) {
i = 0;
}
return msgs[i];
};
var getMessageWithClearButton = function (msg) {
msg = msg ? msg : 'Clear itself?';
msg += '<br /><br /><button type="button" class="btn clear">Yes</button>';
return msg;
};
$('#showtoast').click(function () {
var shortCutFunction = $("#toastTypeGroup input:radio:checked").val();
var msg = $('#message').val();
var title = $('#title').val() || '';
var $showDuration = $('#showDuration');
var $hideDuration = $('#hideDuration');
var $timeOut = $('#timeOut');
var $extendedTimeOut = $('#extendedTimeOut');
var $showEasing = $('#showEasing');
var $hideEasing = $('#hideEasing');
var $showMethod = $('#showMethod');
var $hideMethod = $('#hideMethod');
var toastIndex = toastCount++;
var addClear = $('#addClear').prop('checked');
toastr.options = {
closeButton: $('#closeButton').prop('checked'),
debug: $('#debugInfo').prop('checked'),
newestOnTop: $('#newestOnTop').prop('checked'),
progressBar: $('#progressBar').prop('checked'),
positionClass: $('#positionGroup input:radio:checked').val() || 'toast-top-right',
preventDuplicates: $('#preventDuplicates').prop('checked'),
onclick: null
};
if ($('#addBehaviorOnToastClick').prop('checked')) {
toastr.options.onclick = function () {
alert('You can perform some custom action after a toast goes away');
};
}
if ($showDuration.val().length) {
toastr.options.showDuration = $showDuration.val();
}
if ($hideDuration.val().length) {
toastr.options.hideDuration = $hideDuration.val();
}
if ($timeOut.val().length) {
toastr.options.timeOut = addClear ? 0 : $timeOut.val();
}
if ($extendedTimeOut.val().length) {
toastr.options.extendedTimeOut = addClear ? 0 : $extendedTimeOut.val();
}
if ($showEasing.val().length) {
toastr.options.showEasing = $showEasing.val();
}
if ($hideEasing.val().length) {
toastr.options.hideEasing = $hideEasing.val();
}
if ($showMethod.val().length) {
toastr.options.showMethod = $showMethod.val();
}
if ($hideMethod.val().length) {
toastr.options.hideMethod = $hideMethod.val();
}
if (addClear) {
msg = getMessageWithClearButton(msg);
toastr.options.tapToDismiss = false;
}
if (!msg) {
msg = getMessage();
}
$('#toastrOptions').text('Command: toastr["'
+ shortCutFunction
+ '"]("'
+ msg
+ (title ? '", "' + title : '')
+ '")\n\ntoastr.options = '
+ JSON.stringify(toastr.options, null, 2)
);
var $toast = toastr[shortCutFunction](msg, title); // Wire up an event handler to a button in the toast, if it exists
$toastlast = $toast;
if(typeof $toast === 'undefined'){
return;
}
if ($toast.find('#okBtn').length) {
$toast.delegate('#okBtn', 'click', function () {
alert('you clicked me. i was toast #' + toastIndex + '. goodbye!');
$toast.remove();
});
}
if ($toast.find('#surpriseBtn').length) {
$toast.delegate('#surpriseBtn', 'click', function () {
alert('Surprise! you clicked me. i was toast #' + toastIndex + '. You could perform an action here.');
});
}
if ($toast.find('.clear').length) {
$toast.delegate('.clear', 'click', function () {
toastr.clear($toast, { force: true });
});
}
});
function getLastToast(){
return $toastlast;
}
$('#clearlasttoast').click(function () {
toastr.clear(getLastToast());
});
$('#cleartoasts').click(function () {
toastr.clear();
});
}); |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 104);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ }),
/***/ 104:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(105);
/***/ }),
/***/ 105:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_touch__ = __webpack_require__(106);
__WEBPACK_IMPORTED_MODULE_1__foundation_util_touch__["a" /* Touch */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a);
window.Foundation.Touch = __WEBPACK_IMPORTED_MODULE_1__foundation_util_touch__["a" /* Touch */];
/***/ }),
/***/ 106:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Touch; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
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"); } }
//**************************************************
//**Work inspired by multiple jquery swipe plugins**
//**Done by Yohai Ararat ***************************
//**************************************************
var Touch = {};
var startPosX,
startPosY,
startTime,
elapsedTime,
isMoving = false;
function onTouchEnd() {
// alert(this);
this.removeEventListener('touchmove', onTouchMove);
this.removeEventListener('touchend', onTouchEnd);
isMoving = false;
}
function onTouchMove(e) {
if (__WEBPACK_IMPORTED_MODULE_0_jquery___default.a.spotSwipe.preventDefault) {
e.preventDefault();
}
if (isMoving) {
var x = e.touches[0].pageX;
var y = e.touches[0].pageY;
var dx = startPosX - x;
var dy = startPosY - y;
var dir;
elapsedTime = new Date().getTime() - startTime;
if (Math.abs(dx) >= __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.spotSwipe.moveThreshold && elapsedTime <= __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.spotSwipe.timeThreshold) {
dir = dx > 0 ? 'left' : 'right';
}
// else if(Math.abs(dy) >= $.spotSwipe.moveThreshold && elapsedTime <= $.spotSwipe.timeThreshold) {
// dir = dy > 0 ? 'down' : 'up';
// }
if (dir) {
e.preventDefault();
onTouchEnd.call(this);
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('swipe', dir).trigger('swipe' + dir);
}
}
}
function onTouchStart(e) {
if (e.touches.length == 1) {
startPosX = e.touches[0].pageX;
startPosY = e.touches[0].pageY;
isMoving = true;
startTime = new Date().getTime();
this.addEventListener('touchmove', onTouchMove, false);
this.addEventListener('touchend', onTouchEnd, false);
}
}
function init() {
this.addEventListener && this.addEventListener('touchstart', onTouchStart, false);
}
function teardown() {
this.removeEventListener('touchstart', onTouchStart);
}
var SpotSwipe = function () {
function SpotSwipe($) {
_classCallCheck(this, SpotSwipe);
this.version = '1.0.0';
this.enabled = 'ontouchstart' in document.documentElement;
this.preventDefault = false;
this.moveThreshold = 75;
this.timeThreshold = 200;
this.$ = $;
this._init();
}
_createClass(SpotSwipe, [{
key: '_init',
value: function _init() {
var $ = this.$;
$.event.special.swipe = { setup: init };
$.each(['left', 'up', 'down', 'right'], function () {
$.event.special['swipe' + this] = { setup: function () {
$(this).on('swipe', $.noop);
} };
});
}
}]);
return SpotSwipe;
}();
/****************************************************
* As far as I can tell, both setupSpotSwipe and *
* setupTouchHandler should be idempotent, *
* because they directly replace functions & *
* values, and do not add event handlers directly. *
****************************************************/
Touch.setupSpotSwipe = function ($) {
$.spotSwipe = new SpotSwipe($);
};
/****************************************************
* Method for adding pseudo drag events to elements *
***************************************************/
Touch.setupTouchHandler = function ($) {
$.fn.addTouch = function () {
this.each(function (i, el) {
$(el).bind('touchstart touchmove touchend touchcancel', function (event) {
//we pass the original event object because the jQuery event
//object is normalized to w3c specs and does not provide the TouchList
handleTouch(event);
});
});
var handleTouch = function (event) {
var touches = event.changedTouches,
first = touches[0],
eventTypes = {
touchstart: 'mousedown',
touchmove: 'mousemove',
touchend: 'mouseup'
},
type = eventTypes[event.type],
simulatedEvent;
if ('MouseEvent' in window && typeof window.MouseEvent === 'function') {
simulatedEvent = new window.MouseEvent(type, {
'bubbles': true,
'cancelable': true,
'screenX': first.screenX,
'screenY': first.screenY,
'clientX': first.clientX,
'clientY': first.clientY
});
} else {
simulatedEvent = document.createEvent('MouseEvent');
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0 /*left*/, null);
}
first.target.dispatchEvent(simulatedEvent);
};
};
};
Touch.init = function ($) {
if (typeof $.spotSwipe === 'undefined') {
Touch.setupSpotSwipe($);
Touch.setupTouchHandler($);
}
};
/***/ })
/******/ }); |
/**
* Generated bundle index. Do not edit.
*/
export * from './ga';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYW5ndWxhcnRpY3MyLWdhLmpzIiwic291cmNlUm9vdCI6Im5nOi8vYW5ndWxhcnRpY3MyL2dhLyIsInNvdXJjZXMiOlsiYW5ndWxhcnRpY3MyLWdhLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBRUgsY0FBYyxNQUFNLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEdlbmVyYXRlZCBidW5kbGUgaW5kZXguIERvIG5vdCBlZGl0LlxuICovXG5cbmV4cG9ydCAqIGZyb20gJy4vZ2EnO1xuIl19 |
var fs = require('fs');
var path = require('path');
var connect = require('connect');
var middlewares = [];
function helmet(overrides) {
overrides = overrides || { csp: false };
var result = connect();
middlewares.forEach(function (name) {
if (false !== overrides[name]) {
result.use(helmet[name]());
}
});
return result;
}
var deprecated = [
{ gone: 'iexss', instead: 'xssFilter' },
{ gone: 'contentTypeOptions', instead: 'nosniff' },
{ gone: 'cacheControl', instead: 'nocache' },
{ gone: 'defaults', instead: 'helmet()' }
];
deprecated.forEach(function (method) {
var gone = method.gone;
var instead = method.instead;
helmet[gone] = function () {
throw new ReferenceError(gone + ' has been deprecated. Please use ' + instead + ' instead');
};
});
var middlewarePath = path.resolve(__dirname, 'middleware');
var middlewareFiles = fs.readdirSync(middlewarePath);
middlewareFiles.forEach(function (filename) {
if ('.js' === path.extname(filename)) {
var name = path.basename(filename, '.js');
helmet[name] = require(path.resolve(middlewarePath, filename));
middlewares.push(name);
}
});
module.exports = helmet;
|
// var stringify = require("json-stringify-safe")
var send = require("./index")
var isSendObject = require("./is-send-object")
module.exports = sendJson
function sendJson(req, res, opts, callback) {
if (!isSendObject(opts)) {
opts = { body: opts }
}
opts = opts || {}
if (opts.pretty) {
opts.space = " "
}
var tuple = safeStringify(opts.body,
opts.replacer || null, opts.space || "");
if (tuple[0]) {
return callback(tuple[0]);
}
opts.headers = opts.headers || {}
opts.body = tuple[1];
opts.headers["Content-Type"] = "application/json"
send(req, res, opts, callback)
}
function safeStringify(obj, replace, space) {
var json;
var error = null;
try {
json = JSON.stringify(obj, replace, space);
} catch (e) {
error = e;
}
return [error, json];
}
|
/*
YUI 3.17.0 (build ce55cc9)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('widget-stdmod', function (Y, NAME) {
/**
* Provides standard module support for Widgets through an extension.
*
* @module widget-stdmod
*/
var L = Y.Lang,
Node = Y.Node,
UA = Y.UA,
Widget = Y.Widget,
EMPTY = "",
HD = "hd",
BD = "bd",
FT = "ft",
HEADER = "header",
BODY = "body",
FOOTER = "footer",
FILL_HEIGHT = "fillHeight",
STDMOD = "stdmod",
NODE_SUFFIX = "Node",
CONTENT_SUFFIX = "Content",
FIRST_CHILD = "firstChild",
CHILD_NODES = "childNodes",
OWNER_DOCUMENT = "ownerDocument",
CONTENT_BOX = "contentBox",
HEIGHT = "height",
OFFSET_HEIGHT = "offsetHeight",
AUTO = "auto",
HeaderChange = "headerContentChange",
BodyChange = "bodyContentChange",
FooterChange = "footerContentChange",
FillHeightChange = "fillHeightChange",
HeightChange = "heightChange",
ContentUpdate = "contentUpdate",
RENDERUI = "renderUI",
BINDUI = "bindUI",
SYNCUI = "syncUI",
APPLY_PARSED_CONFIG = "_applyParsedConfig",
UI = Y.Widget.UI_SRC;
/**
* Widget extension, which can be used to add Standard Module support to the
* base Widget class, through the <a href="Base.html#method_build">Base.build</a>
* method.
* <p>
* The extension adds header, body and footer sections to the Widget's content box and
* provides the corresponding methods and attributes to modify the contents of these sections.
* </p>
* @class WidgetStdMod
* @param {Object} The user configuration object
*/
function StdMod(config) {}
/**
* Constant used to refer the the standard module header, in methods which expect a section specifier
*
* @property HEADER
* @static
* @type String
*/
StdMod.HEADER = HEADER;
/**
* Constant used to refer the the standard module body, in methods which expect a section specifier
*
* @property BODY
* @static
* @type String
*/
StdMod.BODY = BODY;
/**
* Constant used to refer the the standard module footer, in methods which expect a section specifier
*
* @property FOOTER
* @static
* @type String
*/
StdMod.FOOTER = FOOTER;
/**
* Constant used to specify insertion position, when adding content to sections of the standard module in
* methods which expect a "where" argument.
* <p>
* Inserts new content <em>before</em> the sections existing content.
* </p>
* @property AFTER
* @static
* @type String
*/
StdMod.AFTER = "after";
/**
* Constant used to specify insertion position, when adding content to sections of the standard module in
* methods which expect a "where" argument.
* <p>
* Inserts new content <em>before</em> the sections existing content.
* </p>
* @property BEFORE
* @static
* @type String
*/
StdMod.BEFORE = "before";
/**
* Constant used to specify insertion position, when adding content to sections of the standard module in
* methods which expect a "where" argument.
* <p>
* <em>Replaces</em> the sections existing content, with new content.
* </p>
* @property REPLACE
* @static
* @type String
*/
StdMod.REPLACE = "replace";
var STD_HEADER = StdMod.HEADER,
STD_BODY = StdMod.BODY,
STD_FOOTER = StdMod.FOOTER,
HEADER_CONTENT = STD_HEADER + CONTENT_SUFFIX,
FOOTER_CONTENT = STD_FOOTER + CONTENT_SUFFIX,
BODY_CONTENT = STD_BODY + CONTENT_SUFFIX;
/**
* Static property used to define the default attribute
* configuration introduced by WidgetStdMod.
*
* @property ATTRS
* @type Object
* @static
*/
StdMod.ATTRS = {
/**
* @attribute headerContent
* @type HTML
* @default undefined
* @description The content to be added to the header section. This will replace any existing content
* in the header. If you want to append, or insert new content, use the <a href="#method_setStdModContent">setStdModContent</a> method.
*/
headerContent: {
value:null
},
/**
* @attribute footerContent
* @type HTML
* @default undefined
* @description The content to be added to the footer section. This will replace any existing content
* in the footer. If you want to append, or insert new content, use the <a href="#method_setStdModContent">setStdModContent</a> method.
*/
footerContent: {
value:null
},
/**
* @attribute bodyContent
* @type HTML
* @default undefined
* @description The content to be added to the body section. This will replace any existing content
* in the body. If you want to append, or insert new content, use the <a href="#method_setStdModContent">setStdModContent</a> method.
*/
bodyContent: {
value:null
},
/**
* @attribute fillHeight
* @type {String}
* @default WidgetStdMod.BODY
* @description The section (WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER) which should be resized to fill the height of the standard module, when a
* height is set on the Widget. If a height is not set on the widget, then all sections are sized based on
* their content.
*/
fillHeight: {
value: StdMod.BODY,
validator: function(val) {
return this._validateFillHeight(val);
}
}
};
/**
* The HTML parsing rules for the WidgetStdMod class.
*
* @property HTML_PARSER
* @static
* @type Object
*/
StdMod.HTML_PARSER = {
headerContent: function(contentBox) {
return this._parseStdModHTML(STD_HEADER);
},
bodyContent: function(contentBox) {
return this._parseStdModHTML(STD_BODY);
},
footerContent : function(contentBox) {
return this._parseStdModHTML(STD_FOOTER);
}
};
/**
* Static hash of default class names used for the header,
* body and footer sections of the standard module, keyed by
* the section identifier (WidgetStdMod.STD_HEADER, WidgetStdMod.STD_BODY, WidgetStdMod.STD_FOOTER)
*
* @property SECTION_CLASS_NAMES
* @static
* @type Object
*/
StdMod.SECTION_CLASS_NAMES = {
header: Widget.getClassName(HD),
body: Widget.getClassName(BD),
footer: Widget.getClassName(FT)
};
/**
* The template HTML strings for each of the standard module sections. Section entries are keyed by the section constants,
* WidgetStdMod.HEADER, WidgetStdMod.BODY, WidgetStdMod.FOOTER, and contain the HTML to be added for each section.
* e.g.
* <pre>
* {
* header : '<div class="yui-widget-hd"></div>',
* body : '<div class="yui-widget-bd"></div>',
* footer : '<div class="yui-widget-ft"></div>'
* }
* </pre>
* @property TEMPLATES
* @type Object
* @static
*/
StdMod.TEMPLATES = {
header : '<div class="' + StdMod.SECTION_CLASS_NAMES[STD_HEADER] + '"></div>',
body : '<div class="' + StdMod.SECTION_CLASS_NAMES[STD_BODY] + '"></div>',
footer : '<div class="' + StdMod.SECTION_CLASS_NAMES[STD_FOOTER] + '"></div>'
};
StdMod.prototype = {
initializer : function() {
this._stdModNode = this.get(CONTENT_BOX);
Y.before(this._renderUIStdMod, this, RENDERUI);
Y.before(this._bindUIStdMod, this, BINDUI);
Y.before(this._syncUIStdMod, this, SYNCUI);
},
/**
* Synchronizes the UI to match the Widgets standard module state.
* <p>
* This method is invoked after syncUI is invoked for the Widget class
* using YUI's aop infrastructure.
* </p>
* @method _syncUIStdMod
* @protected
*/
_syncUIStdMod : function() {
var stdModParsed = this._stdModParsed;
if (!stdModParsed || !stdModParsed[HEADER_CONTENT]) {
this._uiSetStdMod(STD_HEADER, this.get(HEADER_CONTENT));
}
if (!stdModParsed || !stdModParsed[BODY_CONTENT]) {
this._uiSetStdMod(STD_BODY, this.get(BODY_CONTENT));
}
if (!stdModParsed || !stdModParsed[FOOTER_CONTENT]) {
this._uiSetStdMod(STD_FOOTER, this.get(FOOTER_CONTENT));
}
this._uiSetFillHeight(this.get(FILL_HEIGHT));
},
/**
* Creates/Initializes the DOM for standard module support.
* <p>
* This method is invoked after renderUI is invoked for the Widget class
* using YUI's aop infrastructure.
* </p>
* @method _renderUIStdMod
* @protected
*/
_renderUIStdMod : function() {
this._stdModNode.addClass(Widget.getClassName(STDMOD));
this._renderStdModSections();
//This normally goes in bindUI but in order to allow setStdModContent() to work before renderUI
//stage, these listeners should be set up at the earliest possible time.
this.after(HeaderChange, this._afterHeaderChange);
this.after(BodyChange, this._afterBodyChange);
this.after(FooterChange, this._afterFooterChange);
},
_renderStdModSections : function() {
if (L.isValue(this.get(HEADER_CONTENT))) { this._renderStdMod(STD_HEADER); }
if (L.isValue(this.get(BODY_CONTENT))) { this._renderStdMod(STD_BODY); }
if (L.isValue(this.get(FOOTER_CONTENT))) { this._renderStdMod(STD_FOOTER); }
},
/**
* Binds event listeners responsible for updating the UI state in response to
* Widget standard module related state changes.
* <p>
* This method is invoked after bindUI is invoked for the Widget class
* using YUI's aop infrastructure.
* </p>
* @method _bindUIStdMod
* @protected
*/
_bindUIStdMod : function() {
// this.after(HeaderChange, this._afterHeaderChange);
// this.after(BodyChange, this._afterBodyChange);
// this.after(FooterChange, this._afterFooterChange);
this.after(FillHeightChange, this._afterFillHeightChange);
this.after(HeightChange, this._fillHeight);
this.after(ContentUpdate, this._fillHeight);
},
/**
* Default attribute change listener for the headerContent attribute, responsible
* for updating the UI, in response to attribute changes.
*
* @method _afterHeaderChange
* @protected
* @param {EventFacade} e The event facade for the attribute change
*/
_afterHeaderChange : function(e) {
if (e.src !== UI) {
this._uiSetStdMod(STD_HEADER, e.newVal, e.stdModPosition);
}
},
/**
* Default attribute change listener for the bodyContent attribute, responsible
* for updating the UI, in response to attribute changes.
*
* @method _afterBodyChange
* @protected
* @param {EventFacade} e The event facade for the attribute change
*/
_afterBodyChange : function(e) {
if (e.src !== UI) {
this._uiSetStdMod(STD_BODY, e.newVal, e.stdModPosition);
}
},
/**
* Default attribute change listener for the footerContent attribute, responsible
* for updating the UI, in response to attribute changes.
*
* @method _afterFooterChange
* @protected
* @param {EventFacade} e The event facade for the attribute change
*/
_afterFooterChange : function(e) {
if (e.src !== UI) {
this._uiSetStdMod(STD_FOOTER, e.newVal, e.stdModPosition);
}
},
/**
* Default attribute change listener for the fillHeight attribute, responsible
* for updating the UI, in response to attribute changes.
*
* @method _afterFillHeightChange
* @protected
* @param {EventFacade} e The event facade for the attribute change
*/
_afterFillHeightChange: function (e) {
this._uiSetFillHeight(e.newVal);
},
/**
* Default validator for the fillHeight attribute. Verifies that the
* value set is a valid section specifier - one of WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER,
* or a falsey value if fillHeight is to be disabled.
*
* @method _validateFillHeight
* @protected
* @param {String} val The section which should be setup to fill height, or false/null to disable fillHeight
* @return true if valid, false if not
*/
_validateFillHeight : function(val) {
return !val || val == StdMod.BODY || val == StdMod.HEADER || val == StdMod.FOOTER;
},
/**
* Updates the rendered UI, to resize the provided section so that the standard module fills out
* the specified widget height. Note: This method does not check whether or not a height is set
* on the Widget.
*
* @method _uiSetFillHeight
* @protected
* @param {String} fillSection A valid section specifier - one of WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER
*/
_uiSetFillHeight : function(fillSection) {
var fillNode = this.getStdModNode(fillSection);
var currNode = this._currFillNode;
if (currNode && fillNode !== currNode){
currNode.setStyle(HEIGHT, EMPTY);
}
if (fillNode) {
this._currFillNode = fillNode;
}
this._fillHeight();
},
/**
* Updates the rendered UI, to resize the current section specified by the fillHeight attribute, so
* that the standard module fills out the Widget height. If a height has not been set on Widget,
* the section is not resized (height is set to "auto").
*
* @method _fillHeight
* @private
*/
_fillHeight : function() {
if (this.get(FILL_HEIGHT)) {
var height = this.get(HEIGHT);
if (height != EMPTY && height != AUTO) {
this.fillHeight(this.getStdModNode(this.get(FILL_HEIGHT)));
}
}
},
/**
* Updates the rendered UI, adding the provided content (either an HTML string, or node reference),
* to the specified section. The content is either added before, after or replaces existing content
* in the section, based on the value of the <code>where</code> argument.
*
* @method _uiSetStdMod
* @protected
*
* @param {String} section The section to be updated. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
* @param {String | Node} content The new content (either as an HTML string, or Node reference) to add to the section
* @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE.
* If not provided, the content will replace existing content in the section.
*/
_uiSetStdMod : function(section, content, where) {
// Using isValue, so that "" is valid content
if (L.isValue(content)) {
var node = this.getStdModNode(section, true);
this._addStdModContent(node, content, where);
this.set(section + CONTENT_SUFFIX, this._getStdModContent(section), {src:UI});
} else {
this._eraseStdMod(section);
}
this.fire(ContentUpdate);
},
/**
* Creates the DOM node for the given section, and inserts it into the correct location in the contentBox.
*
* @method _renderStdMod
* @protected
* @param {String} section The section to create/render. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
* @return {Node} A reference to the added section node
*/
_renderStdMod : function(section) {
var contentBox = this.get(CONTENT_BOX),
sectionNode = this._findStdModSection(section);
if (!sectionNode) {
sectionNode = this._getStdModTemplate(section);
}
this._insertStdModSection(contentBox, section, sectionNode);
this[section + NODE_SUFFIX] = sectionNode;
return this[section + NODE_SUFFIX];
},
/**
* Removes the DOM node for the given section.
*
* @method _eraseStdMod
* @protected
* @param {String} section The section to remove. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
*/
_eraseStdMod : function(section) {
var sectionNode = this.getStdModNode(section);
if (sectionNode) {
sectionNode.remove(true);
delete this[section + NODE_SUFFIX];
}
},
/**
* Helper method to insert the Node for the given section into the correct location in the contentBox.
*
* @method _insertStdModSection
* @private
* @param {Node} contentBox A reference to the Widgets content box.
* @param {String} section The section to create/render. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
* @param {Node} sectionNode The Node for the section.
*/
_insertStdModSection : function(contentBox, section, sectionNode) {
var fc = contentBox.get(FIRST_CHILD);
if (section === STD_FOOTER || !fc) {
contentBox.appendChild(sectionNode);
} else {
if (section === STD_HEADER) {
contentBox.insertBefore(sectionNode, fc);
} else {
var footer = this[STD_FOOTER + NODE_SUFFIX];
if (footer) {
contentBox.insertBefore(sectionNode, footer);
} else {
contentBox.appendChild(sectionNode);
}
}
}
},
/**
* Gets a new Node reference for the given standard module section, by cloning
* the stored template node.
*
* @method _getStdModTemplate
* @protected
* @param {String} section The section to create a new node for. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
* @return {Node} The new Node instance for the section
*/
_getStdModTemplate : function(section) {
return Node.create(StdMod.TEMPLATES[section], this._stdModNode.get(OWNER_DOCUMENT));
},
/**
* Helper method to add content to a StdMod section node.
* The content is added either before, after or replaces the existing node content
* based on the value of the <code>where</code> argument.
*
* @method _addStdModContent
* @private
*
* @param {Node} node The section Node to be updated.
* @param {Node|NodeList|String} children The new content Node, NodeList or String to be added to section Node provided.
* @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE.
* If not provided, the content will replace existing content in the Node.
*/
_addStdModContent : function(node, children, where) {
// StdMod where to Node where
switch (where) {
case StdMod.BEFORE: // 0 is before fistChild
where = 0;
break;
case StdMod.AFTER: // undefined is appendChild
where = undefined;
break;
default: // replace is replace, not specified is replace
where = StdMod.REPLACE;
}
node.insert(children, where);
},
/**
* Helper method to obtain the precise height of the node provided, including padding and border.
* The height could be a sub-pixel value for certain browsers, such as Firefox 3.
*
* @method _getPreciseHeight
* @private
* @param {Node} node The node for which the precise height is required.
* @return {Number} The height of the Node including borders and padding, possibly a float.
*/
_getPreciseHeight : function(node) {
var height = (node) ? node.get(OFFSET_HEIGHT) : 0,
getBCR = "getBoundingClientRect";
if (node && node.hasMethod(getBCR)) {
var preciseRegion = node.invoke(getBCR);
if (preciseRegion) {
height = preciseRegion.bottom - preciseRegion.top;
}
}
return height;
},
/**
* Helper method to to find the rendered node for the given section,
* if it exists.
*
* @method _findStdModSection
* @private
* @param {String} section The section for which the render Node is to be found. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
* @return {Node} The rendered node for the given section, or null if not found.
*/
_findStdModSection: function(section) {
return this.get(CONTENT_BOX).one("> ." + StdMod.SECTION_CLASS_NAMES[section]);
},
/**
* Utility method, used by WidgetStdMods HTML_PARSER implementation
* to extract data for each section from markup.
*
* @method _parseStdModHTML
* @private
* @param {String} section
* @return {String} Inner HTML string with the contents of the section
*/
_parseStdModHTML : function(section) {
var node = this._findStdModSection(section);
if (node) {
if (!this._stdModParsed) {
this._stdModParsed = {};
Y.before(this._applyStdModParsedConfig, this, APPLY_PARSED_CONFIG);
}
this._stdModParsed[section + CONTENT_SUFFIX] = 1;
return node.get("innerHTML");
}
return null;
},
/**
* This method is injected before the _applyParsedConfig step in
* the application of HTML_PARSER, and sets up the state to
* identify whether or not we should remove the current DOM content
* or not, based on whether or not the current content attribute value
* was extracted from the DOM, or provided by the user configuration
*
* @method _applyStdModParsedConfig
* @private
*/
_applyStdModParsedConfig : function(node, cfg, parsedCfg) {
var parsed = this._stdModParsed;
if (parsed) {
parsed[HEADER_CONTENT] = !(HEADER_CONTENT in cfg) && (HEADER_CONTENT in parsed);
parsed[BODY_CONTENT] = !(BODY_CONTENT in cfg) && (BODY_CONTENT in parsed);
parsed[FOOTER_CONTENT] = !(FOOTER_CONTENT in cfg) && (FOOTER_CONTENT in parsed);
}
},
/**
* Retrieves the child nodes (content) of a standard module section
*
* @method _getStdModContent
* @private
* @param {String} section The standard module section whose child nodes are to be retrieved. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
* @return {Node} The child node collection of the standard module section.
*/
_getStdModContent : function(section) {
return (this[section + NODE_SUFFIX]) ? this[section + NODE_SUFFIX].get(CHILD_NODES) : null;
},
/**
* Updates the body section of the standard module with the content provided (either an HTML string, or node reference).
* <p>
* This method can be used instead of the corresponding section content attribute if you'd like to retain the current content of the section,
* and insert content before or after it, by specifying the <code>where</code> argument.
* </p>
* @method setStdModContent
* @param {String} section The standard module section whose content is to be updated. Either WidgetStdMod.HEADER, WidgetStdMod.BODY or WidgetStdMod.FOOTER.
* @param {String | Node} content The content to be added, either an HTML string or a Node reference.
* @param {String} where Optional. Either WidgetStdMod.AFTER, WidgetStdMod.BEFORE or WidgetStdMod.REPLACE.
* If not provided, the content will replace existing content in the section.
*/
setStdModContent : function(section, content, where) {
//var node = this.getStdModNode(section) || this._renderStdMod(section);
this.set(section + CONTENT_SUFFIX, content, {stdModPosition:where});
//this._addStdModContent(node, content, where);
},
/**
Returns the node reference for the specified `section`.
**Note:** The DOM is not queried for the node reference. The reference
stored by the widget instance is returned if it was set. Passing a
truthy for `forceCreate` will create the section node if it does not
already exist.
@method getStdModNode
@param {String} section The section whose node reference is required.
Either `WidgetStdMod.HEADER`, `WidgetStdMod.BODY`, or
`WidgetStdMod.FOOTER`.
@param {Boolean} forceCreate Whether the section node should be created
if it does not already exist.
@return {Node} The node reference for the `section`, or null if not set.
**/
getStdModNode : function(section, forceCreate) {
var node = this[section + NODE_SUFFIX] || null;
if (!node && forceCreate) {
node = this._renderStdMod(section);
}
return node;
},
/**
* Sets the height on the provided header, body or footer element to
* fill out the height of the Widget. It determines the height of the
* widgets bounding box, based on it's configured height value, and
* sets the height of the provided section to fill out any
* space remaining after the other standard module section heights
* have been accounted for.
*
* <p><strong>NOTE:</strong> This method is not designed to work if an explicit
* height has not been set on the Widget, since for an "auto" height Widget,
* the heights of the header/body/footer will drive the height of the Widget.</p>
*
* @method fillHeight
* @param {Node} node The node which should be resized to fill out the height
* of the Widget bounding box. Should be a standard module section node which belongs
* to the widget.
*/
fillHeight : function(node) {
if (node) {
var contentBox = this.get(CONTENT_BOX),
stdModNodes = [this.headerNode, this.bodyNode, this.footerNode],
stdModNode,
cbContentHeight,
filled = 0,
remaining = 0,
validNode = false;
for (var i = 0, l = stdModNodes.length; i < l; i++) {
stdModNode = stdModNodes[i];
if (stdModNode) {
if (stdModNode !== node) {
filled += this._getPreciseHeight(stdModNode);
} else {
validNode = true;
}
}
}
if (validNode) {
if (UA.ie || UA.opera) {
// Need to set height to 0, to allow height to be reduced
node.set(OFFSET_HEIGHT, 0);
}
cbContentHeight = contentBox.get(OFFSET_HEIGHT) -
parseInt(contentBox.getComputedStyle("paddingTop"), 10) -
parseInt(contentBox.getComputedStyle("paddingBottom"), 10) -
parseInt(contentBox.getComputedStyle("borderBottomWidth"), 10) -
parseInt(contentBox.getComputedStyle("borderTopWidth"), 10);
if (L.isNumber(cbContentHeight)) {
remaining = cbContentHeight - filled;
if (remaining >= 0) {
node.set(OFFSET_HEIGHT, remaining);
}
}
}
}
}
};
Y.WidgetStdMod = StdMod;
}, '3.17.0', {"requires": ["base-build", "widget"]});
|
'use strict';
/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
, expect = chai.expect
, Sequelize = require('../../index')
, Support = require(__dirname + '/support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, dialect = Support.getTestDialect()
, config = require(__dirname + '/../config/config')
, sinon = require('sinon')
, uuid = require('node-uuid')
, current = Support.sequelize;
describe(Support.getTestDialectTeaser('Instance'), function() {
beforeEach(function() {
this.User = this.sequelize.define('User', {
username: { type: DataTypes.STRING },
uuidv1: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV1 },
uuidv4: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 },
touchedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
aNumber: { type: DataTypes.INTEGER },
bNumber: { type: DataTypes.INTEGER },
aDate: { type: DataTypes.DATE },
validateTest: {
type: DataTypes.INTEGER,
allowNull: true,
validate: {isInt: true}
},
validateCustom: {
type: DataTypes.STRING,
allowNull: true,
validate: {len: {msg: 'Length failed.', args: [1, 20]}}
},
dateAllowNullTrue: {
type: DataTypes.DATE,
allowNull: true
},
isSuperUser: {
type: DataTypes.BOOLEAN,
defaultValue: false
}
});
return this.User.sync({ force: true });
});
describe('Escaping', function() {
it('is done properly for special characters', function() {
// Ideally we should test more: "\0\n\r\b\t\\\'\"\x1a"
// But this causes sqlite to fail and exits the entire test suite immediately
var bio = dialect + "'\"\n" // Need to add the dialect here so in case of failure I know what DB it failed for
, self = this;
return this.User.create({ username: bio }).then(function(u1) {
return self.User.findById(u1.id).then(function(u2) {
expect(u2.username).to.equal(bio);
});
});
});
});
describe('isNewRecord', function() {
it('returns true for non-saved objects', function() {
var user = this.User.build({ username: 'user' });
expect(user.id).to.be.null;
expect(user.isNewRecord).to.be.ok;
});
it('returns false for saved objects', function() {
return this.User.build({ username: 'user' }).save().then(function(user) {
expect(user.isNewRecord).to.not.be.ok;
});
});
it('returns false for created objects', function() {
return this.User.create({ username: 'user' }).then(function(user) {
expect(user.isNewRecord).to.not.be.ok;
});
});
it('returns false for objects found by find method', function() {
var self = this;
return this.User.create({ username: 'user' }).then(function() {
return self.User.create({ username: 'user' }).then(function(user) {
return self.User.findById(user.id).then(function(user) {
expect(user.isNewRecord).to.not.be.ok;
});
});
});
});
it('returns false for objects found by findAll method', function() {
var self = this
, users = [];
for (var i = 0; i < 10; i++) {
users[users.length] = {username: 'user'};
}
return this.User.bulkCreate(users).then(function() {
return self.User.findAll().then(function(users) {
users.forEach(function(u) {
expect(u.isNewRecord).to.not.be.ok;
});
});
});
});
});
describe('increment', function() {
beforeEach(function() {
return this.User.create({ id: 1, aNumber: 0, bNumber: 0 });
});
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
var User = sequelize.define('User', { number: Support.Sequelize.INTEGER });
return User.sync({ force: true }).then(function() {
return User.create({ number: 1 }).then(function(user) {
return sequelize.transaction().then(function(t) {
return user.increment('number', { by: 2, transaction: t }).then(function() {
return User.findAll().then(function(users1) {
return User.findAll({ transaction: t }).then(function(users2) {
expect(users1[0].number).to.equal(1);
expect(users2[0].number).to.equal(3);
return t.rollback();
});
});
});
});
});
});
});
});
}
if (current.dialect.supports.returnValues.returning) {
it('supports returning', function() {
return this.User.findById(1).then(function(user1) {
return user1.increment('aNumber', { by: 2 }).then(function() {
expect(user1.aNumber).to.be.equal(2);
});
});
});
}
it('supports where conditions', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.increment(['aNumber'], { by: 2, where: { bNumber: 1 } }).then(function() {
return self.User.findById(1).then(function(user3) {
expect(user3.aNumber).to.be.equal(0);
});
});
});
});
it('with array', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.increment(['aNumber'], { by: 2 }).then(function() {
return self.User.findById(1).then(function(user3) {
expect(user3.aNumber).to.be.equal(2);
});
});
});
});
it('with single field', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.increment('aNumber', { by: 2 }).then(function() {
return self.User.findById(1).then(function(user3) {
expect(user3.aNumber).to.be.equal(2);
});
});
});
});
it('with single field and no value', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.increment('aNumber').then(function() {
return self.User.findById(1).then(function(user2) {
expect(user2.aNumber).to.be.equal(1);
});
});
});
});
it('should still work right with other concurrent updates', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
// Select the user again (simulating a concurrent query)
return self.User.findById(1).then(function(user2) {
return user2.updateAttributes({
aNumber: user2.aNumber + 1
}).then(function() {
return user1.increment(['aNumber'], { by: 2 }).then(function() {
return self.User.findById(1).then(function(user5) {
expect(user5.aNumber).to.be.equal(3);
});
});
});
});
});
});
it('should still work right with other concurrent increments', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return this.sequelize.Promise.all([
user1.increment(['aNumber'], { by: 2 }),
user1.increment(['aNumber'], { by: 2 }),
user1.increment(['aNumber'], { by: 2 })
]).then(function() {
return self.User.findById(1).then(function(user2) {
expect(user2.aNumber).to.equal(6);
});
});
});
});
it('with key value pair', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.increment({ 'aNumber': 1, 'bNumber': 2 }).then(function() {
return self.User.findById(1).then(function(user3) {
expect(user3.aNumber).to.be.equal(1);
expect(user3.bNumber).to.be.equal(2);
});
});
});
});
it('with timestamps set to true', function() {
var User = this.sequelize.define('IncrementUser', {
aNumber: DataTypes.INTEGER
}, { timestamps: true });
return User.sync({ force: true }).then(function() {
return User.create({aNumber: 1}).then(function(user) {
var oldDate = user.updatedAt;
return this.sequelize.Promise.delay(1000).then(function() {
return user.increment('aNumber', { by: 1 }).then(function() {
return User.findById(1).then(function(user) {
expect(user.updatedAt).to.be.afterTime(oldDate);
});
});
});
});
});
});
});
describe('decrement', function() {
beforeEach(function() {
return this.User.create({ id: 1, aNumber: 0, bNumber: 0 });
});
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
var User = sequelize.define('User', { number: Support.Sequelize.INTEGER });
return User.sync({ force: true }).then(function() {
return User.create({ number: 3 }).then(function(user) {
return sequelize.transaction().then(function(t) {
return user.decrement('number', { by: 2, transaction: t }).then(function() {
return User.findAll().then(function(users1) {
return User.findAll({ transaction: t }).then(function(users2) {
expect(users1[0].number).to.equal(3);
expect(users2[0].number).to.equal(1);
return t.rollback();
});
});
});
});
});
});
});
});
}
it('with array', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.decrement(['aNumber'], { by: 2 }).then(function() {
return self.User.findById(1).then(function(user3) {
expect(user3.aNumber).to.be.equal(-2);
});
});
});
});
it('with single field', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.decrement('aNumber', { by: 2 }).then(function() {
return self.User.findById(1).then(function(user3) {
expect(user3.aNumber).to.be.equal(-2);
});
});
});
});
it('with single field and no value', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.decrement('aNumber').then(function() {
return self.User.findById(1).then(function(user2) {
expect(user2.aNumber).to.be.equal(-1);
});
});
});
});
it('should still work right with other concurrent updates', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
// Select the user again (simulating a concurrent query)
return self.User.findById(1).then(function(user2) {
return user2.updateAttributes({
aNumber: user2.aNumber + 1
}).then(function() {
return user1.decrement(['aNumber'], { by: 2 }).then(function() {
return self.User.findById(1).then(function(user5) {
expect(user5.aNumber).to.be.equal(-1);
});
});
});
});
});
});
it('should still work right with other concurrent increments', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return this.sequelize.Promise.all([
user1.decrement(['aNumber'], { by: 2 }),
user1.decrement(['aNumber'], { by: 2 }),
user1.decrement(['aNumber'], { by: 2 })
]).then(function() {
return self.User.findById(1).then(function(user2) {
expect(user2.aNumber).to.equal(-6);
});
});
});
});
it('with key value pair', function() {
var self = this;
return this.User.findById(1).then(function(user1) {
return user1.decrement({ 'aNumber': 1, 'bNumber': 2}).then(function() {
return self.User.findById(1).then(function(user3) {
expect(user3.aNumber).to.be.equal(-1);
expect(user3.bNumber).to.be.equal(-2);
});
});
});
});
it('with timestamps set to true', function() {
var User = this.sequelize.define('IncrementUser', {
aNumber: DataTypes.INTEGER
}, { timestamps: true });
return User.sync({ force: true }).then(function() {
return User.create({aNumber: 1}).then(function(user) {
var oldDate = user.updatedAt;
return this.sequelize.Promise.delay(1000).then(function() {
return user.decrement('aNumber', { by: 1 }).then(function() {
return User.findById(1).then(function(user) {
expect(user.updatedAt).to.be.afterTime(oldDate);
});
});
});
});
});
});
});
describe('reload', function() {
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
var User = sequelize.define('User', { username: Support.Sequelize.STRING });
return User.sync({ force: true }).then(function() {
return User.create({ username: 'foo' }).then(function(user) {
return sequelize.transaction().then(function(t) {
return User.update({ username: 'bar' }, {where: {username: 'foo'}, transaction: t }).then(function() {
return user.reload().then(function(user) {
expect(user.username).to.equal('foo');
return user.reload({ transaction: t }).then(function(user) {
expect(user.username).to.equal('bar');
return t.rollback();
});
});
});
});
});
});
});
});
}
it('should return a reference to the same DAO instead of creating a new one', function() {
return this.User.create({ username: 'John Doe' }).then(function(originalUser) {
return originalUser.updateAttributes({ username: 'Doe John' }).then(function() {
return originalUser.reload().then(function(updatedUser) {
expect(originalUser === updatedUser).to.be.true;
});
});
});
});
it('should update the values on all references to the DAO', function() {
var self = this;
return this.User.create({ username: 'John Doe' }).then(function(originalUser) {
return self.User.findById(originalUser.id).then(function(updater) {
return updater.updateAttributes({ username: 'Doe John' }).then(function() {
// We used a different reference when calling updateAttributes, so originalUser is now out of sync
expect(originalUser.username).to.equal('John Doe');
return originalUser.reload().then(function(updatedUser) {
expect(originalUser.username).to.equal('Doe John');
expect(updatedUser.username).to.equal('Doe John');
});
});
});
});
});
it('should support updating a subset of attributes', function () {
return this.User.create({
aNumber: 1,
bNumber: 1,
}).bind(this).tap(function (user) {
return this.User.update({
bNumber: 2
}, {
where: {
id: user.get('id')
}
});
}).then(function (user) {
return user.reload({
attributes: ['bNumber']
});
}).then(function (user) {
expect(user.get('aNumber')).to.equal(1);
expect(user.get('bNumber')).to.equal(2);
});
});
it('should update read only attributes as well (updatedAt)', function() {
var self = this;
return this.User.create({ username: 'John Doe' }).then(function(originalUser) {
var originallyUpdatedAt = originalUser.updatedAt;
// Wait for a second, so updatedAt will actually be different
return this.sequelize.Promise.delay(1000).then(function() {
return self.User.findById(originalUser.id).then(function(updater) {
return updater.updateAttributes({ username: 'Doe John' }).then(function() {
return originalUser.reload().then(function(updatedUser) {
expect(originalUser.updatedAt).to.be.above(originallyUpdatedAt);
expect(updatedUser.updatedAt).to.be.above(originallyUpdatedAt);
});
});
});
});
});
});
it('should update the associations as well', function() {
var Book = this.sequelize.define('Book', { title: DataTypes.STRING })
, Page = this.sequelize.define('Page', { content: DataTypes.TEXT });
Book.hasMany(Page);
Page.belongsTo(Book);
return Book.sync({force: true}).then(function() {
return Page.sync({force: true}).then(function() {
return Book.create({ title: 'A very old book' }).then(function(book) {
return Page.create({ content: 'om nom nom' }).then(function(page) {
return book.setPages([page]).then(function() {
return Book.findOne({
where: { id: book.id },
include: [Page]
}).then(function(leBook) {
return page.updateAttributes({ content: 'something totally different' }).then(function(page) {
expect(leBook.Pages.length).to.equal(1);
expect(leBook.Pages[0].content).to.equal('om nom nom');
expect(page.content).to.equal('something totally different');
return leBook.reload().then(function(leBook) {
expect(leBook.Pages.length).to.equal(1);
expect(leBook.Pages[0].content).to.equal('something totally different');
expect(page.content).to.equal('something totally different');
});
});
});
});
});
});
});
});
});
it('should set an association to null after deletion, 1-1', function() {
var Shoe = this.sequelize.define('Shoe', { brand: DataTypes.STRING })
, Player = this.sequelize.define('Player', { name: DataTypes.STRING });
Player.hasOne(Shoe);
Shoe.belongsTo(Player);
return this.sequelize.sync({force: true}).then(function() {
return Shoe.create({
brand: 'the brand',
Player: {
name: 'the player'
}
}, {include: [Player]});
}).then(function(shoe) {
return Player.findOne({
where: { id: shoe.Player.id },
include: [Shoe]
}).then(function(lePlayer) {
expect(lePlayer.Shoe).not.to.be.null;
return lePlayer.Shoe.destroy().return(lePlayer);
}).then(function(lePlayer) {
return lePlayer.reload();
}).then(function(lePlayer) {
expect(lePlayer.Shoe).to.be.null;
});
});
});
it('should set an association to empty after all deletion, 1-N', function() {
var Team = this.sequelize.define('Team', { name: DataTypes.STRING })
, Player = this.sequelize.define('Player', { name: DataTypes.STRING });
Team.hasMany(Player);
Player.belongsTo(Team);
return this.sequelize.sync({force: true}).then(function() {
return Team.create({
name: 'the team',
Players: [{
name: 'the player1'
}, {
name: 'the player2'
}]
}, {include: [Player]});
}).then(function(team) {
return Team.findOne({
where: { id: team.id },
include: [Player]
}).then(function(leTeam) {
expect(leTeam.Players).not.to.be.empty;
return leTeam.Players[1].destroy().then(function() {
return leTeam.Players[0].destroy();
}).return(leTeam);
}).then(function(leTeam) {
return leTeam.reload();
}).then(function(leTeam) {
expect(leTeam.Players).to.be.empty;
});
});
});
it('should update the associations after one element deleted', function() {
var Team = this.sequelize.define('Team', { name: DataTypes.STRING })
, Player = this.sequelize.define('Player', { name: DataTypes.STRING });
Team.hasMany(Player);
Player.belongsTo(Team);
return this.sequelize.sync({force: true}).then(function() {
return Team.create({
name: 'the team',
Players: [{
name: 'the player1'
}, {
name: 'the player2'
}]
}, {include: [Player]});
}).then(function(team) {
return Team.findOne({
where: { id: team.id },
include: [Player]
}).then(function(leTeam) {
expect(leTeam.Players).to.have.length(2);
return leTeam.Players[0].destroy().return(leTeam);
}).then(function(leTeam) {
return leTeam.reload();
}).then(function(leTeam) {
expect(leTeam.Players).to.have.length(1);
});
});
});
});
describe('default values', function() {
describe('uuid', function() {
it('should store a string in uuidv1 and uuidv4', function() {
var user = this.User.build({ username: 'a user'});
expect(user.uuidv1).to.be.a('string');
expect(user.uuidv4).to.be.a('string');
});
it('should store a string of length 36 in uuidv1 and uuidv4', function() {
var user = this.User.build({ username: 'a user'});
expect(user.uuidv1).to.have.length(36);
expect(user.uuidv4).to.have.length(36);
});
it('should store a valid uuid in uuidv1 and uuidv4 that can be parsed to something of length 16', function() {
var user = this.User.build({ username: 'a user'});
expect(uuid.parse(user.uuidv1)).to.have.length(16);
expect(uuid.parse(user.uuidv4)).to.have.length(16);
});
it('should store a valid uuid if the field is a primary key named id', function() {
var Person = this.sequelize.define('Person', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV1,
primaryKey: true
}
});
var person = Person.build({});
expect(person.id).to.be.ok;
expect(person.id).to.have.length(36);
});
});
describe('current date', function() {
it('should store a date in touchedAt', function() {
var user = this.User.build({ username: 'a user'});
expect(user.touchedAt).to.be.instanceof(Date);
});
it('should store the current date in touchedAt', function() {
var clock = sinon.useFakeTimers();
clock.tick(5000);
var user = this.User.build({ username: 'a user'});
clock.restore();
expect(+user.touchedAt).to.be.equal(5000);
});
});
describe('allowNull date', function() {
it('should be just "null" and not Date with Invalid Date', function() {
var self = this;
return this.User.build({ username: 'a user'}).save().then(function() {
return self.User.findOne({where: {username: 'a user'}}).then(function(user) {
expect(user.dateAllowNullTrue).to.be.null;
});
});
});
it('should be the same valid date when saving the date', function() {
var self = this;
var date = new Date();
return this.User.build({ username: 'a user', dateAllowNullTrue: date}).save().then(function() {
return self.User.findOne({where: {username: 'a user'}}).then(function(user) {
expect(user.dateAllowNullTrue.toString()).to.equal(date.toString());
});
});
});
});
describe('super user boolean', function() {
it('should default to false', function() {
return this.User.build({
username: 'a user'
})
.save()
.bind(this)
.then(function() {
return this.User.findOne({
where: {
username: 'a user'
}
})
.then(function(user) {
expect(user.isSuperUser).to.be.false;
});
});
});
it('should override default when given truthy boolean', function() {
return this.User.build({
username: 'a user',
isSuperUser: true
})
.save()
.bind(this)
.then(function() {
return this.User.findOne({
where: {
username: 'a user'
}
})
.then(function(user) {
expect(user.isSuperUser).to.be.true;
});
});
});
it('should override default when given truthy boolean-string ("true")', function() {
return this.User.build({
username: 'a user',
isSuperUser: "true"
})
.save()
.bind(this)
.then(function() {
return this.User.findOne({
where: {
username: 'a user'
}
})
.then(function(user) {
expect(user.isSuperUser).to.be.true;
});
});
});
it('should override default when given truthy boolean-int (1)', function() {
return this.User.build({
username: 'a user',
isSuperUser: 1
})
.save()
.bind(this)
.then(function() {
return this.User.findOne({
where: {
username: 'a user'
}
})
.then(function(user) {
expect(user.isSuperUser).to.be.true;
});
});
});
it('should throw error when given value of incorrect type', function() {
var callCount = 0;
return this.User.build({
username: 'a user',
isSuperUser: "INCORRECT_VALUE_TYPE"
})
.save()
.then(function () {
callCount += 1;
})
.catch(function(err) {
expect(callCount).to.equal(0);
expect(err).to.exist;
expect(err.message).to.exist;
});
});
});
});
describe('complete', function() {
it('gets triggered if an error occurs', function() {
return this.User.findOne({ where: ['asdasdasd'] }).catch(function(err) {
expect(err).to.exist;
expect(err.message).to.exist;
});
});
it('gets triggered if everything was ok', function() {
return this.User.count().then(function(result) {
expect(result).to.exist;
});
});
});
describe('save', function() {
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
var User = sequelize.define('User', { username: Support.Sequelize.STRING });
return User.sync({ force: true }).then(function() {
return sequelize.transaction().then(function(t) {
return User.build({ username: 'foo' }).save({ transaction: t }).then(function() {
return User.count().then(function(count1) {
return User.count({ transaction: t }).then(function(count2) {
expect(count1).to.equal(0);
expect(count2).to.equal(1);
return t.rollback();
});
});
});
});
});
});
});
}
it('only updates fields in passed array', function() {
var self = this
, date = new Date(1990, 1, 1);
return this.User.create({
username: 'foo',
touchedAt: new Date()
}).then(function(user) {
user.username = 'fizz';
user.touchedAt = date;
return user.save({fields: ['username']}).then(function() {
// re-select user
return self.User.findById(user.id).then(function(user2) {
// name should have changed
expect(user2.username).to.equal('fizz');
// bio should be unchanged
expect(user2.birthDate).not.to.equal(date);
});
});
});
});
it('should work on a model with an attribute named length', function () {
var Box = this.sequelize.define('box', {
length : DataTypes.INTEGER,
width : DataTypes.INTEGER,
height : DataTypes.INTEGER
});
return Box.sync({force: true}).then(function () {
return Box.create({
length: 1,
width: 2,
height: 3
}).then(function (box) {
return box.update({
length: 4,
width: 5,
height: 6
});
}).then(function () {
return Box.findOne({}).then(function (box) {
expect(box.get('length')).to.equal(4);
expect(box.get('width')).to.equal(5);
expect(box.get('height')).to.equal(6);
});
});
});
});
it('only validates fields in passed array', function() {
return this.User.build({
validateTest: 'cake', // invalid, but not saved
validateCustom: '1'
}).save({
fields: ['validateCustom']
});
});
describe('hooks', function () {
it('should update attributes added in hooks when default fields are used', function () {
var User = this.sequelize.define('User' + config.rand(), {
name: DataTypes.STRING,
bio: DataTypes.TEXT,
email: DataTypes.STRING
});
User.beforeUpdate(function(instance) {
instance.set('email', 'B');
});
return User.sync({force: true}).then(function() {
return User.create({
name: 'A',
bio: 'A',
email: 'A'
}).then(function (user) {
return user.set({
name: 'B',
bio: 'B'
}).save();
}).then(function () {
return User.findOne({});
}).then(function (user) {
expect(user.get('name')).to.equal('B');
expect(user.get('bio')).to.equal('B');
expect(user.get('email')).to.equal('B');
});
});
});
it('should update attributes changed in hooks when default fields are used', function () {
var User = this.sequelize.define('User' + config.rand(), {
name: DataTypes.STRING,
bio: DataTypes.TEXT,
email: DataTypes.STRING
});
User.beforeUpdate(function(instance) {
instance.set('email', 'C');
});
return User.sync({force: true}).then(function() {
return User.create({
name: 'A',
bio: 'A',
email: 'A'
}).then(function (user) {
return user.set({
name: 'B',
bio: 'B',
email: 'B'
}).save();
}).then(function () {
return User.findOne({});
}).then(function (user) {
expect(user.get('name')).to.equal('B');
expect(user.get('bio')).to.equal('B');
expect(user.get('email')).to.equal('C');
});
});
});
it('should validate attributes added in hooks when default fields are used', function () {
var User = this.sequelize.define('User' + config.rand(), {
name: DataTypes.STRING,
bio: DataTypes.TEXT,
email: {
type: DataTypes.STRING,
validate: {
isEmail: true
}
}
});
User.beforeUpdate(function(instance) {
instance.set('email', 'B');
});
return User.sync({force: true}).then(function () {
return User.create({
name: 'A',
bio: 'A',
email: 'valid.email@gmail.com'
}).then(function (user) {
return expect(user.set({
name: 'B'
}).save()).to.be.rejectedWith(Sequelize.ValidationError);
}).then(function () {
return User.findOne({}).then(function (user) {
expect(user.get('email')).to.equal('valid.email@gmail.com');
});
});
});
});
it('should validate attributes changed in hooks when default fields are used', function () {
var User = this.sequelize.define('User' + config.rand(), {
name: DataTypes.STRING,
bio: DataTypes.TEXT,
email: {
type: DataTypes.STRING,
validate: {
isEmail: true
}
}
});
User.beforeUpdate(function(instance) {
instance.set('email', 'B');
});
return User.sync({force: true}).then(function () {
return User.create({
name: 'A',
bio: 'A',
email: 'valid.email@gmail.com'
}).then(function (user) {
return expect(user.set({
name: 'B',
email: 'still.valid.email@gmail.com'
}).save()).to.be.rejectedWith(Sequelize.ValidationError);
}).then(function () {
return User.findOne({}).then(function (user) {
expect(user.get('email')).to.equal('valid.email@gmail.com');
});
});
});
});
});
it('stores an entry in the database', function() {
var username = 'user'
, User = this.User
, user = this.User.build({
username: username,
touchedAt: new Date(1984, 8, 23)
});
return User.findAll().then(function(users) {
expect(users).to.have.length(0);
return user.save().then(function() {
return User.findAll().then(function(users) {
expect(users).to.have.length(1);
expect(users[0].username).to.equal(username);
expect(users[0].touchedAt).to.be.instanceof(Date);
expect(users[0].touchedAt).to.equalDate(new Date(1984, 8, 23));
});
});
});
});
it('handles an entry with primaryKey of zero', function() {
var username = 'user'
, newUsername = 'newUser'
, User2 = this.sequelize.define('User2',
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: false,
primaryKey: true
},
username: { type: DataTypes.STRING }
});
return User2.sync().then(function () {
return User2.create({id: 0, username: username}).then(function (user){
expect(user).to.be.ok;
expect(user.id).to.equal(0);
expect(user.username).to.equal(username);
return User2.findById(0).then(function (user) {
expect(user).to.be.ok;
expect(user.id).to.equal(0);
expect(user.username).to.equal(username);
return user.updateAttributes({username: newUsername}).then(function (user) {
expect(user).to.be.ok;
expect(user.id).to.equal(0);
expect(user.username).to.equal(newUsername);
});
});
});
});
});
it('updates the timestamps', function() {
var now = Date.now()
, user = null
, User = this.User;
// timeout is needed, in order to check the update of the timestamp
return this.sequelize.Promise.delay(1000).then(function() {
user = User.build({ username: 'user' });
return user.save().then(function() {
expect(now).to.be.below(user.updatedAt.getTime());
});
});
});
it('does not update timestamps when passing silent=true', function() {
return this.User.create({ username: 'user' }).then(function(user) {
var updatedAt = user.updatedAt;
return this.sequelize.Promise.delay(2000).then(function() {
return user.update({
username: 'userman'
}, {
silent: true
}).then(function(user1) {
expect(user1.updatedAt).to.equalDate(updatedAt);
});
});
});
});
describe('when nothing changed', function() {
beforeEach(function () {
this.clock = sinon.useFakeTimers();
});
afterEach(function () {
this.clock.restore();
});
it('does not update timestamps', function() {
var self = this;
return self.User.create({ username: 'John' }).then(function() {
return self.User.findOne({ username: 'John' }).then(function(user) {
var updatedAt = user.updatedAt;
self.clock.tick(2000);
return user.save().then(function(newlySavedUser) {
expect(newlySavedUser.updatedAt).to.equalTime(updatedAt);
});
});
});
});
});
it('updates with function and column value', function() {
var self = this;
return this.User.create({
aNumber: 42
}).then(function(user) {
user.bNumber = self.sequelize.col('aNumber');
user.username = self.sequelize.fn('upper', 'sequelize');
return user.save().then(function() {
return self.User.findById(user.id).then(function(user2) {
expect(user2.username).to.equal('SEQUELIZE');
expect(user2.bNumber).to.equal(42);
});
});
});
});
describe('without timestamps option', function() {
it("doesn't update the updatedAt column", function() {
var User2 = this.sequelize.define('User2', {
username: DataTypes.STRING,
updatedAt: DataTypes.DATE
}, { timestamps: false });
return User2.sync().then(function() {
return User2.create({ username: 'john doe' }).then(function(johnDoe) {
// sqlite and mysql return undefined, whereas postgres returns null
expect([undefined, null].indexOf(johnDoe.updatedAt)).not.to.be.equal(-1);
});
});
});
});
describe('with custom timestamp options', function() {
var now = Date.now();
it('updates the createdAt column if updatedAt is disabled', function() {
var User2 = this.sequelize.define('User2', {
username: DataTypes.STRING
}, { updatedAt: false });
return User2.sync().then(function() {
return User2.create({ username: 'john doe' }).then(function(johnDoe) {
expect(johnDoe.updatedAt).to.be.undefined;
expect(now).to.be.below(johnDoe.createdAt.getTime());
});
});
});
it('updates the updatedAt column if createdAt is disabled', function() {
var User2 = this.sequelize.define('User2', {
username: DataTypes.STRING
}, { createdAt: false });
return User2.sync().then(function() {
return User2.create({ username: 'john doe' }).then(function(johnDoe) {
expect(johnDoe.createdAt).to.be.undefined;
expect(now).to.be.below(johnDoe.updatedAt.getTime());
});
});
});
});
it('should fail a validation upon creating', function() {
return this.User.create({aNumber: 0, validateTest: 'hello'}).catch(function(err) {
expect(err).to.exist;
expect(err).to.be.instanceof(Object);
expect(err.get('validateTest')).to.be.instanceof(Array);
expect(err.get('validateTest')[0]).to.exist;
expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed');
});
});
it('should fail a validation upon creating with hooks false', function() {
return this.User.create({aNumber: 0, validateTest: 'hello'}, {hooks: false}).catch(function(err) {
expect(err).to.exist;
expect(err).to.be.instanceof(Object);
expect(err.get('validateTest')).to.be.instanceof(Array);
expect(err.get('validateTest')[0]).to.exist;
expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed');
});
});
it('should fail a validation upon building', function() {
return this.User.build({aNumber: 0, validateCustom: 'aaaaaaaaaaaaaaaaaaaaaaaaaa'}).save()
.catch(function(err) {
expect(err).to.exist;
expect(err).to.be.instanceof(Object);
expect(err.get('validateCustom')).to.exist;
expect(err.get('validateCustom')).to.be.instanceof(Array);
expect(err.get('validateCustom')[0]).to.exist;
expect(err.get('validateCustom')[0].message).to.equal('Length failed.');
});
});
it('should fail a validation when updating', function() {
return this.User.create({aNumber: 0}).then(function(user) {
return user.updateAttributes({validateTest: 'hello'}).catch(function(err) {
expect(err).to.exist;
expect(err).to.be.instanceof(Object);
expect(err.get('validateTest')).to.exist;
expect(err.get('validateTest')).to.be.instanceof(Array);
expect(err.get('validateTest')[0]).to.exist;
expect(err.get('validateTest')[0].message).to.equal('Validation isInt failed');
});
});
});
it('takes zero into account', function() {
return this.User.build({ aNumber: 0 }).save({
fields: ['aNumber']
}).then(function(user) {
expect(user.aNumber).to.equal(0);
});
});
it('saves a record with no primary key', function() {
var HistoryLog = this.sequelize.define('HistoryLog', {
someText: { type: DataTypes.STRING },
aNumber: { type: DataTypes.INTEGER },
aRandomId: { type: DataTypes.INTEGER }
});
return HistoryLog.sync().then(function() {
return HistoryLog.create({ someText: 'Some random text', aNumber: 3, aRandomId: 5 }).then(function(log) {
return log.updateAttributes({ aNumber: 5 }).then(function(newLog) {
expect(newLog.aNumber).to.equal(5);
});
});
});
});
describe('eagerly loaded objects', function() {
beforeEach(function() {
var self = this;
this.UserEager = this.sequelize.define('UserEagerLoadingSaves', {
username: DataTypes.STRING,
age: DataTypes.INTEGER
}, { timestamps: false });
this.ProjectEager = this.sequelize.define('ProjectEagerLoadingSaves', {
title: DataTypes.STRING,
overdue_days: DataTypes.INTEGER
}, { timestamps: false });
this.UserEager.hasMany(this.ProjectEager, { as: 'Projects', foreignKey: 'PoobahId' });
this.ProjectEager.belongsTo(this.UserEager, { as: 'Poobah', foreignKey: 'PoobahId' });
return self.UserEager.sync({force: true}).then(function() {
return self.ProjectEager.sync({force: true});
});
});
it('saves one object that has a collection of eagerly loaded objects', function() {
var self = this;
return this.UserEager.create({ username: 'joe', age: 1 }).then(function(user) {
return self.ProjectEager.create({ title: 'project-joe1', overdue_days: 0 }).then(function(project1) {
return self.ProjectEager.create({ title: 'project-joe2', overdue_days: 0 }).then(function(project2) {
return user.setProjects([project1, project2]).then(function() {
return self.UserEager.findOne({where: {age: 1}, include: [{model: self.ProjectEager, as: 'Projects'}]}).then(function(user) {
expect(user.username).to.equal('joe');
expect(user.age).to.equal(1);
expect(user.Projects).to.exist;
expect(user.Projects.length).to.equal(2);
user.age = user.age + 1; // happy birthday joe
return user.save().then(function(user) {
expect(user.username).to.equal('joe');
expect(user.age).to.equal(2);
expect(user.Projects).to.exist;
expect(user.Projects.length).to.equal(2);
});
});
});
});
});
});
});
it('saves many objects that each a have collection of eagerly loaded objects', function() {
var self = this;
return this.UserEager.create({ username: 'bart', age: 20 }).then(function(bart) {
return self.UserEager.create({ username: 'lisa', age: 20 }).then(function(lisa) {
return self.ProjectEager.create({ title: 'detention1', overdue_days: 0 }).then(function(detention1) {
return self.ProjectEager.create({ title: 'detention2', overdue_days: 0 }).then(function(detention2) {
return self.ProjectEager.create({ title: 'exam1', overdue_days: 0 }).then(function(exam1) {
return self.ProjectEager.create({ title: 'exam2', overdue_days: 0 }).then(function(exam2) {
return bart.setProjects([detention1, detention2]).then(function() {
return lisa.setProjects([exam1, exam2]).then(function() {
return self.UserEager.findAll({where: {age: 20}, order: 'username ASC', include: [{model: self.ProjectEager, as: 'Projects'}]}).then(function(simpsons) {
var _bart, _lisa;
expect(simpsons.length).to.equal(2);
_bart = simpsons[0];
_lisa = simpsons[1];
expect(_bart.Projects).to.exist;
expect(_lisa.Projects).to.exist;
expect(_bart.Projects.length).to.equal(2);
expect(_lisa.Projects.length).to.equal(2);
_bart.age = _bart.age + 1; // happy birthday bart - off to Moe's
return _bart.save().then(function(savedbart) {
expect(savedbart.username).to.equal('bart');
expect(savedbart.age).to.equal(21);
_lisa.username = 'lsimpson';
return _lisa.save().then(function(savedlisa) {
expect(savedlisa.username).to.equal('lsimpson');
expect(savedlisa.age).to.equal(20);
});
});
});
});
});
});
});
});
});
});
});
});
it('saves many objects that each has one eagerly loaded object (to which they belong)', function() {
var self = this;
return this.UserEager.create({ username: 'poobah', age: 18 }).then(function(user) {
return self.ProjectEager.create({ title: 'homework', overdue_days: 10 }).then(function(homework) {
return self.ProjectEager.create({ title: 'party', overdue_days: 2 }).then(function(party) {
return user.setProjects([homework, party]).then(function() {
return self.ProjectEager.findAll({include: [{model: self.UserEager, as: 'Poobah'}]}).then(function(projects) {
expect(projects.length).to.equal(2);
expect(projects[0].Poobah).to.exist;
expect(projects[1].Poobah).to.exist;
expect(projects[0].Poobah.username).to.equal('poobah');
expect(projects[1].Poobah.username).to.equal('poobah');
projects[0].title = 'partymore';
projects[1].title = 'partymore';
projects[0].overdue_days = 0;
projects[1].overdue_days = 0;
return projects[0].save().then(function() {
return projects[1].save().then(function() {
return self.ProjectEager.findAll({where: {title: 'partymore', overdue_days: 0}, include: [{model: self.UserEager, as: 'Poobah'}]}).then(function(savedprojects) {
expect(savedprojects.length).to.equal(2);
expect(savedprojects[0].Poobah).to.exist;
expect(savedprojects[1].Poobah).to.exist;
expect(savedprojects[0].Poobah.username).to.equal('poobah');
expect(savedprojects[1].Poobah.username).to.equal('poobah');
});
});
});
});
});
});
});
});
});
});
});
describe('many to many relations', function() {
var udo;
beforeEach(function() {
var self = this;
this.User = this.sequelize.define('UserWithUsernameAndAgeAndIsAdmin', {
username: DataTypes.STRING,
age: DataTypes.INTEGER,
isAdmin: DataTypes.BOOLEAN
}, {timestamps: false});
this.Project = this.sequelize.define('NiceProject',
{ title: DataTypes.STRING }, {timestamps: false});
this.Project.hasMany(this.User);
this.User.hasMany(this.Project);
return this.User.sync({ force: true }).then(function() {
return self.Project.sync({ force: true }).then(function() {
return self.User.create({ username: 'fnord', age: 1, isAdmin: true })
.then(function(user) {
udo = user;
});
});
});
});
it.skip('Should assign a property to the instance', function() {
// @thanpolas rethink this test, it doesn't make sense, a relation has
// to be created first in the beforeEach().
return this.User.findOne({id: udo.id})
.then(function(user) {
user.NiceProjectId = 1;
expect(user.NiceProjectId).to.equal(1);
});
});
});
describe('toJSON', function() {
beforeEach(function() {
var self = this;
this.User = this.sequelize.define('UserWithUsernameAndAgeAndIsAdmin', {
username: DataTypes.STRING,
age: DataTypes.INTEGER,
isAdmin: DataTypes.BOOLEAN
}, { timestamps: false });
this.Project = this.sequelize.define('NiceProject', { title: DataTypes.STRING }, { timestamps: false });
this.User.hasMany(this.Project, { as: 'Projects', foreignKey: 'lovelyUserId' });
this.Project.belongsTo(this.User, { as: 'LovelyUser', foreignKey: 'lovelyUserId' });
return this.User.sync({ force: true }).then(function() {
return self.Project.sync({ force: true });
});
});
it("dont return instance that isn't defined", function() {
var self = this;
return self.Project.create({ lovelyUserId: null })
.then(function(project) {
return self.Project.findOne({
where: {
id: project.id
},
include: [
{ model: self.User, as: 'LovelyUser' }
]
});
})
.then(function(project) {
var json = project.toJSON();
expect(json.LovelyUser).to.be.equal(null);
});
});
it("dont return instances that aren't defined", function() {
var self = this;
return self.User.create({ username: 'cuss' })
.then(function(user) {
return self.User.findOne({
where: {
id: user.id
},
include: [
{ model: self.Project, as: 'Projects' }
]
});
})
.then(function(user) {
expect(user.Projects).to.be.instanceof(Array);
expect(user.Projects).to.be.length(0);
});
});
it('returns an object containing all values', function() {
var user = this.User.build({ username: 'test.user', age: 99, isAdmin: true });
expect(user.toJSON()).to.deep.equal({ username: 'test.user', age: 99, isAdmin: true, id: null });
});
it('returns a response that can be stringified', function() {
var user = this.User.build({ username: 'test.user', age: 99, isAdmin: true });
expect(JSON.stringify(user)).to.deep.equal('{"id":null,"username":"test.user","age":99,"isAdmin":true}');
});
it('returns a response that can be stringified and then parsed', function() {
var user = this.User.build({ username: 'test.user', age: 99, isAdmin: true });
expect(JSON.parse(JSON.stringify(user))).to.deep.equal({ username: 'test.user', age: 99, isAdmin: true, id: null });
});
it('includes the eagerly loaded associations', function() {
var self = this;
return this.User.create({ username: 'fnord', age: 1, isAdmin: true }).then(function(user) {
return self.Project.create({ title: 'fnord' }).then(function(project) {
return user.setProjects([project]).then(function() {
return self.User.findAll({include: [{ model: self.Project, as: 'Projects' }]}).then(function(users) {
var _user = users[0];
expect(_user.Projects).to.exist;
expect(JSON.parse(JSON.stringify(_user)).Projects).to.exist;
return self.Project.findAll({include: [{ model: self.User, as: 'LovelyUser' }]}).then(function(projects) {
var _project = projects[0];
expect(_project.LovelyUser).to.exist;
expect(JSON.parse(JSON.stringify(_project)).LovelyUser).to.exist;
});
});
});
});
});
});
});
describe('findAll', function() {
beforeEach(function() {
this.ParanoidUser = this.sequelize.define('ParanoidUser', {
username: { type: DataTypes.STRING }
}, { paranoid: true });
this.ParanoidUser.hasOne(this.ParanoidUser);
return this.ParanoidUser.sync({ force: true });
});
it('sql should have paranoid condition', function() {
var self = this;
return self.ParanoidUser.create({ username: 'cuss' })
.then(function() {
return self.ParanoidUser.findAll();
})
.then(function(users) {
expect(users).to.have.length(1);
return users[0].destroy();
})
.then(function() {
return self.ParanoidUser.findAll();
})
.then(function(users) {
expect(users).to.have.length(0);
});
});
it('sequelize.and as where should include paranoid condition', function() {
var self = this;
return self.ParanoidUser.create({ username: 'cuss' })
.then(function() {
return self.ParanoidUser.findAll({
where: self.sequelize.and({
username: 'cuss'
})
});
})
.then(function(users) {
expect(users).to.have.length(1);
return users[0].destroy();
})
.then(function() {
return self.ParanoidUser.findAll({
where: self.sequelize.and({
username: 'cuss'
})
});
})
.then(function(users) {
expect(users).to.have.length(0);
});
});
it('sequelize.or as where should include paranoid condition', function() {
var self = this;
return self.ParanoidUser.create({ username: 'cuss' })
.then(function() {
return self.ParanoidUser.findAll({
where: self.sequelize.or({
username: 'cuss'
})
});
})
.then(function(users) {
expect(users).to.have.length(1);
return users[0].destroy();
})
.then(function() {
return self.ParanoidUser.findAll({
where: self.sequelize.or({
username: 'cuss'
})
});
})
.then(function(users) {
expect(users).to.have.length(0);
});
});
it('escapes a single single quotes properly in where clauses', function() {
var self = this;
return this.User
.create({ username: "user'name" })
.then(function() {
return self.User.findAll({
where: { username: "user'name" }
}).then(function(users) {
expect(users.length).to.equal(1);
expect(users[0].username).to.equal("user'name");
});
});
});
it('escapes two single quotes properly in where clauses', function() {
var self = this;
return this.User
.create({ username: "user''name" })
.then(function() {
return self.User.findAll({
where: { username: "user''name" }
}).then(function(users) {
expect(users.length).to.equal(1);
expect(users[0].username).to.equal("user''name");
});
});
});
it('returns the timestamps if no attributes have been specified', function() {
var self = this;
return this.User.create({ username: 'fnord' }).then(function() {
return self.User.findAll().then(function(users) {
expect(users[0].createdAt).to.exist;
});
});
});
it('does not return the timestamps if the username attribute has been specified', function() {
var self = this;
return this.User.create({ username: 'fnord' }).then(function() {
return self.User.findAll({ attributes: ['username'] }).then(function(users) {
expect(users[0].createdAt).not.to.exist;
expect(users[0].username).to.exist;
});
});
});
it('creates the deletedAt property, when defining paranoid as true', function() {
var self = this;
return this.ParanoidUser.create({ username: 'fnord' }).then(function() {
return self.ParanoidUser.findAll().then(function(users) {
expect(users[0].deletedAt).to.be.null;
});
});
});
it('destroys a record with a primary key of something other than id', function() {
var UserDestroy = this.sequelize.define('UserDestroy', {
newId: {
type: DataTypes.STRING,
primaryKey: true
},
email: DataTypes.STRING
});
return UserDestroy.sync().then(function() {
return UserDestroy.create({newId: '123ABC', email: 'hello'}).then(function() {
return UserDestroy.findOne({where: {email: 'hello'}}).then(function(user) {
return user.destroy();
});
});
});
});
it('sets deletedAt property to a specific date when deleting an instance', function() {
var self = this;
return this.ParanoidUser.create({ username: 'fnord' }).then(function() {
return self.ParanoidUser.findAll().then(function(users) {
return users[0].destroy().then(function(user) {
expect(user.deletedAt.getMonth).to.exist;
});
});
});
});
it('keeps the deletedAt-attribute with value null, when running updateAttributes', function() {
var self = this;
return this.ParanoidUser.create({ username: 'fnord' }).then(function() {
return self.ParanoidUser.findAll().then(function(users) {
return users[0].updateAttributes({username: 'newFnord'}).then(function(user) {
expect(user.deletedAt).not.to.exist;
});
});
});
});
it('keeps the deletedAt-attribute with value null, when updating associations', function() {
var self = this;
return this.ParanoidUser.create({ username: 'fnord' }).then(function() {
return self.ParanoidUser.findAll().then(function(users) {
return self.ParanoidUser.create({ username: 'linkedFnord' }).then(function(linkedUser) {
return users[0].setParanoidUser(linkedUser).then(function(user) {
expect(user.deletedAt).not.to.exist;
});
});
});
});
});
it('can reuse query option objects', function() {
var self = this;
return this.User.create({ username: 'fnord' }).then(function() {
var query = { where: { username: 'fnord' }};
return self.User.findAll(query).then(function(users) {
expect(users[0].username).to.equal('fnord');
return self.User.findAll(query).then(function(users) {
expect(users[0].username).to.equal('fnord');
});
});
});
});
});
describe('find', function() {
it('can reuse query option objects', function() {
var self = this;
return this.User.create({ username: 'fnord' }).then(function() {
var query = { where: { username: 'fnord' }};
return self.User.findOne(query).then(function(user) {
expect(user.username).to.equal('fnord');
return self.User.findOne(query).then(function(user) {
expect(user.username).to.equal('fnord');
});
});
});
});
it('returns null for null, undefined, and unset boolean values', function() {
var Setting = this.sequelize.define('SettingHelper', {
setting_key: DataTypes.STRING,
bool_value: { type: DataTypes.BOOLEAN, allowNull: true },
bool_value2: { type: DataTypes.BOOLEAN, allowNull: true },
bool_value3: { type: DataTypes.BOOLEAN, allowNull: true }
}, { timestamps: false, logging: false });
return Setting.sync({ force: true }).then(function() {
return Setting.create({ setting_key: 'test', bool_value: null, bool_value2: undefined }).then(function() {
return Setting.findOne({ where: { setting_key: 'test' } }).then(function(setting) {
expect(setting.bool_value).to.equal(null);
expect(setting.bool_value2).to.equal(null);
expect(setting.bool_value3).to.equal(null);
});
});
});
});
});
describe('equals', function() {
it('can compare records with Date field', function() {
var self = this;
return this.User.create({ username: 'fnord' }).then(function(user1) {
return self.User.findOne({ where: { username: 'fnord' }}).then(function(user2) {
expect(user1.equals(user2)).to.be.true;
});
});
});
});
describe('values', function() {
it('returns all values', function() {
var User = this.sequelize.define('UserHelper', {
username: DataTypes.STRING
}, { timestamps: false, logging: false });
return User.sync().then(function() {
var user = User.build({ username: 'foo' });
expect(user.get({ plain: true })).to.deep.equal({ username: 'foo', id: null });
});
});
});
describe('destroy', function() {
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
var User = sequelize.define('User', { username: Support.Sequelize.STRING });
return User.sync({ force: true }).then(function() {
return User.create({ username: 'foo' }).then(function(user) {
return sequelize.transaction().then(function(t) {
return user.destroy({ transaction: t }).then(function() {
return User.count().then(function(count1) {
return User.count({ transaction: t }).then(function(count2) {
expect(count1).to.equal(1);
expect(count2).to.equal(0);
return t.rollback();
});
});
});
});
});
});
});
});
}
it('deletes a record from the database if dao is not paranoid', function() {
var UserDestroy = this.sequelize.define('UserDestroy', {
name: Support.Sequelize.STRING,
bio: Support.Sequelize.TEXT
});
return UserDestroy.sync({ force: true }).then(function() {
return UserDestroy.create({name: 'hallo', bio: 'welt'}).then(function(u) {
return UserDestroy.findAll().then(function(users) {
expect(users.length).to.equal(1);
return u.destroy().then(function() {
return UserDestroy.findAll().then(function(users) {
expect(users.length).to.equal(0);
});
});
});
});
});
});
it('allows sql logging of delete statements', function() {
var UserDelete = this.sequelize.define('UserDelete', {
name: Support.Sequelize.STRING,
bio: Support.Sequelize.TEXT
});
return UserDelete.sync({ force: true }).then(function() {
return UserDelete.create({name: 'hallo', bio: 'welt'}).then(function(u) {
return UserDelete.findAll().then(function(users) {
expect(users.length).to.equal(1);
return u.destroy({
logging: function (sql) {
expect(sql).to.exist;
expect(sql.toUpperCase().indexOf('DELETE')).to.be.above(-1);
}
});
});
});
});
});
it('delete a record of multiple primary keys table', function() {
var MultiPrimary = this.sequelize.define('MultiPrimary', {
bilibili: {
type: Support.Sequelize.CHAR(2),
primaryKey: true
},
guruguru: {
type: Support.Sequelize.CHAR(2),
primaryKey: true
}
});
return MultiPrimary.sync({ force: true }).then(function() {
return MultiPrimary.create({ bilibili: 'bl', guruguru: 'gu' }).then(function() {
return MultiPrimary.create({ bilibili: 'bl', guruguru: 'ru' }).then(function(m2) {
return MultiPrimary.findAll().then(function(ms) {
expect(ms.length).to.equal(2);
return m2.destroy({
logging: function(sql) {
expect(sql).to.exist;
expect(sql.toUpperCase().indexOf('DELETE')).to.be.above(-1);
expect(sql.indexOf('ru')).to.be.above(-1);
expect(sql.indexOf('bl')).to.be.above(-1);
}
}).then(function() {
return MultiPrimary.findAll().then(function(ms) {
expect(ms.length).to.equal(1);
expect(ms[0].bilibili).to.equal('bl');
expect(ms[0].guruguru).to.equal('gu');
});
});
});
});
});
});
});
});
describe('restore', function() {
it('returns an error if the model is not paranoid', function() {
return this.User.create({username: 'Peter', secretValue: '42'}).then(function(user) {
expect(function() {user.restore();}).to.throw(Error, 'Model is not paranoid');
});
});
it('restores a previously deleted model', function() {
var self = this
, ParanoidUser = self.sequelize.define('ParanoidUser', {
username: DataTypes.STRING,
secretValue: DataTypes.STRING,
data: DataTypes.STRING,
intVal: { type: DataTypes.INTEGER, defaultValue: 1}
}, {
paranoid: true
})
, data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '43' },
{ username: 'Bob', secretValue: '44' }];
return ParanoidUser.sync({ force: true }).then(function() {
return ParanoidUser.bulkCreate(data);
}).then(function() {
return ParanoidUser.findOne({where: {secretValue: '42'}});
}).then(function(user) {
return user.destroy().then(function() {
return user.restore();
});
}).then(function() {
return ParanoidUser.findOne({where: {secretValue: '42'}});
}).then(function(user) {
expect(user).to.be.ok;
expect(user.username).to.equal('Peter');
});
});
});
});
|
// Heatmap Constructor
var Heatmap = (function HeatmapClosure() {
var Coordinator = (function CoordinatorClosure() {
function Coordinator() {
this.cStore = {};
};
Coordinator.prototype = {
on: function(evtName, callback, scope) {
var cStore = this.cStore;
if (!cStore[evtName]) {
cStore[evtName] = [];
}
cStore[evtName].push((function(data) {
return callback.call(scope, data);
}));
},
emit: function(evtName, data) {
var cStore = this.cStore;
if (cStore[evtName]) {
var len = cStore[evtName].length;
for (var i=0; i<len; i++) {
var callback = cStore[evtName][i];
callback(data);
}
}
}
};
return Coordinator;
})();
var _connect = function(scope) {
var renderer = scope._renderer;
var coordinator = scope._coordinator;
var store = scope._store;
coordinator.on('renderpartial', renderer.renderPartial, renderer);
coordinator.on('renderall', renderer.renderAll, renderer);
coordinator.on('extremachange', function(data) {
scope._config.onExtremaChange &&
scope._config.onExtremaChange({
min: data.min,
max: data.max,
gradient: scope._config['gradient'] || scope._config['defaultGradient']
});
});
store.setCoordinator(coordinator);
};
function Heatmap() {
var config = this._config = Util.merge(HeatmapConfig, arguments[0] || {});
this._coordinator = new Coordinator();
if (config['plugin']) {
var pluginToLoad = config['plugin'];
if (!HeatmapConfig.plugins[pluginToLoad]) {
throw new Error('Plugin \''+ pluginToLoad + '\' not found. Maybe it was not registered.');
} else {
var plugin = HeatmapConfig.plugins[pluginToLoad];
// set plugin renderer and store
this._renderer = new plugin.renderer(config);
this._store = new plugin.store(config);
}
} else {
this._renderer = new Renderer(config);
this._store = new Store(config);
}
_connect(this);
};
// @TODO:
// add API documentation
Heatmap.prototype = {
addData: function() {
this._store.addData.apply(this._store, arguments);
return this;
},
removeData: function() {
this._store.removeData && this._store.removeData.apply(this._store, arguments);
return this;
},
setData: function() {
this._store.setData.apply(this._store, arguments);
return this;
},
setDataMax: function() {
this._store.setDataMax.apply(this._store, arguments);
return this;
},
setDataMin: function() {
this._store.setDataMin.apply(this._store, arguments);
return this;
},
configure: function(config) {
this._config = Util.merge(this._config, config);
this._renderer.updateConfig(this._config);
this._coordinator.emit('renderall', this._store._getInternalData());
return this;
},
repaint: function() {
this._coordinator.emit('renderall', this._store._getInternalData());
return this;
},
getData: function() {
return this._store.getData();
},
getDataURL: function() {
return this._renderer.getDataURL();
},
getValueAt: function(point) {
if (this._store.getValueAt) {
return this._store.getValueAt(point);
} else if (this._renderer.getValueAt) {
return this._renderer.getValueAt(point);
} else {
return null;
}
}
};
return Heatmap;
})();
// core
var heatmapFactory = {
create: function(config) {
return new Heatmap(config);
},
register: function(pluginKey, plugin) {
HeatmapConfig.plugins[pluginKey] = plugin;
}
};
return heatmapFactory;
|
tinyMCE.addI18n('fr.style_dlg',{
title:"\u00C9diter la feuille de style CSS",
apply:"Appliquer",
text_tab:"Texte",
background_tab:"Fond",
block_tab:"Bloc",
box_tab:"Bo\u00EEte",
border_tab:"Bordure",
list_tab:"Liste",
positioning_tab:"Positionement",
text_props:"Texte",
text_font:"Police",
text_size:"Taille",
text_weight:"Poids",
text_style:"Style",
text_variant:"Variante",
text_lineheight:"Hauteur de ligne",
text_case:"Casse",
text_color:"Couleur",
text_decoration:"D\u00E9coration",
text_overline:"surlign\u00E9",
text_underline:"soulign\u00E9",
text_striketrough:"barr\u00E9",
text_blink:"clignotant",
text_none:"aucun",
background_color:"Couleur de fond",
background_image:"Image de fond",
background_repeat:"R\u00E9p\u00E9ter",
background_attachment:"Attachement",
background_hpos:"Position horizontale",
background_vpos:"Position verticale",
block_wordspacing:"Espacement des mots ",
block_letterspacing:"Espacement des lettres",
block_vertical_alignment:"Alignement vertical",
block_text_align:"Alignement du texte",
block_text_indent:"Indentation du texte",
block_whitespace:"Fin de ligne",
block_display:"Affichage",
box_width:"Largeur",
box_height:"Hauteur",
box_float:"Flottant",
box_clear:"Vider",
padding:"Espacement",
same:"Identique pour tous",
top:"Haut",
right:"Droit",
bottom:"Bas",
left:"Gauche",
margin:"Marge",
style:"Style",
width:"Largeur",
height:"Hauter",
color:"Couleur",
list_type:"Type",
bullet_image:"Image de puce",
position:"Position",
positioning_type:"Type",
visibility:"Visibilit\u00E9",
zindex:"Z-index",
overflow:"D\u00E9bordement",
placement:"Placement",
clip:"Clip"
}); |
!function(e,_){"object"==typeof exports&&"undefined"!=typeof module?module.exports=_(require("dayjs")):"function"==typeof define&&define.amd?define(["dayjs"],_):e.dayjs_locale_tzl=_(e.dayjs)}(this,function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var _={name:"tzl",weekdays:"Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi".split("_"),months:"Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar".split("_"),weekStart:1,weekdaysShort:"Súl_Lún_Mai_Már_Xhú_Vié_Sát".split("_"),monthsShort:"Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec".split("_"),weekdaysMin:"Sú_Lú_Ma_Má_Xh_Vi_Sá".split("_"),ordinal:function(e){return e},formats:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD.MM.YYYY",LL:"D. MMMM [dallas] YYYY",LLL:"D. MMMM [dallas] YYYY HH.mm",LLLL:"dddd, [li] D. MMMM [dallas] YYYY HH.mm"}};return e.locale(_,null,!0),_}); |
/*
* Copyright (c) 2012 - 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.
*
*/
define(function (require, exports, module) {
"use strict";
var _ = require("thirdparty/lodash");
/**
* Convert between URL querystring and name/value pairs. Decodes and encodes URL parameters.
*/
function UrlParams() {
this._store = {};
}
/**
* Parse the window location by default. Optionally specify a URL to parse.
* @param {string} url
*/
UrlParams.prototype.parse = function (url) {
var queryString = "",
urlParams,
p,
self = this;
self._store = {};
if (!url) {
queryString = window.document.location.search.substring(1);
} else if (url.indexOf("?") !== -1) {
queryString = url.substring(url.indexOf("?") + 1);
}
queryString = queryString.trimRight();
if (queryString) {
urlParams = queryString.split("&");
urlParams.forEach(function (param) {
p = param.split("=");
p[1] = p[1] || "";
self._store[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
});
}
};
/**
* Store a name/value string pair
* @param {!string} name
* @param {!string} value
*/
UrlParams.prototype.put = function (name, value) {
this._store[name] = value;
};
/**
* Retrieve a value by name
* @param {!string} name
* @return {string}
*/
UrlParams.prototype.get = function (name) {
return this._store[name];
};
/**
* Remove a name/value string pair
* @param {!string} name
*/
UrlParams.prototype.remove = function (name) {
delete this._store[name];
};
/**
* Returns true if the parameter list is empty, else returns false.
* @return {boolean}
*/
UrlParams.prototype.isEmpty = function (name) {
return _.isEmpty(this._store);
};
/**
* Encode name/value pairs as URI components.
* @return {string}
*/
UrlParams.prototype.toString = function () {
var strs = [],
self = this;
_.forEach(self._store, function (value, key) {
strs.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
});
return strs.join("&");
};
// Define public API
exports.UrlParams = UrlParams;
});
|
/**
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
$(function(){
//
// Used for the modules listing
//
if ($("#position_filer").length != 0)
{
var panel_selection = $("#modules-position-selection-panel");
var panel_selection_single_selection = panel_selection.find("#modules-position-single-selection");
var panel_selection_multiple_selection = panel_selection.find("#modules-position-multiple-selection");
var panel_selection_original_y = panel_selection.offset().top;
var panel_selection_original_y_top_margin = 111;
panel_selection.css("position", "relative").hide();
$(window).on("scroll", function (event) {
var scroll_top = $(window).scrollTop();
panel_selection.css(
"top",
scroll_top < panel_selection_original_y_top_margin
? 0
: scroll_top - panel_selection_original_y + panel_selection_original_y_top_margin
);
});
var modules_list = $(".modules-position-checkbox");
modules_list.on("change", function () {
var checked_count = modules_list.filter(":checked").length;
panel_selection.hide();
panel_selection_single_selection.hide();
panel_selection_multiple_selection.hide();
if (checked_count == 1)
{
panel_selection.show();
panel_selection_single_selection.show();
}
else if (checked_count > 1)
{
panel_selection.show();
panel_selection_multiple_selection.show();
panel_selection_multiple_selection.find("#modules-position-selection-count").html(checked_count);
}
});
panel_selection.find("button").click(function () {
$("button[name='unhookform']").trigger("click");
});
var hooks_list = [];
$("section.hook_panel").find(".hook_name").each(function () {
var $this = $(this);
hooks_list.push({
'title': $this.html(),
'element': $this,
'container': $this.parents(".hook_panel")
});
});
var show_modules = $("#show_modules");
show_modules.select2();
show_modules.bind("change", function () {
modulesPositionFilterHooks();
});
var hook_position = $("#hook_position");
hook_position.bind("change", function () {
modulesPositionFilterHooks();
});
$('#hook_search').bind('input', function () {
modulesPositionFilterHooks();
});
function modulesPositionFilterHooks()
{
var id;
var hook_name = $('#hook_search').val();
var module_id = $("#show_modules").val();
var position = hook_position.prop('checked');
var regex = new RegExp("(" + hook_name + ")", "gi");
for (id = 0; id < hooks_list.length; id++)
{
hooks_list[id].container.toggle(hook_name == "" && module_id == "all");
hooks_list[id].element.html(hooks_list[id].title);
hooks_list[id].container.find('.module_list_item').removeClass('highlight');
}
if (hook_name != "" || module_id != "all")
{
var hooks_to_show_from_module = $();
var hooks_to_show_from_hook_name = $();
if (module_id != "all")
for (id = 0; id < hooks_list.length; id++)
{
var current_hooks = hooks_list[id].container.find(".module_position_" + module_id);
if (current_hooks.length > 0)
{
hooks_to_show_from_module = hooks_to_show_from_module.add(hooks_list[id].container);
current_hooks.addClass('highlight');
}
}
if (hook_name != "")
for (id = 0; id < hooks_list.length; id++)
{
var start = hooks_list[id].title.toLowerCase().search(hook_name.toLowerCase());
if (start != -1)
{
hooks_to_show_from_hook_name = hooks_to_show_from_hook_name.add(hooks_list[id].container);
hooks_list[id].element.html(hooks_list[id].title.replace(regex, '<span class="highlight">$1</span>'));
}
}
if (module_id == "all" && hook_name != "")
hooks_to_show_from_hook_name.show();
else if (hook_name == "" && module_id != "all")
hooks_to_show_from_module.show();
else
hooks_to_show_from_hook_name.filter(hooks_to_show_from_module).show();
}
if (!position)
for (id = 0; id < hooks_list.length; id++)
if (hooks_list[id].container.is('.hook_position'))
hooks_list[id].container.hide();
}
}
//
// Used for the anchor module page
//
$("#hook_module_form").find("select[name='id_module']").change(function(){
var $this = $(this);
var hook_select = $("select[name='id_hook']");
if ($this.val() != 0)
{
$this.find("[value='0']").remove();
hook_select.find("option").remove();
$.ajax({
type: 'POST',
url: 'index.php',
async: true,
dataType: 'json',
data: {
action: 'getPossibleHookingListForModule',
tab: 'AdminModulesPositions',
ajax: 1,
module_id: $this.val(),
token: token
},
success: function (jsonData) {
if (jsonData.hasError)
{
var errors = '';
for (var error in jsonData.errors)
if (error != 'indexOf')
errors += $('<div />').html(jsonData.errors[error]).text() + "\n";
}
else
{
for (var current_hook = 0; current_hook < jsonData.length; current_hook++)
hook_select.append('<option value="'+jsonData[current_hook].id_hook+'">'+jsonData[current_hook].name+'</option>');
hook_select.prop('disabled', false);
}
}
});
}
})
});
|
export default from './component.jsx';
|
'use strict';
exports.__esModule = true;
exports.default = tokenize;
var _tokenTypes = require('./tokenTypes');
var t = _interopRequireWildcard(_tokenTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var wordEnd = /[ \n\t\r\(\)\*:;!&'"\+\|~>,=$^\[\]\\]|\/(?=\*)/g;
function tokenize(input) {
var tokens = [];
var css = input.css.valueOf();
var _css = css,
length = _css.length;
var offset = -1;
var line = 1;
var start = 0;
var end = 0;
var code = void 0,
content = void 0,
endColumn = void 0,
endLine = void 0,
escaped = void 0,
escapePos = void 0,
last = void 0,
lines = void 0,
next = void 0,
nextLine = void 0,
nextOffset = void 0,
quote = void 0,
tokenType = void 0;
function unclosed(what, fix) {
if (input.safe) {
// fyi: this is never set to true.
css += fix;
next = css.length - 1;
} else {
throw input.error('Unclosed ' + what, line, start - offset, start);
}
}
while (start < length) {
code = css.charCodeAt(start);
if (code === t.newline) {
offset = start;
line += 1;
}
switch (code) {
case t.newline:
case t.space:
case t.tab:
case t.cr:
case t.feed:
next = start;
do {
next += 1;
code = css.charCodeAt(next);
if (code === t.newline) {
offset = next;
line += 1;
}
} while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
tokenType = t.space;
endLine = line;
endColumn = start - offset;
end = next;
break;
case t.plus:
case t.greaterThan:
case t.tilde:
case t.pipe:
next = start;
do {
next += 1;
code = css.charCodeAt(next);
} while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
tokenType = t.combinator;
endLine = line;
endColumn = start - offset;
end = next;
break;
// Consume these characters as single tokens.
case t.asterisk:
case t.ampersand:
case t.comma:
case t.equals:
case t.dollar:
case t.caret:
case t.openSquare:
case t.closeSquare:
case t.colon:
case t.semicolon:
case t.openParenthesis:
case t.closeParenthesis:
next = start;
tokenType = code;
endLine = line;
endColumn = start - offset;
end = next + 1;
break;
case t.singleQuote:
case t.doubleQuote:
quote = code === t.singleQuote ? "'" : '"';
next = start;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
unclosed('quote', quote);
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === t.backslash) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
tokenType = t.str;
endLine = line;
endColumn = start - offset;
end = next + 1;
break;
case t.backslash:
next = start;
escaped = true;
while (css.charCodeAt(next + 1) === t.backslash) {
next += 1;
escaped = !escaped;
}
code = css.charCodeAt(next + 1);
if (escaped && code !== t.slash && code !== t.space && code !== t.newline && code !== t.tab && code !== t.cr && code !== t.feed) {
next += 1;
}
tokenType = t.word;
endLine = line;
endColumn = next - offset;
end = next + 1;
break;
default:
if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
next = css.indexOf('*/', start + 2) + 1;
if (next === 0) {
unclosed('comment', '*/');
}
content = css.slice(start, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokenType = t.comment;
line = nextLine;
endLine = nextLine;
endColumn = next - nextOffset;
} else {
wordEnd.lastIndex = start + 1;
wordEnd.test(css);
if (wordEnd.lastIndex === 0) {
next = css.length - 1;
} else {
next = wordEnd.lastIndex - 2;
}
tokenType = t.word;
endLine = line;
endColumn = next - offset;
}
end = next + 1;
break;
}
// Ensure that the token structure remains consistent
tokens.push([tokenType, // [0] Token type
line, // [1] Starting line
start - offset, // [2] Starting column
endLine, // [3] Ending line
endColumn, // [4] Ending column
start, // [5] Start position / Source index
end] // [6] End position
);
// Reset offset for the next token
if (nextOffset) {
offset = nextOffset;
nextOffset = null;
}
start = end;
}
return tokens;
}
module.exports = exports['default']; |
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAssistantPhoto = (props) => (
<SvgIcon {...props}>
<path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/>
</SvgIcon>
);
ImageAssistantPhoto = pure(ImageAssistantPhoto);
ImageAssistantPhoto.displayName = 'ImageAssistantPhoto';
ImageAssistantPhoto.muiName = 'SvgIcon';
export default ImageAssistantPhoto;
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardVoice = (props) => (
<SvgIcon {...props}>
<path d="M12 15c1.66 0 2.99-1.34 2.99-3L15 6c0-1.66-1.34-3-3-3S9 4.34 9 6v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 15 6.7 12H5c0 3.42 2.72 6.23 6 6.72V22h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/>
</SvgIcon>
);
HardwareKeyboardVoice = pure(HardwareKeyboardVoice);
HardwareKeyboardVoice.displayName = 'HardwareKeyboardVoice';
HardwareKeyboardVoice.muiName = 'SvgIcon';
export default HardwareKeyboardVoice;
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionZoomIn = (props) => (
<SvgIcon {...props}>
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/>
</SvgIcon>
);
ActionZoomIn = pure(ActionZoomIn);
ActionZoomIn.displayName = 'ActionZoomIn';
ActionZoomIn.muiName = 'SvgIcon';
export default ActionZoomIn;
|
'use strict';function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
/**
* @module
* @description
* Starting point to import all compiler APIs.
*/
__export(require('./src/compiler/url_resolver'));
__export(require('./src/compiler/xhr'));
__export(require('./src/compiler/compiler'));
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29tcGlsZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJhbmd1bGFyMi9jb21waWxlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQTs7OztHQUlHO0FBQ0gsaUJBQWMsNkJBQTZCLENBQUMsRUFBQTtBQUM1QyxpQkFBYyxvQkFBb0IsQ0FBQyxFQUFBO0FBQ25DLGlCQUFjLHlCQUF5QixDQUFDLEVBQUEiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBtb2R1bGVcbiAqIEBkZXNjcmlwdGlvblxuICogU3RhcnRpbmcgcG9pbnQgdG8gaW1wb3J0IGFsbCBjb21waWxlciBBUElzLlxuICovXG5leHBvcnQgKiBmcm9tICcuL3NyYy9jb21waWxlci91cmxfcmVzb2x2ZXInO1xuZXhwb3J0ICogZnJvbSAnLi9zcmMvY29tcGlsZXIveGhyJztcbmV4cG9ydCAqIGZyb20gJy4vc3JjL2NvbXBpbGVyL2NvbXBpbGVyJzsiXX0= |
// #1683
var arr = [];
for (var i = 0; i < 4; ++i) {
arr.push(React.createElement("i", null));
}
|
/** math-expression-evaluator version 1.2.16
Dated:2017-02-02 */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mexp = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var Mexp=require('./postfix_evaluator.js');
Mexp.prototype.formulaEval = function () {
"use strict";
var stack=[],pop1,pop2,pop3;
var disp=[];
var temp='';
var arr=this.value;
for(var i=0;i<arr.length;i++){
if(arr[i].type===1||arr[i].type===3){
disp.push({value:arr[i].type===3?arr[i].show:arr[i].value,type:1});
}
else if(arr[i].type===13){
disp.push({value:arr[i].show,type:1});
}
else if(arr[i].type===0){
disp[disp.length-1]={value:arr[i].show+(arr[i].show!="-"?"(":"")+disp[disp.length-1].value+(arr[i].show!="-"?")":""),type:0};
}
else if(arr[i].type===7){
disp[disp.length-1]={value:(disp[disp.length-1].type!=1?"(":"")+disp[disp.length-1].value+(disp[disp.length-1].type!=1?")":"")+arr[i].show,type:7};
}
else if(arr[i].type===10){
pop1=disp.pop();
pop2=disp.pop();
if(arr[i].show==='P'||arr[i].show==='C')disp.push({value:"<sup>"+pop2.value+"</sup>"+arr[i].show+"<sub>"+pop1.value+"</sub>",type:10});
else disp.push({value:(pop2.type!=1?"(":"")+pop2.value+(pop2.type!=1?")":"")+"<sup>"+pop1.value+"</sup>",type:1});
}
else if(arr[i].type===2||arr[i].type===9){
pop1=disp.pop();
pop2=disp.pop();
disp.push({value:(pop2.type!=1?"(":"")+pop2.value+(pop2.type!=1?")":"")+arr[i].show+(pop1.type!=1?"(":"")+pop1.value+(pop1.type!=1?")":""),type:arr[i].type});
}
else if(arr[i].type===12){
pop1=disp.pop();
pop2=disp.pop();
pop3=disp.pop();
disp.push({value:arr[i].show+"("+pop3.value+","+pop2.value+","+pop1.value+")",type:12});
}
}
return disp[0].value;
};
module.exports=Mexp;
},{"./postfix_evaluator.js":5}],2:[function(require,module,exports){
var Mexp=require('./math_function.js');
function inc(arr,val){
for(var i=0;i<arr.length;i++)
arr[i]+=val;
return arr;
}
var token=['sin','cos','tan','pi','(',')','P','C',
'asin','acos','atan','7','8','9','int',
'cosh','acosh','ln','^','root','4','5','6','/','!',
'tanh','atanh','Mod','1','2','3','*',
'sinh','asinh','e','log','0','.','+','-',',','Sigma','n','Pi','pow'];
var show=['sin','cos','tan','π','(',')','P','C',
'asin','acos','atan','7','8','9','Int',
'cosh','acosh',' ln','^','root','4','5','6','÷','!',
'tanh','atanh',' Mod ','1','2','3','×',
'sinh','asinh','e',' log','0','.','+','-',',','Σ','n','Π','pow'];
var eva=[Mexp.math.sin,Mexp.math.cos,Mexp.math.tan,'PI','(',')',Mexp.math.P,Mexp.math.C,
Mexp.math.asin,Mexp.math.acos,Mexp.math.atan,'7','8','9',Math.floor,
Mexp.math.cosh,Mexp.math.acosh,Math.log,Math.pow,Math.sqrt,'4','5','6',Mexp.math.div,Mexp.math.fact,
Mexp.math.tanh,Mexp.math.atanh,Mexp.math.mod,'1','2','3',Mexp.math.mul,
Mexp.math.sinh,Mexp.math.asinh,'E',Mexp.math.log,'0','.',Mexp.math.add,Mexp.math.sub,',',Mexp.math.sigma,'n',Mexp.math.Pi,Math.pow];
var preced={0:11,1:0,2:3,3:0,4:0,5:0,6:0,7:11,8:11,9:1,10:10,11:0,12:11,13:0};
var type=[0,0,0,3,4,5,10,10,
0,0,0,1,1,1,0,
0,0,0,10,0,1,1,1,2,7,
0,0,2,1,1,1,2,
0,0,3,0,1,6,9,9,11,12,13,12,8];
/*
0 : function with syntax function_name(Maths_exp)
1 : numbers
2 : binary operators like * / Mod left associate and same precedence
3 : Math constant values like e,pi,Cruncher ans
4 : opening bracket
5 : closing bracket
6 : decimal
7 : function with syntax (Math_exp)function_name
8: function with syntax function_name(Math_exp1,Math_exp2)
9 : binary operator like +,-
10: binary operator like P C or ^
11: ,
12: function with , seperated three parameters
13: variable of Sigma function
*/
var type0={0:true,1:true,3:true,4:true,6:true,8:true,9:true,12:true,13:true},//type2:true,type4:true,type9:true,type11:true,type21:true,type22
type1={0:true,1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true,9:true,10:true,11:true,12:true,13:true},//type3:true,type5:true,type7:true,type23
type_1={0:true,3:true,4:true,8:true,12:true,13:true},
empty={},
type_3={0:true,1:true,3:true,4:true,6:true,8:true,12:true,13:true},//type_5:true,type_7:true,type_23
type6={1:true},
newAr=[[],
["1","2","3","7","8","9","4","5","6","+","-","*","/","(",")","^","!","P","C","e","0",".",",","n"],
["pi","ln","Pi"],
["sin","cos","tan","Del","int","Mod","log","pow"],
["asin","acos","atan","cosh","root","tanh","sinh"],
["acosh","atanh","asinh","Sigma"]];
function match(str1,str2,i,x){
for(var f=0;f<x;f++){
if (str1[i+f]!==str2[f])
return false;
}
return true;
}
Mexp.addToken=function(tokens){
for(i=0;i<tokens.length;i++){
x=tokens[i].token.length;
var temp=-1;
//newAr is a specially designed data structure in which 1D array at location one of 2d array has all string with length 1 2 with 2 and so on
if (x<newAr.length) //match to check if token is really huge and not existing
//if not checked it will break in next line as undefined index
for(y=0;y<newAr[x].length;y++){
if (tokens[i].token===newAr[x][y]){
temp=token.indexOf(newAr[x][y]);
break;
}
}
if (temp===-1) {
token.push(tokens[i].token);
type.push(tokens[i].type);
if(newAr.length<=tokens[i].token.length)
newAr[tokens[i].token.length]=[];
newAr[tokens[i].token.length].push(tokens[i].token);
eva.push(tokens[i].value);
show.push(tokens[i].show);
}
else {
token[temp]=tokens[i].token;
type[temp]=tokens[i].type;
eva[temp]=tokens[i].value;
show[temp]=tokens[i].show;
}
}
};
Mexp.lex=function(inp,tokens){
'use strict';
var str=[{type:4,value:"(",show:"(",pre:0}];
var ptc=[]; //Parenthesis to close at the beginning is after one token
var inpStr=inp;
var key;
var pcounter=0;
var allowed=type0;
var bracToClose=0;
var asterick=empty;
var prevKey='';
var i,x,y;
if(typeof tokens!=="undefined")
Mexp.addToken(tokens);
var obj={};
for(i=0;i<inpStr.length;i++){
if (inpStr[i]==' ') {
continue;
}
key='';
sec:for(x=(inpStr.length-i>(newAr.length-2)?newAr.length-1:inpStr.length-i);x>0;x--){
for(y=0;y<newAr[x].length;y++){
if (match(inpStr,newAr[x][y],i,x)){
key=newAr[x][y];
break sec;
}
}
}
i+=key.length-1;
if(key===''){
throw(new Mexp.exception("Can't understand after "+inpStr.slice(i)));
}
var index=token.indexOf(key);
var cToken=key;
var cType=type[index];
var cEv=eva[index];
var cPre=preced[cType];
var cShow=show[index];
var pre=str[str.length-1];
for(j=ptc.length;j--;){ //loop over ptc
if(ptc[j]===0){
if([0,2,3,5,9,11,12,13].indexOf(cType)!==-1){
if(allowed[cType]!==true){
throw(new Mexp.exception(key+" is not allowed after "+prevKey));
}
str.push({value:")",type:5,pre:0,show:")"});
allowed=type1;
asterick=type_3;
inc(ptc,-1).pop();
}
}
}
if(allowed[cType]!==true){
throw(new Mexp.exception(key+" is not allowed after "+prevKey));
}
if(asterick[cType]===true){
cType=2;
cEv=Mexp.math.mul;
cShow="×";
cPre=3;
i=i-key.length;
}
obj={value:cEv,type:cType,pre:cPre,show:cShow};
if(cType===0){
allowed=type0;
asterick=empty;
inc(ptc,2).push(2);
str.push(obj);
str.push({value:"(",type:4,pre:0,show:"("});
}
else if(cType===1){
if(pre.type===1){
pre.value+=cEv;
inc(ptc,1);
}
else {
str.push(obj);
}
allowed=type1;
asterick=type_1;
}
else if(cType===2){
allowed=type0;
asterick=empty;
inc(ptc,2);
str.push(obj);
}
else if(cType===3){//constant
str.push(obj);
allowed=type1;
asterick=type_3;
}
else if(cType===4){
pcounter+=ptc.length;
ptc=[];
bracToClose++;
allowed=type0;
asterick=empty;
str.push(obj);
}
else if(cType===5){
if(!bracToClose){
throw(new Mexp.exception("Closing parenthesis are more than opening one, wait What!!!"));
}
while(pcounter--){ //loop over ptc
str.push({value:")",type:5,pre:0,show:")"});
}
pcounter=0;
bracToClose--;
allowed=type1;
asterick=type_3;
str.push(obj);
}
else if(cType===6){
if(pre.hasDec){
throw(new Mexp.exception("Two decimals are not allowed in one number"));
}
if(pre.type!==1){
pre={value:0,type:1,pre:0}; //pre needs to be changed as it will the last value now to be safe in later code
str.push(pre);
inc(ptc,-1);
}
allowed=type6;
inc(ptc,1);
asterick=empty;
pre.value+=cEv;
pre.hasDec=true;
}
else if(cType===7){
allowed=type1;
asterick=type_3;
inc(ptc,1);
str.push(obj);
}
if(cType===8){
allowed=type0;
asterick=empty;
inc(ptc,4).push(4);
str.push(obj);
str.push({value:"(",type:4,pre:0,show:"("});
}
else if(cType===9){
if(pre.type===9){
if(pre.value===Mexp.math.add){
pre.value=cEv;
pre.show=cShow;
inc(ptc,1);
}
else if(pre.value===Mexp.math.sub&&cShow==='-'){
pre.value=Mexp.math.add;
pre.show='+';
inc(ptc,1);
}
}
else if(pre.type!==5&&pre.type!==7&&pre.type!==1&&pre.type!==3&&pre.type!==13){//changesign only when negative is found
if(cToken==='-'){//do nothing for + token
//don't add with the above if statement as that will run the else statement of parent if on Ctoken +
allowed=type0;
asterick=empty;
inc(ptc,2).push(2);
str.push({value:Mexp.math.changeSign,type:0,pre:21,show:"-"});
str.push({value:"(",type:4,pre:0,show:"("});
}
}
else{
str.push(obj);
inc(ptc,2);
}
allowed=type0;
asterick=empty;
}
else if(cType===10){
allowed=type0;
asterick=empty;
inc(ptc,2);
str.push(obj);
}
else if(cType===11){
allowed=type0;
asterick=empty;
str.push(obj);
}
else if(cType===12){
allowed=type0;
asterick=empty;
inc(ptc,6).push(6);
str.push(obj);
str.push({value:"(",type:4,pre:0});
}
else if(cType===13){
allowed=type1;
asterick=type_3;
str.push(obj);
}
inc(ptc,-1);
prevKey=key;
}
for(var j=ptc.length;j--;){ //loop over ptc
if(ptc[j]===0){
str.push({value:")",show:")",type:5,pre:3});
inc(ptc,-1).pop();
}
}
if (allowed[5]!==true) {
throw(new Mexp.exception("complete the expression"));
}
while(bracToClose--)
str.push({value:")",show:")",type:5,pre:3});
str.push({type:5,value:")",show:")",pre:0});
// console.log(str);
return new Mexp(str);
};
module.exports=Mexp;
},{"./math_function.js":3}],3:[function(require,module,exports){
var Mexp=function(parsed){
this.value=parsed;
};
Mexp.math={
isDegree:true, //mode of calculator
acos:function(x){
return (Mexp.math.isDegree?180/Math.PI*Math.acos(x):Math.acos(x));
},
add:function(a,b){
return a+b;
},
asin:function(x){
return (Mexp.math.isDegree?180/Math.PI*Math.asin(x):Math.asin(x));
},
atan:function(x){
return (Mexp.math.isDegree?180/Math.PI*Math.atan(x):Math.atan(x));
},
acosh:function(x){
return Math.log(x+Math.sqrt(x*x-1));
},
asinh:function(x){
return Math.log(x+Math.sqrt(x*x+1));
},
atanh:function(x){
return Math.log((1+x)/(1-x));
},
C:function(n,r){
var pro=1,other=n-r,choice=r;
if(choice<other){
choice=other;
other=r;
}
for(var i=choice+1;i<=n;i++)
pro*=i;
return pro/Mexp.math.fact(other);
},
changeSign:function(x){
return -x;
},
cos:function(x){
if(Mexp.math.isDegree)x=Mexp.math.toRadian(x);
return Math.cos(x);
},
cosh:function(x){
return (Math.pow(Math.E,x)+Math.pow(Math.E,-1*x))/2;
},
div:function(a,b){
return a/b;
},
fact:function(n) {
if(n%1!==0)return "NAN";
var pro=1;
for(var i=2;i<=n;i++)
pro*=i;
return pro;
},
inverse:function(x){
return 1/x;
},
log:function(i){
return Math.log(i)/Math.log(10);
},
mod:function(a,b){
return a%b;
},
mul:function(a,b){
return a*b;
},
P:function(n,r){var pro=1;
for(var i=Math.floor(n)-Math.floor(r)+1;i<=Math.floor(n);i++)
pro*=i;
return pro;
},
Pi:function(low,high,ex){
var pro=1;
for(var i=low;i<=high;i++){
pro*=Number(ex.postfixEval({n:i}));
}
return pro;
},
pow10x:function(e){
var x=1;
while(e--){x*=10;}
return x;
},
sigma:function(low,high,ex){
var sum=0;
for(var i=low;i<=high;i++){
sum+=Number(ex.postfixEval({n:i}));
}
return sum;
},
sin:function(x){
if(Mexp.math.isDegree)x=Mexp.math.toRadian(x);
return Math.sin(x);
},
sinh:function(x){
return (Math.pow(Math.E,x)-Math.pow(Math.E,-1*x))/2;
},
sub:function(a,b){
return a-b;
},
tan:function(x){
if(Mexp.math.isDegree)x=Mexp.math.toRadian(x);
return Math.tan(x);
},
tanh:function(x){
return Mexp.sinha(x)/Mexp.cosha(x);
},
toRadian:function(x){
return x*Math.PI/180;
}
};
Mexp.exception=function(message){
this.message=message;
};
module.exports=Mexp;
},{}],4:[function(require,module,exports){
var Mexp=require('./lexer.js');
Mexp.prototype.toPostfix = function () {
'use strict';
var post=[],elem,popped,prep,pre,ele;
var stack=[{value:"(",type:4,pre:0}];
var arr=this.value;
for (var i=1; i < arr.length; i++) {
if(arr[i].type===1||arr[i].type===3||arr[i].type===13){ //if token is number,constant,or n(which is also a special constant in our case)
if(arr[i].type===1)
arr[i].value=Number(arr[i].value);
post.push(arr[i]);
}
else if(arr[i].type===4){
stack.push(arr[i]);
}
else if(arr[i].type===5){
while((popped=stack.pop()).type!==4){
post.push(popped);
}
}
else if(arr[i].type===11){
while((popped=stack.pop()).type!==4){
post.push(popped);
}
stack.push(popped);
}
else {
elem=arr[i];
pre=elem.pre;
ele=stack[stack.length-1];
prep=ele.pre;
var flag=ele.value=='Math.pow'&&elem.value=='Math.pow';
if(pre>prep)stack.push(elem);
else {
while(prep>=pre&&!flag||flag&&pre<prep){
popped=stack.pop();
ele=stack[stack.length-1];
post.push(popped);
prep=ele.pre;
flag=elem.value=='Math.pow'&&ele.value=='Math.pow';
}
stack.push(elem);
}
}
}
return new Mexp(post);
};
module.exports=Mexp;
},{"./lexer.js":2}],5:[function(require,module,exports){
var Mexp=require('./postfix.js');
Mexp.prototype.postfixEval = function (UserDefined) {
'use strict';
UserDefined=UserDefined||{};
UserDefined.PI=Math.PI;
UserDefined.E=Math.E;
var stack=[],pop1,pop2,pop3;
var disp=[];
var temp='';
var arr=this.value;
var bool=(typeof UserDefined.n!=="undefined");
for(var i=0;i<arr.length;i++){
if(arr[i].type===1){
stack.push({value:arr[i].value,type:1});
}
else if(arr[i].type===3){
stack.push({value:UserDefined[arr[i].value],type:1});
}
else if(arr[i].type===0){
if(typeof stack[stack.length-1].type==="undefined"){
stack[stack.length-1].value.push(arr[i]);
}
else stack[stack.length-1].value=arr[i].value(stack[stack.length-1].value);
}
else if(arr[i].type===7){
if(typeof stack[stack.length-1].type==="undefined"){
stack[stack.length-1].value.push(arr[i]);
}
else stack[stack.length-1].value=arr[i].value(stack[stack.length-1].value);
}
else if(arr[i].type===8){
pop1=stack.pop();
pop2=stack.pop();
stack.push({type:1,value:arr[i].value(pop2.value,pop1.value)});
}
else if(arr[i].type===10){
pop1=stack.pop();
pop2=stack.pop();
if(typeof pop2.type==="undefined"){
pop2.value=pop2.concat(pop1);
pop2.value.push(arr[i]);
stack.push(pop2);
}
else if (typeof pop1.type==="undefined") {
pop1.unshift(pop2);
pop1.push(arr[i]);
stack.push(pop1);
}
else{
stack.push({type:1,value:arr[i].value(pop2.value,pop1.value)});
}
}
else if(arr[i].type===2||arr[i].type===9){
pop1=stack.pop();
pop2=stack.pop();
if(typeof pop2.type==="undefined"){
console.log(pop2);
pop2=pop2.concat(pop1);
pop2.push(arr[i]);
stack.push(pop2);
}
else if (typeof pop1.type==="undefined") {
pop1.unshift(pop2);
pop1.push(arr[i]);
stack.push(pop1);
}
else{
stack.push({type:1,value:arr[i].value(pop2.value,pop1.value)});
}
}
else if(arr[i].type===12){
pop1=stack.pop();
if (typeof pop1.type!=="undefined") {
pop1=[pop1];
}
pop2=stack.pop();
pop3=stack.pop();
stack.push({type:1,value:arr[i].value(pop3.value,pop2.value,new Mexp(pop1))});
}
else if(arr[i].type===13){
if(bool){
stack.push({value:UserDefined[arr[i].value],type:3});
}
else stack.push([arr[i]]);
}
}
if (stack.length>1) {
throw(new Mexp.exception("Uncaught Syntax error"));
}
return stack[0].value>1000000000000000?"Infinity":Number(stack[0].value.toFixed(15)).toPrecision();
};
Mexp.eval=function(str,tokens,obj){
if (typeof tokens==="undefined") {
return this.lex(str).toPostfix().postfixEval();
}
else if (typeof obj==="undefined") {
if (typeof tokens.length!=="undefined")
return this.lex(str,tokens).toPostfix().postfixEval();
else
return this.lex(str).toPostfix().postfixEval(tokens);
}
else
return this.lex(str,tokens).toPostfix().postfixEval(obj);
};
module.exports=Mexp;
},{"./postfix.js":4}]},{},[1])(1)
}); |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v7.0.2
* @link http://www.ag-grid.com/
* @license MIT
*/
var eventService_1 = require("../eventService");
var utils_1 = require("../utils");
var TouchListener = (function () {
function TouchListener(eElement) {
var _this = this;
this.destroyFuncs = [];
this.touching = false;
this.eventService = new eventService_1.EventService();
this.eElement = eElement;
var startListener = this.onTouchStart.bind(this);
var moveListener = this.onTouchMove.bind(this);
var endListener = this.onTouchEnd.bind(this);
this.eElement.addEventListener('touchstart', startListener);
this.eElement.addEventListener('touchmove', moveListener);
this.eElement.addEventListener('touchend', endListener);
this.destroyFuncs.push(function () {
_this.eElement.addEventListener('touchstart', startListener);
_this.eElement.addEventListener('touchmove', moveListener);
_this.eElement.addEventListener('touchend', endListener);
});
}
TouchListener.prototype.getActiveTouch = function (touchList) {
for (var i = 0; i < touchList.length; i++) {
var matches = touchList[i].identifier === this.touchStart.identifier;
if (matches) {
return touchList[i];
}
}
return null;
};
TouchListener.prototype.addEventListener = function (eventType, listener) {
this.eventService.addEventListener(eventType, listener);
};
TouchListener.prototype.removeEventListener = function (eventType, listener) {
this.eventService.removeEventListener(eventType, listener);
};
TouchListener.prototype.onTouchStart = function (touchEvent) {
var _this = this;
// only looking at one touch point at any time
if (this.touching) {
return;
}
this.touchStart = touchEvent.touches[0];
this.touching = true;
this.moved = false;
var touchStartCopy = this.touchStart;
setTimeout(function () {
var touchesMatch = _this.touchStart === touchStartCopy;
if (_this.touching && touchesMatch && !_this.moved) {
_this.moved = true;
_this.eventService.dispatchEvent(TouchListener.EVENT_LONG_TAP, _this.touchStart);
}
}, 500);
};
TouchListener.prototype.onTouchMove = function (touchEvent) {
if (!this.touching) {
return;
}
var touch = this.getActiveTouch(touchEvent.touches);
if (!touch) {
return;
}
var eventIsFarAway = !utils_1.Utils.areEventsNear(touch, this.touchStart, 4);
if (eventIsFarAway) {
this.moved = true;
}
};
TouchListener.prototype.onTouchEnd = function (touchEvent) {
if (!this.touching) {
return;
}
if (!this.moved) {
this.eventService.dispatchEvent(TouchListener.EVENT_TAP, this.touchStart);
}
this.touching = false;
};
TouchListener.prototype.destroy = function () {
this.destroyFuncs.forEach(function (func) { return func(); });
};
// private mostRecentTouch: Touch;
TouchListener.EVENT_TAP = 'tap';
TouchListener.EVENT_LONG_TAP = 'longTap';
return TouchListener;
})();
exports.TouchListener = TouchListener;
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=useForkRef;var React=_interopRequireWildcard(require("react")),_setRef=_interopRequireDefault(require("./setRef"));function useForkRef(r,t){return React.useMemo(function(){return null==r&&null==t?null:function(e){(0,_setRef.default)(r,e),(0,_setRef.default)(t,e)}},[r,t])} |
(function (exports,covutils) {
'use strict';
function iota$1(n) {
var result = new Array(n);
for(var i=0; i<n; ++i) {
result[i] = i;
}
return result
}
var iota_1 = iota$1;
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
var index = function (obj) {
return obj != null && (isBuffer$1(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
};
function isBuffer$1 (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer$1(obj.slice(0, 0))
}
var iota = iota_1;
var isBuffer = index;
var hasTypedArrays = ((typeof Float64Array) !== "undefined");
function compare1st(a, b) {
return a[0] - b[0]
}
function order() {
var stride = this.stride;
var terms = new Array(stride.length);
var i;
for(i=0; i<terms.length; ++i) {
terms[i] = [Math.abs(stride[i]), i];
}
terms.sort(compare1st);
var result = new Array(terms.length);
for(i=0; i<result.length; ++i) {
result[i] = terms[i][1];
}
return result
}
function compileConstructor(dtype, dimension) {
var className = ["View", dimension, "d", dtype].join("");
if(dimension < 0) {
className = "View_Nil" + dtype;
}
var useGetters = (dtype === "generic");
if(dimension === -1) {
//Special case for trivial arrays
var code =
"function "+className+"(a){this.data=a;};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return -1};\
proto.size=0;\
proto.dimension=-1;\
proto.shape=proto.stride=proto.order=[];\
proto.lo=proto.hi=proto.transpose=proto.step=\
function(){return new "+className+"(this.data);};\
proto.get=proto.set=function(){};\
proto.pick=function(){return null};\
return function construct_"+className+"(a){return new "+className+"(a);}";
var procedure = new Function(code);
return procedure()
} else if(dimension === 0) {
//Special case for 0d arrays
var code =
"function "+className+"(a,d) {\
this.data = a;\
this.offset = d\
};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return this.offset};\
proto.dimension=0;\
proto.size=1;\
proto.shape=\
proto.stride=\
proto.order=[];\
proto.lo=\
proto.hi=\
proto.transpose=\
proto.step=function "+className+"_copy() {\
return new "+className+"(this.data,this.offset)\
};\
proto.pick=function "+className+"_pick(){\
return TrivialArray(this.data);\
};\
proto.valueOf=proto.get=function "+className+"_get(){\
return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+
"};\
proto.set=function "+className+"_set(v){\
return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\
};\
return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}";
var procedure = new Function("TrivialArray", code);
return procedure(CACHED_CONSTRUCTORS[dtype][0])
}
var code = ["'use strict'"];
//Create constructor for view
var indices = iota(dimension);
var args = indices.map(function(i) { return "i"+i });
var index_str = "this.offset+" + indices.map(function(i) {
return "this.stride[" + i + "]*i" + i
}).join("+");
var shapeArg = indices.map(function(i) {
return "b"+i
}).join(",");
var strideArg = indices.map(function(i) {
return "c"+i
}).join(",");
code.push(
"function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a",
"this.shape=[" + shapeArg + "]",
"this.stride=[" + strideArg + "]",
"this.offset=d|0}",
"var proto="+className+".prototype",
"proto.dtype='"+dtype+"'",
"proto.dimension="+dimension);
//view.size:
code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\
return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"),
"}})");
//view.order:
if(dimension === 1) {
code.push("proto.order=[0]");
} else {
code.push("Object.defineProperty(proto,'order',{get:");
if(dimension < 4) {
code.push("function "+className+"_order(){");
if(dimension === 2) {
code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})");
} else if(dimension === 3) {
code.push(
"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\
if(s0>s1){\
if(s1>s2){\
return [2,1,0];\
}else if(s0>s2){\
return [1,2,0];\
}else{\
return [1,0,2];\
}\
}else if(s0>s2){\
return [2,0,1];\
}else if(s2>s1){\
return [0,1,2];\
}else{\
return [0,2,1];\
}}})");
}
} else {
code.push("ORDER})");
}
}
//view.set(i0, ..., v):
code.push(
"proto.set=function "+className+"_set("+args.join(",")+",v){");
if(useGetters) {
code.push("return this.data.set("+index_str+",v)}");
} else {
code.push("return this.data["+index_str+"]=v}");
}
//view.get(i0, ...):
code.push("proto.get=function "+className+"_get("+args.join(",")+"){");
if(useGetters) {
code.push("return this.data.get("+index_str+")}");
} else {
code.push("return this.data["+index_str+"]}");
}
//view.index:
code.push(
"proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}");
//view.hi():
code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
indices.map(function(i) {
return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("")
}).join(",")+","+
indices.map(function(i) {
return "this.stride["+i + "]"
}).join(",")+",this.offset)}");
//view.lo():
var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" });
var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" });
code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","));
for(var i=0; i<dimension; ++i) {
code.push(
"if(typeof i"+i+"==='number'&&i"+i+">=0){\
d=i"+i+"|0;\
b+=c"+i+"*d;\
a"+i+"-=d}");
}
code.push("return new "+className+"(this.data,"+
indices.map(function(i) {
return "a"+i
}).join(",")+","+
indices.map(function(i) {
return "c"+i
}).join(",")+",b)}");
//view.step():
code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
indices.map(function(i) {
return "a"+i+"=this.shape["+i+"]"
}).join(",")+","+
indices.map(function(i) {
return "b"+i+"=this.stride["+i+"]"
}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");
for(var i=0; i<dimension; ++i) {
code.push(
"if(typeof i"+i+"==='number'){\
d=i"+i+"|0;\
if(d<0){\
c+=b"+i+"*(a"+i+"-1);\
a"+i+"=ceil(-a"+i+"/d)\
}else{\
a"+i+"=ceil(a"+i+"/d)\
}\
b"+i+"*=d\
}");
}
code.push("return new "+className+"(this.data,"+
indices.map(function(i) {
return "a" + i
}).join(",")+","+
indices.map(function(i) {
return "b" + i
}).join(",")+",c)}");
//view.transpose():
var tShape = new Array(dimension);
var tStride = new Array(dimension);
for(var i=0; i<dimension; ++i) {
tShape[i] = "a[i"+i+"]";
tStride[i] = "b[i"+i+"]";
}
code.push("proto.transpose=function "+className+"_transpose("+args+"){"+
args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"),
"var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}");
//view.pick():
code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset");
for(var i=0; i<dimension; ++i) {
code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}");
}
code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}");
//Add return statement
code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
indices.map(function(i) {
return "shape["+i+"]"
}).join(",")+","+
indices.map(function(i) {
return "stride["+i+"]"
}).join(",")+",offset)}");
//Compile procedure
var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"));
return procedure(CACHED_CONSTRUCTORS[dtype], order)
}
function arrayDType(data) {
if(isBuffer(data)) {
return "buffer"
}
if(hasTypedArrays) {
switch(Object.prototype.toString.call(data)) {
case "[object Float64Array]":
return "float64"
case "[object Float32Array]":
return "float32"
case "[object Int8Array]":
return "int8"
case "[object Int16Array]":
return "int16"
case "[object Int32Array]":
return "int32"
case "[object Uint8Array]":
return "uint8"
case "[object Uint16Array]":
return "uint16"
case "[object Uint32Array]":
return "uint32"
case "[object Uint8ClampedArray]":
return "uint8_clamped"
}
}
if(Array.isArray(data)) {
return "array"
}
return "generic"
}
var CACHED_CONSTRUCTORS = {
"float32":[],
"float64":[],
"int8":[],
"int16":[],
"int32":[],
"uint8":[],
"uint16":[],
"uint32":[],
"array":[],
"uint8_clamped":[],
"buffer":[],
"generic":[]
};function wrappedNDArrayCtor(data, shape, stride, offset) {
if(data === undefined) {
var ctor = CACHED_CONSTRUCTORS.array[0];
return ctor([])
} else if(typeof data === "number") {
data = [data];
}
if(shape === undefined) {
shape = [ data.length ];
}
var d = shape.length;
if(stride === undefined) {
stride = new Array(d);
for(var i=d-1, sz=1; i>=0; --i) {
stride[i] = sz;
sz *= shape[i];
}
}
if(offset === undefined) {
offset = 0;
for(var i=0; i<d; ++i) {
if(stride[i] < 0) {
offset -= (shape[i]-1)*stride[i];
}
}
}
var dtype = arrayDType(data);
var ctor_list = CACHED_CONSTRUCTORS[dtype];
while(ctor_list.length <= d+1) {
ctor_list.push(compileConstructor(dtype, ctor_list.length-1));
}
var ctor = ctor_list[d+1];
return ctor(data, shape, stride, offset)
}
var ndarray = wrappedNDArrayCtor;
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var urlTemplate = createCommonjsModule(function (module, exports) {
(function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define([], factory);
} else {
root.urltemplate = factory();
}
}(commonjsGlobal, function () {
/**
* @constructor
*/
function UrlTemplate() {
}
/**
* @private
* @param {string} str
* @return {string}
*/
UrlTemplate.prototype.encodeReserved = function (str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
return part;
}).join('');
};
/**
* @private
* @param {string} str
* @return {string}
*/
UrlTemplate.prototype.encodeUnreserved = function (str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
};
/**
* @private
* @param {string} operator
* @param {string} value
* @param {string} key
* @return {string}
*/
UrlTemplate.prototype.encodeValue = function (operator, value, key) {
value = (operator === '+' || operator === '#') ? this.encodeReserved(value) : this.encodeUnreserved(value);
if (key) {
return this.encodeUnreserved(key) + '=' + value;
} else {
return value;
}
};
/**
* @private
* @param {*} value
* @return {boolean}
*/
UrlTemplate.prototype.isDefined = function (value) {
return value !== undefined && value !== null;
};
/**
* @private
* @param {string}
* @return {boolean}
*/
UrlTemplate.prototype.isKeyOperator = function (operator) {
return operator === ';' || operator === '&' || operator === '?';
};
/**
* @private
* @param {Object} context
* @param {string} operator
* @param {string} key
* @param {string} modifier
*/
UrlTemplate.prototype.getValues = function (context, operator, key, modifier) {
var value = context[key],
result = [];
if (this.isDefined(value) && value !== '') {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
value = value.toString();
if (modifier && modifier !== '*') {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
} else {
if (modifier === '*') {
if (Array.isArray(value)) {
value.filter(this.isDefined).forEach(function (value) {
result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
}, this);
} else {
Object.keys(value).forEach(function (k) {
if (this.isDefined(value[k])) {
result.push(this.encodeValue(operator, value[k], k));
}
}, this);
}
} else {
var tmp = [];
if (Array.isArray(value)) {
value.filter(this.isDefined).forEach(function (value) {
tmp.push(this.encodeValue(operator, value));
}, this);
} else {
Object.keys(value).forEach(function (k) {
if (this.isDefined(value[k])) {
tmp.push(this.encodeUnreserved(k));
tmp.push(this.encodeValue(operator, value[k].toString()));
}
}, this);
}
if (this.isKeyOperator(operator)) {
result.push(this.encodeUnreserved(key) + '=' + tmp.join(','));
} else if (tmp.length !== 0) {
result.push(tmp.join(','));
}
}
}
} else {
if (operator === ';') {
if (this.isDefined(value)) {
result.push(this.encodeUnreserved(key));
}
} else if (value === '' && (operator === '&' || operator === '?')) {
result.push(this.encodeUnreserved(key) + '=');
} else if (value === '') {
result.push('');
}
}
return result;
};
/**
* @param {string} template
* @return {function(Object):string}
*/
UrlTemplate.prototype.parse = function (template) {
var that = this;
var operators = ['+', '#', '.', '/', ';', '?', '&'];
return {
expand: function (context) {
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
var operator = null,
values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push.apply(values, that.getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== '+') {
var separator = ',';
if (operator === '?') {
separator = '&';
} else if (operator !== '#') {
separator = operator;
}
return (values.length !== 0 ? operator : '') + values.join(separator);
} else {
return values.join(',');
}
} else {
return that.encodeReserved(literal);
}
});
}
};
};
return new UrlTemplate();
}));
});
var LINKRELPREFIX = 'http://www.iana.org/assignments/relation/';
var PREFIX = 'https://covjson.org/def/';
var CORE_PREFIX = PREFIX + 'core#';
var DOMAINTYPES_PREFIX = PREFIX + 'domainTypes#';
/**
* @ignore
*/
function assert(condition, message) {
if (!condition) {
message = message || 'Assertion failed';
throw new Error(message);
}
}
/**
* @ignore
*/
function shallowcopy(obj) {
var copy = Object.create(Object.getPrototypeOf(obj));
for (var prop in obj) {
copy[prop] = obj[prop];
}
return copy;
}
/**
* Extracts all the directly included namespaces from the `@context` field,
* not following remote JSON-LD contexts.
*
* @ignore
* @param doc A JSON-LD document.
* @returns {Map<string,string>}
*/
function getNamespacePrefixes(doc) {
var context = doc['@context'];
if (!context) {
return;
}
if (!Array.isArray(context)) {
context = [context];
}
var prefixes = new Map();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = context[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var item = _step.value;
if (typeof item === 'string') {
continue;
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = Object.keys(item)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var key = _step2.value;
if (typeof item[key] === 'string') {
prefixes.set(key, item[key]);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return prefixes;
}
var MEDIATYPE = {
COVJSON: 'application/prs.coverage+json',
JSONLD: 'application/ld+json',
JSON: 'application/json',
TEXT: 'text/plain'
};
var COVJSON_PROFILE_STANDALONE = CORE_PREFIX + 'standalone';
/**
* Returns an Accept header value for requesting CoverageJSON documents.
*
* @param {bool} standalone Whether to include the standalone profile of CoverageJSON or not.
*/
function getAcceptHeader(standalone) {
var covjsonProfile = standalone ? '; profile="' + COVJSON_PROFILE_STANDALONE + '"' : '';
var accept = MEDIATYPE.COVJSON + covjsonProfile + '; q=1.0, ' + MEDIATYPE.JSONLD + '; q=0.1, ' + MEDIATYPE.JSON + '; q=0.1';
return accept;
}
/**
* Checks if a media type matches any given media types, ignoring any parameters.
*
* @param {string} mediaType The media type.
* @param {string|Array} matchingMediaTypes The media type(s) to match against.
* @return {bool} True if there is a match.
*/
/**
* See reader.js#load for docs.
*
* Browser implementation.
*/
function load$1(url) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var responseType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'arraybuffer';
if (['arraybuffer', 'text'].indexOf(responseType) === -1) {
throw new Error();
}
var headers = options.headers || {};
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = responseType;
var accept = getAcceptHeader(options.eagerload);
req.setRequestHeader('Accept', accept);
if (headers) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(headers)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var header = _step.value;
req.setRequestHeader(header, headers[header]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
req.addEventListener('load', function () {
try {
if (!(req.status >= 200 && req.status < 300 || req.status === 304)) {
// as in jquery
reject(new Error('Resource "' + url + '" not found, HTTP status code: ' + req.status));
return;
}
var data = void 0;
if (responseType === 'arraybuffer') {
if (window.TextDecoder) {
var t0 = new Date();
data = JSON.parse(new TextDecoder().decode(new DataView(req.response)));
console.log('JSON decoding: ' + (new Date() - t0) + 'ms');
} else {
// load again (from cache) to get correct response type
// Note we use 'text' and not 'json' as we want to throw parsing errors.
// With 'json', the response is just 'null'.
reject({ responseType: 'text' });
return;
}
} else {
var _t = new Date();
data = JSON.parse(req.response);
console.log('JSON decoding (slow path): ' + (new Date() - _t) + 'ms');
}
var responseHeaders = parseResponseHeaders(req.getAllResponseHeaders());
resolve({
data: data,
headers: responseHeaders
});
} catch (e) {
reject(e);
}
});
req.addEventListener('error', function () {
reject(new Error('Network error loading resource at ' + url));
});
req.send();
}).catch(function (e) {
if (e.responseType) {
return load$1(url, headers, e.responseType);
} else {
throw e;
}
});
}
/**
* XmlHttpRequest's getAllResponseHeaders() method returns a string of response
* headers according to the format described here:
* http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method
* This method parses that string into a user-friendly key/value pair object.
* Header names are lower-cased.
*
* https://gist.github.com/monsur/706839
*/
function parseResponseHeaders(headerStr) {
var headers = {};
if (!headerStr) {
return headers;
}
var headerPairs = headerStr.split('\r\n');
for (var i = 0; i < headerPairs.length; i++) {
var headerPair = headerPairs[i];
// Can't use split() here because it does the wrong thing
// if the header value has the string ": " in it.
var index = headerPair.indexOf(': ');
if (index > 0) {
var key = headerPair.substring(0, index).toLowerCase();
var val = headerPair.substring(index + 2);
headers[key] = val;
}
}
return headers;
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var asyncGenerator = function () {
function AwaitValue(value) {
this.value = value;
}
function AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function (resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
if (value instanceof AwaitValue) {
Promise.resolve(value.value).then(function (arg) {
resume("next", arg);
}, function (arg) {
resume("throw", arg);
});
} else {
settle(result.done ? "return" : "normal", result.value);
}
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch (type) {
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
return this;
};
}
AsyncGenerator.prototype.next = function (arg) {
return this._invoke("next", arg);
};
AsyncGenerator.prototype.throw = function (arg) {
return this._invoke("throw", arg);
};
AsyncGenerator.prototype.return = function (arg) {
return this._invoke("return", arg);
};
return {
wrap: function (fn) {
return function () {
return new AsyncGenerator(fn.apply(this, arguments));
};
},
await: function (value) {
return new AwaitValue(value);
}
};
}();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
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$1 = function get$1(object, property, receiver) {
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 {
return get$1(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
var set = function set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent !== null) {
set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) {
setter.call(receiver, value);
}
}
return value;
};
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 toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/**
* @external {Parameter} https://github.com/Reading-eScience-Centre/coverage-jsapi/blob/master/Parameter.md
* @external {Domain} https://github.com/Reading-eScience-Centre/coverage-jsapi/blob/master/Domain.md
* @external {Range} https://github.com/Reading-eScience-Centre/coverage-jsapi/blob/master/Range.md
*/
/**
* Wraps a CoverageJSON Coverage object as a Coverage API object.
*
* @see https://github.com/Reading-eScience-Centre/coverage-jsapi
*/
var Coverage = function () {
/**
* Create a Coverage instance.
*
* @param {Object} covjson A CoverageJSON Coverage object.
* @param {Object} [options]
* @param {boolean} [options.cacheRanges]
* If true, then any range that was loaded remotely is cached.
* (The domain is always cached.)
* @param {Array} [options.referencing]
* Referencing info to use (e.g. from containing collection).
*/
function Coverage(covjson, options) {
classCallCheck(this, Coverage);
this._covjson = covjson;
/**
* The constant "Coverage".
*
* @type {string}
*/
this.type = covutils.COVERAGE;
/**
* JSON-LD document
*
* @type {Object}
*/
this.ld = {};
this._exposeLd(covjson);
this.prefixes = getNamespacePrefixes(this.ld);
/**
* The options object that was passed in to the constructor.
*
* @type {Object}
*/
this.options = options ? shallowcopy(options) : {};
/**
* ID of the coverage.
*
* @type {string|undefined}
*/
this.id = covjson.id;
/**
* A Map from key to {@link Parameter} object.
* The key is a short alias of a {@link Parameter}, typically what is called a "variable name" or similar.
*
* @type {Map<string,Parameter>}
*/
this.parameters = new Map();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(covjson.parameters)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
transformParameter(covjson.parameters, key);
this.parameters.set(key, covjson.parameters[key]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var domainType = void 0;
if (typeof this._covjson.domain === 'string') {
domainType = this._covjson.domainType;
} else {
domainType = this._covjson.domain.domainType || this._covjson.domainType;
}
if (domainType && domainType.indexOf(':') === -1) {
domainType = DOMAINTYPES_PREFIX + domainType;
}
/**
* If defined, then the coverage has a domain that follows the given domain type,
* either a full URI or a namespace-prefixed term. (See .prefixes)
*
* @type {string|undefined}
*/
this.domainType = domainType;
this._updateLoadStatus();
}
createClass(Coverage, [{
key: '_updateLoadStatus',
value: function _updateLoadStatus() {
var _this = this;
var isLoaded = function isLoaded(prop) {
return (typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) === 'object';
};
var domainLoaded = isLoaded(this._covjson.domain);
var rangesLoaded = Object.keys(this._covjson.ranges).every(function (key) {
return isLoaded(_this._covjson.ranges[key]);
});
/**
* A boolean which indicates whether all coverage data is already loaded in memory.
* If true then this typically means that calls to .loadDomain(), .loadRange(),
* .loadRanges(), .subsetByIndex(), and .subsetByValue() will not invoke a network request.
*
* @type {boolean}
*/
this.loaded = domainLoaded && rangesLoaded;
}
}, {
key: '_exposeLd',
value: function _exposeLd(covjson) {
if (!covjson['@context']) {
// no LD love here...
return;
}
// make a deep copy since the object gets modified in-place later
// but first, remove domain and range which may be embedded
var copy = shallowcopy(covjson);
delete copy.domain;
delete copy.ranges;
this.ld = JSON.parse(JSON.stringify(copy));
}
/**
* Returns a Promise succeeding with a {@link Domain} object.
*
* @return {Promise<Domain>}
*/
}, {
key: 'loadDomain',
value: function loadDomain() {
var _this2 = this;
var domainOrUrl = this._covjson.domain;
if (this._domainPromise) return this._domainPromise;
var promise = void 0;
if ((typeof domainOrUrl === 'undefined' ? 'undefined' : _typeof(domainOrUrl)) === 'object') {
var domain = domainOrUrl;
transformDomain(domain, this.options.referencing, this.domainType);
promise = Promise.resolve(domain);
} else {
var url = domainOrUrl;
promise = load$1(url).then(function (result) {
var domain = result.data;
transformDomain(domain, _this2.options.referencing, _this2.domainType);
_this2._covjson.domain = domain;
_this2._updateLoadStatus();
return domain;
});
}
/* The promise gets cached so that the domain is not loaded twice remotely.
* This might otherwise happen when loadDomain and loadRange is used
* with Promise.all(). Remember that loadRange also invokes loadDomain.
*/
this._domainPromise = promise;
return promise;
}
/**
* Returns a Promise succeeding with a {@link Range} object.
*
* Note that this method implicitly loads the domain as well.
*
* @example
* cov.loadRange('salinity').then(function (sal) {
* // work with Range object
* }).catch(function (e) {
* // there was an error when loading the range
* console.log(e.message)
* })
* @param {string} paramKey The key of the Parameter for which to load the range.
* @return {Promise<Range>} A Promise object which loads the requested range data and succeeds with a Range object.
*/
}, {
key: 'loadRange',
value: function loadRange(paramKey) {
return loadRangeFn(this)(paramKey);
}
/**
* Returns the requested range data as a Promise.
*
* Note that this method implicitly loads the domain as well.
*
* @example
* cov.loadRanges(['salinity','temp']).then(function (ranges) {
* // work with Map object
* console.log(ranges.get('salinity').values)
* }).catch(function (e) {
* // there was an error when loading the range data
* console.log(e)
* })
* @param {iterable<string>} [paramKeys] An iterable of parameter keys for which to load the range data. If not given, loads all range data.
* @return {Promise<Map<string,Range>>} A Promise object which loads the requested range data and succeeds with a Map object.
*/
}, {
key: 'loadRanges',
value: function loadRanges(paramKeys) {
return loadRangesFn(this)(paramKeys);
}
/**
* Returns a Promise object which provides a copy of this Coverage object
* with the domain subsetted by the given indices specification.
*
* Note that the coverage type and/or domain type of the resulting coverage
* may be different than in the original coverage.
*
* Note that the subsetted ranges are a view over the original ranges, meaning
* that no copying is done but also no memory is released if the original
* coverage is garbage collected.
*
* @example
* cov.subsetByIndex({t: 4, z: {start: 10, stop: 20} }).then(function(subsetCov) {
* // work with subsetted coverage
* })
* @param {Object} constraints An object which describes the subsetting constraints.
* Every property of it refers to an axis name as defined in Domain.names,
* and its value must either be an integer
* or an object with start, stop, and optionally step (defaults to 1) properties
* whose values are integers.
* Properties that have the values undefined or null are ignored.
* All integers must be non-negative, step must not be zero.
* An integer constrains the axis to the given index,
* a start/stop/step object to a range of indices:
* If step=1, this includes all indices starting at start and ending at stop (exclusive);
* if step>1, all indices start, start + step, ..., start + (q + r - 1) step where
* q and r are the quotient and remainder obtained by dividing stop - start by step.
* @returns {Promise<Coverage>} A Promise object with the subsetted coverage object as result.
*/
}, {
key: 'subsetByIndex',
value: function subsetByIndex(constraints) {
return subsetByIndexFn(this)(constraints);
}
/**
* Returns a Promise object which provides a copy of this Coverage object
* with the domain subsetted by the given value specification.
*
* Note that the coverage type and/or domain type of the resulting coverage
* may be different than in the original coverage.
*
* Note that the subsetted ranges are a view over the original ranges, meaning
* that no copying is done but also no memory is released if the original
* coverage is garbage collected.
*
* @example
* cov.subsetByValue({
* t: '2015-01-01T01:00:00',
* z: {start: -10, stop: -5}
* }).then(function(subsetCov) {
* // work with subsetted coverage
* })
* @example
* cov.subsetByValue({z: {target: -10} }).then(function(subsetCov) {
* // work with subsetted coverage
* }
* @param {Object} constraints An object which describes the subsetting constraints.
* Every property of it refers to an axis name as defined in Domain.names,
* and its value must either be a number or string, or,
* if the axis has an ordering relation, an object with start and stop properties
* whose values are numbers or strings, or an object with a target property
* whose value is a number or string.
* Properties that have the values undefined or null are ignored.
* A number or string constrains the axis to exactly the given value,
* a start/stop object to the values intersecting the extent,
* and a target object to the value closest to the given value.
* @returns {Promise<Coverage>} A Promise object with the subsetted coverage object as result.
*/
}, {
key: 'subsetByValue',
value: function subsetByValue(constraints) {
return covutils.subsetByValue(this, constraints);
}
}]);
return Coverage;
}();
function getRangeAxisOrder(domain, range) {
if (!domain) {
return range._axisNames;
}
// backwards-compatibility, in the future the range always has an explicit axis ordering
var needsRangeAxisOrder = [].concat(toConsumableArray(domain.axes.values())).filter(function (axis) {
return axis.values.length > 1;
}).length > 1;
// domain is checked for backwards-compatibility
var axisOrder = domain._rangeAxisOrder || range._axisNames;
if (needsRangeAxisOrder && !axisOrder) {
throw new Error('Range axis order missing');
}
axisOrder = axisOrder || [].concat(toConsumableArray(domain.axes.keys()));
return axisOrder;
}
function getRangeShapeArray(domain, range) {
if (!domain) {
return range._shape;
}
// mostly backwards-compatibility, in the future this just returns range._shape
var axisOrder = getRangeAxisOrder(domain, range);
var shape = axisOrder.map(function (k) {
return domain.axes.get(k).values.length;
});
if (range._shape) {
var matchesDomain = range._shape.length === shape.length && range._shape.every(function (v, i) {
return v === shape[i];
});
if (!matchesDomain) {
throw new Error('range.shape must match domain axis sizes');
}
}
return shape;
}
function loadRangesFn(cov) {
return function (paramKeys) {
if (paramKeys === undefined) paramKeys = cov.parameters.keys();
paramKeys = Array.from(paramKeys);
return Promise.all(paramKeys.map(function (k) {
return cov.loadRange(k);
})).then(function (ranges) {
var map = new Map();
for (var i = 0; i < paramKeys.length; i++) {
map.set(paramKeys[i], ranges[i]);
}
return map;
});
};
}
function loadRangeFn(cov, globalConstraints) {
return function (paramKey) {
// Since the shape of the range array is derived from the domain, it has to be loaded as well.
return cov.loadDomain().then(function () {
var rangeOrUrl = cov._covjson.ranges[paramKey];
if ((typeof rangeOrUrl === 'undefined' ? 'undefined' : _typeof(rangeOrUrl)) === 'object') {
var rawRange = rangeOrUrl;
// we need the original domain here, not a potentially subsetted one,
// therefore we access cov._covjson directly
// this legacy code will disappear once the old range format is not supported anymore
return doLoadRange(cov, paramKey, rawRange, cov._covjson.domain, globalConstraints);
} else {
var url = rangeOrUrl;
return load$1(url).then(function (result) {
var rawRange = result.data;
return doLoadRange(cov, paramKey, rawRange, cov._covjson.domain, globalConstraints);
});
}
});
};
}
function doLoadRange(cov, paramKey, range, domain) {
var globalConstraints = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
globalConstraints = covutils.normalizeIndexSubsetConstraints(domain, globalConstraints);
if (range.type === 'NdArray' || range.type === 'Range') {
// if an NdArray, then we modify it in-place (only done the first time)
transformNdArrayRange(range, domain);
if (cov.options.cacheRanges) {
cov._covjson.ranges[paramKey] = range;
cov._updateLoadStatus();
}
var newrange = subsetNdArrayRangeByIndex(range, domain, globalConstraints);
return Promise.resolve(newrange);
} else if (range.type === 'TiledNdArray') {
return loadTiledNdArraySubset(range, globalConstraints);
} else {
throw new Error('Unsupported: ' + range.type);
}
}
/**
*
* @param {object} range TiledNdArray range object
* @param {object} constraints subsetting constraints
* @returns {Promise<Range>}
*/
function loadTiledNdArraySubset(range, constraints) {
var constraintsArr = range.axisNames.map(function (name) {
return constraints[name];
});
// step 1: select tileset with least network effort
var fillNulls = function fillNulls(tileShape) {
return tileShape.map(function (v, i) {
return v === null ? range.shape[i] : v;
});
};
var tilesetsStats = range.tileSets.map(function (ts) {
return getTilesetStats(fillNulls(ts.tileShape), constraintsArr);
});
var idxBestTileset = indexOfBestTileset(tilesetsStats);
var tileset = range.tileSets[idxBestTileset];
var urlTemplate$$1 = urlTemplate.parse(tileset.urlTemplate);
var tileShape = fillNulls(tileset.tileShape);
// step 2: determine the tiles to load
var subsetTilesetAxes = [];
for (var ax = 0; ax < tileShape.length; ax++) {
var _constraintsArr$ax = constraintsArr[ax];
var start = _constraintsArr$ax.start;
var stop = _constraintsArr$ax.stop;
var step = _constraintsArr$ax.step;
var tileSize = tileShape[ax];
// the indices of the first and last tile containing the subsetting constraints
var tileStart = Math.floor(start / tileSize); // inclusive
var tileStop = Math.ceil(stop / tileSize); // exclusive
var tilesetAxis = [];
for (var t = tileStart; t < tileStop; t++) {
var mid = (t + 0.5) * tileSize;
// regard the subset constraint as a list of [x,y) half-closed intervals and find out where 'mid' falls into
var iv = Math.floor((mid - start) / step);
// start and end point of the interval in range index space
var ivStart = start + iv * step;
var ivStop = start + (iv + 1) * step;
// tile start and end in range index space
var tileStartR = t * tileSize;
var tileStopR = (t + 1) * tileSize;
// check if the start or end point of the interval lies within the tile
if (ivStart >= tileStartR || tileStopR <= ivStop) {
tilesetAxis.push(t);
}
}
subsetTilesetAxes.push(tilesetAxis);
}
var tiles = cartesianProduct(subsetTilesetAxes);
var subsetShape = constraintsArr.map(function (_ref) {
var start = _ref.start;
var stop = _ref.stop;
var step = _ref.step;
return Math.floor((stop - start) / step) + (stop - start) % step;
});
function getTileUrl(tile) {
var tileUrlVars = {};
tile.forEach(function (v, i) {
return tileUrlVars[range.axisNames[i]] = v;
});
return urlTemplate$$1.expand(tileUrlVars);
}
// step 3a: check if only a single tile will be loaded and avoid copying data around in that case
if (tiles.length === 1 && subsetShape.every(function (v, i) {
return v === tileShape[i];
})) {
var url = getTileUrl(tiles[0]);
return load$1(url).then(function (result) {
var tileRange = result.data;
transformNdArrayRange(tileRange);
return tileRange;
});
} else {
var _ret = function () {
// step 3b: create an empty ndarray of the subset shape that will be filled with tile data
var subsetSize = subsetShape.reduce(function (l, r) {
return l * r;
});
var subsetNdArr = ndarray(new Array(subsetSize), subsetShape);
// step 4: load tiles and fill subset ndarray
var promises = tiles.map(function (tile) {
var url = getTileUrl(tile);
return load$1(url).then(function (result) {
var tileRange = result.data;
transformNdArrayRange(tileRange);
// figure out which parts of the tile to copy into which part of the final ndarray
var tileOffsets = tile.map(function (v, i) {
return v * tileShape[i];
});
// iterate all tile values and for each check if they are part of the subset
// TODO this code is probably quite slow, consider pre-compiling etc
// -> use ndarray-ops#assign for fast copies
var tileAxesSubsetIndices = [];
for (var _ax = 0; _ax < tileShape.length; _ax++) {
var _constraintsArr$_ax = constraintsArr[_ax];
var start = _constraintsArr$_ax.start;
var stop = _constraintsArr$_ax.stop;
var step = _constraintsArr$_ax.step;
var tileAxisSize = tileShape[_ax];
var tileAxisOffset = tileOffsets[_ax];
var tileAxisSubsetIndices = [];
var startIdx = 0;
if (tileAxisOffset < start) {
startIdx = start - tileAxisOffset;
}
var stopIdx = tileAxisSize;
if (tileAxisOffset + stopIdx > stop) {
stopIdx = stop - tileAxisOffset;
}
for (var i = startIdx; i < stopIdx; i++) {
var idx = tileAxisOffset + i;
if ((idx - start) % step === 0) {
tileAxisSubsetIndices.push(i);
}
}
tileAxesSubsetIndices.push(tileAxisSubsetIndices);
}
var tileSubsetIndices = cartesianProduct(tileAxesSubsetIndices);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = tileSubsetIndices[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var _tileRange$_ndarr;
var tileInd = _step2.value;
var val = (_tileRange$_ndarr = tileRange._ndarr).get.apply(_tileRange$_ndarr, toConsumableArray(tileInd));
var subsetInd = tileInd.map(function (i, ax) {
var idx = tileOffsets[ax] + i;
return Math.floor((idx - constraintsArr[ax].start) / constraintsArr[ax].step);
});
subsetNdArr.set.apply(subsetNdArr, toConsumableArray(subsetInd).concat([val]));
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
});
});
// step 5: create and return the new range
return {
v: Promise.all(promises).then(function () {
var newrange = {
dataType: range.dataType,
get: createRangeGetFunction(subsetNdArr, range.axisNames),
_ndarr: subsetNdArr,
_axisNames: range.axisNames,
_shape: subsetShape
};
newrange.shape = new Map(range.axisNames.map(function (v, i) {
return [v, subsetNdArr.shape[i]];
}));
return newrange;
})
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
}
/**
* Return the cartesian product of the given arrays.
*
* @see http://stackoverflow.com/a/36234242
*/
function cartesianProduct(arr) {
return arr.reduce(function (a, b) {
return a.map(function (x) {
return b.map(function (y) {
return x.concat(y);
});
}).reduce(function (a, b) {
return a.concat(b);
}, []);
}, [[]]);
}
/**
* Returns the number of tiles and values that have to be loaded, given a set of subsetting constraints.
*
* @param {Array<number>} tileShape
* @param {Array<object>} constraints - start/stop/step subset constraints for each axis, stop is exclusive
* @returns {number}
*/
function getTilesetStats(tileShape, constraints) {
var tileCount = 1;
for (var i = 0; i < tileShape.length; i++) {
var _constraints$i = constraints[i];
var start = _constraints$i.start;
var stop = _constraints$i.stop;
var step = _constraints$i.step;
var tileSize = tileShape[i];
// the indices of the first and last tile containing the subsetting constraints
var tileStart = Math.floor(start / tileSize); // inclusive
var tileStop = Math.ceil(stop / tileSize); // exclusive
// total number of values within the tiles containing the subsetting constraints
var nvalues = tileSize * (tileStop - tileStart);
// number of tiles that intersect with the subsetting constraints
tileCount *= Math.ceil(nvalues / Math.max(step, tileSize));
}
// the value count is an upper bound as it doesn't account for edge tiles that may be smaller
var valueCount = tileCount * tileShape.reduce(function (l, r) {
return l * r;
});
return { tileCount: tileCount, valueCount: valueCount };
}
/**
* Returns the index of the tileset with minimum network effort based on the given tileset statistics.
* Effort here means a combination of number of requested tiles and values.
*
* @param {Array<object>} tilesetsStats
* @returns {number} index of the tileset with minimum network effort
*/
function indexOfBestTileset(tilesetsStats) {
// one tile request shall have an equal effort as receiving 1000 values
var tileValueRatio = 1000;
var efforts = tilesetsStats.map(function (s) {
return s.tileCount + s.valueCount / tileValueRatio;
});
var minEffortIdx = efforts.reduce(function (imin, x, i, arr) {
return x < arr[imin] ? i : imin;
}, 0);
return minEffortIdx;
}
function subsetNdArrayRangeByIndex(range, domain, constraints) {
var _ndarr$hi$lo, _ndarr$hi;
var ndarr = range._ndarr;
// fast ndarray view
var axisNames = getRangeAxisOrder(domain, range);
var los = axisNames.map(function (name) {
return constraints[name].start;
});
var his = axisNames.map(function (name) {
return constraints[name].stop;
});
var steps = axisNames.map(function (name) {
return constraints[name].step;
});
var newndarr = (_ndarr$hi$lo = (_ndarr$hi = ndarr.hi.apply(ndarr, toConsumableArray(his))).lo.apply(_ndarr$hi, toConsumableArray(los))).step.apply(_ndarr$hi$lo, toConsumableArray(steps));
var newrange = {
dataType: range.dataType,
get: createRangeGetFunction(newndarr, axisNames),
_ndarr: newndarr,
_axisNames: axisNames,
_shape: newndarr.shape
};
newrange.shape = new Map(axisNames.map(function (v, i) {
return [v, newndarr.shape[i]];
}));
return newrange;
}
function subsetByIndexFn(cov, globalConstraints) {
return function (constraints) {
return cov.loadDomain().then(function (domain) {
constraints = covutils.normalizeIndexSubsetConstraints(domain, constraints);
var newdomain = covutils.subsetDomainByIndex(domain, constraints);
var newGlobalConstraints = toGlobalSubsetConstraints(constraints, globalConstraints);
// backwards-compatibility
if (domain._rangeAxisOrder) {
newdomain._rangeAxisOrder = domain._rangeAxisOrder;
}
// assemble everything to a new coverage
var newcov = {
_covjson: cov._covjson,
options: cov.options,
type: covutils.COVERAGE,
// TODO are the profiles still valid?
domainProfiles: cov.domainProfiles,
domainType: cov.domainType,
parameters: cov.parameters,
loadDomain: function loadDomain() {
return Promise.resolve(newdomain);
}
};
newcov.loadRange = loadRangeFn(newcov, newGlobalConstraints);
newcov.loadRanges = loadRangesFn(newcov);
newcov.subsetByIndex = subsetByIndexFn(newcov, newGlobalConstraints);
newcov.subsetByValue = covutils.subsetByValue.bind(null, newcov);
return newcov;
});
};
}
/**
* Currently unused, but may need in future.
* This determines the best array type for categorical data which
* doesn't have missing values.
*/
/*
function arrayType (validMin, validMax) {
let type
if (validMin !== undefined) {
if (validMin >= 0) {
if (validMax < Math.pow(2,8)) {
type = Uint8Array
} else if (validMax < Math.pow(2,16)) {
type = Uint16Array
} else if (validMax < Math.pow(2,32)) {
type = Uint32Array
} else {
type = Array
}
} else {
let max = Math.max(Math.abs(validMin), validMax)
if (max < Math.pow(2,8)) {
type = Int8Array
} else if (validMax < Math.pow(2,16)) {
type = Int16Array
} else if (validMax < Math.pow(2,32)) {
type = Int32Array
} else {
type = Array
}
}
} else {
type = Array
}
return type
}
*/
/**
* Transforms a CoverageJSON parameter to the Coverage API format, that is,
* some elements are converted from objects to Maps. Transformation is made in-place.
*
* @param {Object} param The original parameter.
* @access private
*/
function transformParameter(params, key) {
if ('__transformDone' in params[key]) return;
var param = params[key];
param.key = key;
if (param.unit) {
if (typeof param.unit.symbol === 'string') {
param.unit.symbol = {
value: param.unit.symbol
// no type member, since the scheme is unknown
};
}
}
if (param.categoryEncoding) {
var map = new Map();
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = Object.keys(param.categoryEncoding)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var category = _step3.value;
var vals = param.categoryEncoding[category];
if (!Array.isArray(vals)) {
vals = [vals];
}
map.set(category, vals);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
param.categoryEncoding = map;
}
param.__transformDone = true;
}
/**
* Transforms a CoverageJSON NdArray range to the Coverage API format. Transformation is made in-place.
*
* @param {Object} range The original NdArray range.
* @param {Object} [domain] The CoverageJSON domain object.
* @return {Object} The transformed range.
*/
function transformNdArrayRange(range, domain) {
if ('__transformDone' in range) return;
var values = range.values;
if (range.actualMin === undefined) {
var _minMax = covutils.minMax(values);
var _minMax2 = slicedToArray(_minMax, 2);
var min = _minMax2[0];
var max = _minMax2[1];
if (min !== null) {
range.actualMin = min;
range.actualMax = max;
}
}
// store the array as we will expose a Map on range.shape in the next step
if (range.shape) {
range._shape = range.shape;
}
if (range.axisNames) {
// not part of public API
range._axisNames = range.axisNames;
delete range.axisNames;
}
var axisNames = getRangeAxisOrder(domain, range);
var shapeArr = getRangeShapeArray(domain, range);
var ndarr = ndarray(values, shapeArr);
range._ndarr = ndarr;
range.get = createRangeGetFunction(ndarr, axisNames);
range.shape = new Map(axisNames.map(function (v, i) {
return [v, shapeArr[i]];
}));
range.__transformDone = true;
return range;
}
/**
*
* @param axisOrder An array of axis names.
* @returns Function
*/
function createRangeGetFunction(ndarr, axisOrder) {
// see below for slower reference version
var ndargs = '';
for (var i = 0; i < axisOrder.length; i++) {
if (ndargs) ndargs += ',';
ndargs += '\'' + axisOrder[i] + '\' in obj ? obj[\'' + axisOrder[i] + '\'] : 0';
}
var fn = new Function('ndarr', 'return function ndarrget (obj) { return ndarr.get(' + ndargs + ') }')(ndarr);
return fn;
}
/*
* Reference version of createRangeGetFunction().
* Around 50% slower (on Chrome 46) compared to precompiled version.
*
function createRangeGetFunction (ndarr, axisOrder) {
axisOrder = axisOrder.slice() // help the JIT (possibly..)
const axisCount = axisOrder.length
return obj => {
let indices = new Array(axisCount)
for (let i=0; i < axisCount; i++) {
indices[i] = axisOrder[i] in obj ? obj[axisOrder[i]] : 0
}
return ndarr.get(...indices)
}
}
*/
/**
* Transforms a CoverageJSON domain to the Coverage API format.
* Transformation is made in-place.
*
* @param {Object} domain The original domain object.
* @param {Array} [referencing] Referencing info to inject.
* @return {Object} The transformed domain object.
* @access private
*/
function transformDomain(domain, referencing, domainType) {
if ('__transformDone' in domain) return;
domainType = domain.domainType || domainType;
if (domainType && domainType.indexOf(':') === -1) {
domainType = DOMAINTYPES_PREFIX + domainType;
}
domain.domainType = domainType;
var axes = new Map(); // axis name -> axis object
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = Object.keys(domain.axes)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var axisName = _step4.value;
axes.set(axisName, domain.axes[axisName]);
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
domain.axes = axes;
// expand start/stop/num regular axes
// replace 1D numeric axis arrays with typed arrays for efficiency
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = axes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var _step5$value = slicedToArray(_step5.value, 2);
var key = _step5$value[0];
var axis = _step5$value[1];
axis.key = key;
if (axis.dataType && axis.dataType.indexOf(':') === -1) {
axis.dataType = CORE_PREFIX + axis.dataType;
}
// TODO remove this if-block later, just here for backwards-compatibility
if (axis.components) {
axis.coordinates = axis.components;
}
if (!axis.coordinates) {
axis.coordinates = [key];
}
// TODO remove this line later, just here for backwards-compatibility
axis.components = axis.coordinates;
if ('start' in axis && 'stop' in axis && 'num' in axis) {
var arr = new Float64Array(axis.num);
var step = void 0;
if (axis.num === 1) {
if (axis.start !== axis.stop) {
throw new Error('regular axis of length 1 must have equal start/stop values');
}
step = 0;
} else {
step = (axis.stop - axis.start) / (axis.num - 1);
}
for (var i = 0; i < axis.num; i++) {
arr[i] = axis.start + i * step;
}
axis.values = arr;
delete axis.start;
delete axis.stop;
delete axis.num;
}
if (Array.isArray(axis.values) && typeof axis.values[0] === 'number') {
var _arr = new Float64Array(axis.values.length);
for (var _i = 0; _i < axis.values.length; _i++) {
_arr[_i] = axis.values[_i];
}
axis.values = _arr;
}
axis.bounds = wrapBounds(axis);
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
if (referencing) {
domain.referencing = referencing;
}
// TODO remove this later, just here for backwards-compatibility
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = domain.referencing[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var obj = _step6.value;
if (obj.components) {
obj.coordinates = obj.components;
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
if (domain.rangeAxisOrder) {
domain._rangeAxisOrder = domain.rangeAxisOrder;
delete domain.rangeAxisOrder;
}
domain.__transformDone = true;
return domain;
}
/**
* Applies the local index subset constraints to the existing global constraints.
* Both constraint objects must be normalized, that is, must contain the same axes
* as start/stop/step objects.
*
* @example
* var local = {x: {start: 0, stop: 50, step: 2}}
* var global = {x: {start: 500, stop: 1000}}
* var newGlobal = toGlobalSubsetConstraints(local, global)
* // newGlobal == {x: {start: 500, stop: 550, step: 2}}
*
* @example
* var local = {x: {start: 5, stop: 10, step: 2}} // 5, 7, 9
* var global = {x: {start: 500, stop: 1000, step: 10}} // 500, 510, 520,...
* var newGlobal = toGlobalSubsetConstraints(local, global)
* // newGlobal == {x: {start: 550, stop: 600, step: 20}} // 550, 570, 590
*/
function toGlobalSubsetConstraints(localConstraints) {
var globalConstraints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var res = {};
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = Object.keys(localConstraints)[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var axis = _step7.value;
var local = localConstraints[axis];
var _ref2 = globalConstraints[axis] || {};
var _ref2$start = _ref2.start;
var globalStart = _ref2$start === undefined ? 0 : _ref2$start;
var _ref2$step = _ref2.step;
var globalStep = _ref2$step === undefined ? 1 : _ref2$step;
res[axis] = {
start: globalStart + globalStep * local.start,
stop: globalStart + globalStep * local.stop,
step: globalStep * local.step
};
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
return res;
}
function wrapBounds(axis) {
if (axis.bounds) {
var _ret2 = function () {
var bounds = axis.bounds;
return {
v: {
get: function get(i) {
return [bounds[2 * i], bounds[2 * i + 1]];
}
}
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
}
}
/**
* @external {CollectionQuery} https://github.com/Reading-eScience-Centre/coverage-jsapi/blob/master/CoverageCollectionQuery.md
*/
/**
* Wraps a CoverageJSON Collection object as a CoverageCollection API object.
*
* @see https://github.com/Reading-eScience-Centre/coverage-jsapi
*
*/
var CoverageCollection = function () {
/**
* @param {Object} covjson The CoverageJSON Collection document.
*/
function CoverageCollection(covjson) {
classCallCheck(this, CoverageCollection);
/**
* The constant "CoverageCollection".
*
* @type {string}
*/
this.type = covutils.COVERAGECOLLECTION;
/**
* JSON-LD document
*
* @type {Object}
*/
this.ld = {};
this._exposeLd(covjson);
this.prefixes = getNamespacePrefixes(this.ld);
/**
* ID of the coverage collection.
*
* @type {string|undefined}
*/
this.id = covjson.id;
var domainType = covjson.domainType;
if (domainType && domainType.indexOf(':') === -1) {
domainType = DOMAINTYPES_PREFIX + domainType;
}
/**
* If defined, every coverage in the collection has the given domain type, typically a URI.
*
* @type {string|undefined}
*/
this.domainType = domainType;
var covs = [];
var rootParams = covjson.parameters ? covjson.parameters : {};
// generate local parameter IDs if not existing
// this is to keep track of same parameters when copied into the coverages
// (e.g. to synchronize legends etc.)
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(rootParams)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _key = _step.value;
var param = rootParams[_key];
if (!param.id) {
param.id = Math.round(new Date().getTime() * Math.random()).toString();
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var covOptions = {};
if (covjson.referencing) {
covOptions.referencing = covjson.referencing;
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = covjson.coverages[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var coverage = _step2.value;
if (!coverage.domainType) {
coverage.domainType = domainType;
}
if (!coverage.parameters) {
coverage.parameters = {};
}
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = Object.keys(rootParams)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var _key2 = _step4.value;
if (_key2 in coverage.ranges) {
coverage.parameters[_key2] = rootParams[_key2];
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
if (covjson['@context']) {
coverage['@context'] = covjson['@context'];
}
covs.push(new Coverage(coverage, covOptions));
}
/**
* The Coverages of this collection.
*
* @type {Array<Coverage>}
*/
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.coverages = covs;
if (covjson.parameters) {
/**
* A Map from key to {@link Parameter} object.
* The key is a short alias of a {@link Parameter}, typically what is called a "variable name" or similar.
*
* @type {Map<string,Parameter>}
*/
this.parameters = new Map();
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = Object.keys(covjson.parameters)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var key = _step3.value;
transformParameter(covjson.parameters, key);
this.parameters.set(key, covjson.parameters[key]);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
if (covjson.domainTemplate) {
transformDomain(covjson.domainTemplate);
/**
* @ignore
*/
this.domainTemplate = covjson.domainTemplate;
}
}
/**
*
* @return {CollectionQuery}
*/
createClass(CoverageCollection, [{
key: 'query',
value: function query() {
return new covutils.CollectionQuery(this);
}
}, {
key: '_exposeLd',
value: function _exposeLd(covjson) {
if (!covjson['@context']) {
// no LD love here...
return;
}
// make a deep copy since the object gets modified in-place later
// but first, remove the coverages (those have their own .ld property)
var copy = shallowcopy(covjson);
delete copy.coverages;
this.ld = JSON.parse(JSON.stringify(copy));
}
}]);
return CoverageCollection;
}();
// NO FILE EXTENSION, to work around JSPM bug in handling package.json's "browser" field
// see https://github.com/jspm/jspm-cli/issues/1062#issuecomment-170342414
/**
* Loads a CoverageJSON document from a given URL and returns a {@link Promise} object
* that succeeds with the unmodified CoverageJSON object.
*
* @param {string} url The URL to load the CoverageJSON document from.
* @param {Object} [options] An options object.
* @param {Object} [options.headers] Additional HTTP headers to send if input is a URL.
* @param {Object} [options.eagerload]
* Request a stand-alone CoverageJSON document (with domain and ranges embedded) if input is a URL.
* Note that the server may ignore that preference.
* @return {Promise}
* A Promise succeeding with an object <code>{data, headers}</code> where data is the CoverageJSON object
* and headers are the HTTP response headers with lower-cased header names as object keys.
* The promise fails if the resource at the given URL is not a valid JSON or CBOR document.
*/
function load$$1(url, options) {
return load$1(url, options);
}
/**
* Reads a CoverageJSON document and returns a {@link Promise} that succeeds with
* a Domain, {@link Coverage}, or {@link CoverageCollection} object.
*
* Note that if the document references external domain or range documents,
* then these are not loaded immediately.
*
*
* @example
* CovJSON.read('http://example.com/coverage.covjson').then(function (cov) {
* // work with Coverage data object
* }).catch(function (e) {
* // there was an error when loading the coverage data
* console.log(e)
* })
* @param {Object|string} input
* A CoverageJSON Domain, Coverage, or Coverage Collection document, as URL or object.
* @param {Object} [options]
* An options object.
* @param {Object} [options.headers]
* Additional HTTP headers to send if input is a URL.
* @param {Object} [options.eagerload]
* Request a stand-alone CoverageJSON document (with domain and ranges embedded) if input is a URL.
* Note that the server may ignore that preference.
* @return {Promise}
* A promise object succeeding with a Domain, {@link Coverage}, or {@link CoverageCollection} object,
* and failing with an {@link Error} object.
*/
function read(input) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object') {
return Promise.resolve().then(function () {
return transformCovJSON(input);
});
} else {
return load$$1(input, options).then(function (_ref) {
var data = _ref.data;
var headers = _ref.headers;
return transformCovJSON(data, headers);
});
}
}
/**
* Transforms a CoverageJSON object into one or more Coverage objects.
*
* @param {object} obj A CoverageJSON object of type Coverage or CoverageCollection.
* @param {array} headers An optional array of HTTP headers. Keys are lower-cased header names.
* @return {Coverage|Array of Coverage}
*/
function transformCovJSON(obj, headers) {
checkValidCovJSON(obj);
if ([covutils.COVERAGE, covutils.COVERAGECOLLECTION, covutils.DOMAIN].indexOf(obj.type) === -1) {
throw new Error('CoverageJSON document must be of Coverage, CoverageCollection, or Domain type');
}
var result = void 0;
if (obj.type === covutils.DOMAIN) {
transformDomain(obj);
result = obj;
} else if (obj.type === covutils.COVERAGE) {
result = new Coverage(obj);
} else {
result = new CoverageCollection(obj);
}
if (obj.type === covutils.COVERAGE || obj.type === covutils.COVERAGECOLLECTION) {
addLinkRelations(result, headers);
}
return result;
}
/**
* Scans the supplied HTTP headers for Link relations and adds them
* to the .ld property of the Coverage/CoverageCollection.
*/
function addLinkRelations(cov, headers) {
if (!headers || !headers['link']) {
return;
}
var ld = cov.ld;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = headers['link'].split(',')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var link = _step.value;
link = link.trim();
// FIXME this will fail if the URL contains a ";" which is valid (see RFC5988)
var parts = link.split(';');
var url = parts[0].substr(1, parts[0].length - 2);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = parts.slice(1)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var param = _step2.value;
var relStart = param.indexOf('rel=');
if (relStart === -1) {
continue;
}
var rel = param.substring(relStart + 5, param.length - 1);
if (rel.indexOf('http://') !== 0 && rel.indexOf('https://') !== 0) {
rel = LINKRELPREFIX + rel;
}
if (ld[rel]) {
if (Array.isArray(ld[rel])) {
ld[rel].push(url);
} else {
ld[rel] = [ld[rel], url];
}
} else {
ld[rel] = url;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
/**
* Performs basic structural checks to validate whether a given object is a CoverageJSON object.
*
* Note that this method is not comprehensive and should not be used for checking
* whether an object fully conforms to the CoverageJSON specification.
*
* @param obj
* @throws {Error} when obj is not a valid CoverageJSON document
*/
function checkValidCovJSON(obj) {
assert('type' in obj, '"type" missing');
if (obj.type === covutils.COVERAGE) {
assert('parameters' in obj, '"parameters" missing');
assert('domain' in obj, '"domain" missing');
assert('ranges' in obj, '"ranges" missing');
} else if (obj.type === covutils.COVERAGECOLLECTION) {
assert(Array.isArray(obj.coverages), '"coverages" must be an array');
}
}
exports.load = load$$1;
exports.read = read;
}((this.CovJSON = this.CovJSON || {}),CovUtils));
//# sourceMappingURL=covjson-reader.src.js.map
|
'use strict';
// Angular E2E Testing Guide:
// https://docs.angularjs.org/guide/e2e-testing
describe('PhoneCat Application', function() {
it('should redirect `index.html` to `index.html#!/phones', function() {
browser.get('index.html');
expect(browser.getLocationAbsUrl()).toBe('/phones');
});
describe('View: Phone list', function() {
beforeEach(function() {
browser.get('index.html#!/phones');
});
it('should filter the phone list as a user types into the search box', function() {
var phoneList = element.all(by.repeater('phone in $ctrl.phones'));
var query = element(by.model('$ctrl.query'));
expect(phoneList.count()).toBe(20);
query.sendKeys('nexus');
expect(phoneList.count()).toBe(1);
query.clear();
query.sendKeys('motorola');
expect(phoneList.count()).toBe(8);
});
it('should be possible to control phone order via the drop-down menu', function() {
var queryField = element(by.model('$ctrl.query'));
var orderSelect = element(by.model('$ctrl.orderProp'));
var nameOption = orderSelect.element(by.css('option[value="name"]'));
var phoneNameColumn = element.all(by.repeater('phone in $ctrl.phones').column('phone.name'));
function getNames() {
return phoneNameColumn.map(function(elem) {
return elem.getText();
});
}
queryField.sendKeys('tablet'); // Let's narrow the dataset to make the assertions shorter
expect(getNames()).toEqual([
'Motorola XOOM\u2122 with Wi-Fi',
'MOTOROLA XOOM\u2122'
]);
nameOption.click();
expect(getNames()).toEqual([
'MOTOROLA XOOM\u2122',
'Motorola XOOM\u2122 with Wi-Fi'
]);
});
it('should render phone specific links', function() {
var query = element(by.model('$ctrl.query'));
query.sendKeys('nexus');
element.all(by.css('.phones li a')).first().click();
expect(browser.getLocationAbsUrl()).toBe('/phones/nexus-s');
});
});
describe('View: Phone detail', function() {
beforeEach(function() {
browser.get('index.html#!/phones/nexus-s');
});
it('should display the `nexus-s` page', function() {
expect(element(by.binding('$ctrl.phone.name')).getText()).toBe('Nexus S');
});
it('should display the first phone image as the main phone image', function() {
var mainImage = element(by.css('img.phone.selected'));
expect(mainImage.getAttribute('src')).toMatch(/img\/phones\/nexus-s.0.jpg/);
});
it('should swap the main image when clicking on a thumbnail image', function() {
var mainImage = element(by.css('img.phone.selected'));
var thumbnails = element.all(by.css('.phone-thumbs img'));
thumbnails.get(2).click();
expect(mainImage.getAttribute('src')).toMatch(/img\/phones\/nexus-s.2.jpg/);
thumbnails.get(0).click();
expect(mainImage.getAttribute('src')).toMatch(/img\/phones\/nexus-s.0.jpg/);
});
});
});
|
/**
* @author mrdoob / http://mrdoob.com/
*/
var Script = function ( editor ) {
var signals = editor.signals;
var container = new UI.Panel();
container.setId( 'script' );
container.setPosition( 'absolute' );
container.setBackgroundColor( '#272822' );
container.setDisplay( 'none' );
var header = new UI.Panel();
header.setPadding( '10px' );
container.add( header );
var title = new UI.Text().setColor( '#fff' );
header.add( title );
var buttonSVG = ( function () {
var svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
svg.setAttribute( 'width', 32 );
svg.setAttribute( 'height', 32 );
var path = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
path.setAttribute( 'd', 'M 12,12 L 22,22 M 22,12 12,22' );
path.setAttribute( 'stroke', '#fff' );
svg.appendChild( path );
return svg;
} )();
var close = new UI.Element( buttonSVG );
close.setPosition( 'absolute' );
close.setTop( '3px' );
close.setRight( '1px' );
close.setCursor( 'pointer' );
close.onClick( function () {
container.setDisplay( 'none' );
} );
header.add( close );
var renderer;
signals.rendererChanged.add( function ( newRenderer ) {
renderer = newRenderer;
} );
var delay;
var currentMode;
var currentScript;
var currentObject;
var codemirror = CodeMirror( container.dom, {
value: '',
lineNumbers: true,
matchBrackets: true,
indentWithTabs: true,
tabSize: 4,
indentUnit: 4,
hintOptions: {
completeSingle: false
}
} );
codemirror.setOption( 'theme', 'monokai' );
codemirror.on( 'change', function () {
if ( codemirror.state.focused === false ) return;
clearTimeout( delay );
delay = setTimeout( function () {
var value = codemirror.getValue();
if ( ! validate( value ) ) return;
if ( typeof( currentScript ) === 'object' ) {
if ( value !== currentScript.source ) {
editor.execute( new SetScriptValueCommand( currentObject, currentScript, 'source', value ) );
}
return;
}
if ( currentScript !== 'programInfo' ) return;
var json = JSON.parse( value );
if ( JSON.stringify( currentObject.material.defines ) !== JSON.stringify( json.defines ) ) {
var cmd = new SetMaterialValueCommand( currentObject, 'defines', json.defines );
cmd.updatable = false;
editor.execute( cmd );
}
if ( JSON.stringify( currentObject.material.uniforms ) !== JSON.stringify( json.uniforms ) ) {
var cmd = new SetMaterialValueCommand( currentObject, 'uniforms', json.uniforms );
cmd.updatable = false;
editor.execute( cmd );
}
if ( JSON.stringify( currentObject.material.attributes ) !== JSON.stringify( json.attributes ) ) {
var cmd = new SetMaterialValueCommand( currentObject, 'attributes', json.attributes );
cmd.updatable = false;
editor.execute( cmd );
}
}, 300 );
});
// prevent backspace from deleting objects
var wrapper = codemirror.getWrapperElement();
wrapper.addEventListener( 'keydown', function ( event ) {
event.stopPropagation();
} );
// validate
var errorLines = [];
var widgets = [];
var validate = function ( string ) {
var valid;
var errors = [];
return codemirror.operation( function () {
while ( errorLines.length > 0 ) {
codemirror.removeLineClass( errorLines.shift(), 'background', 'errorLine' );
}
while ( widgets.length > 0 ) {
codemirror.removeLineWidget( widgets.shift() );
}
//
switch ( currentMode ) {
case 'javascript':
try {
var syntax = esprima.parse( string, { tolerant: true } );
errors = syntax.errors;
} catch ( error ) {
errors.push( {
lineNumber: error.lineNumber - 1,
message: error.message
} );
}
for ( var i = 0; i < errors.length; i ++ ) {
var error = errors[ i ];
error.message = error.message.replace(/Line [0-9]+: /, '');
}
break;
case 'json':
errors = [];
jsonlint.parseError = function ( message, info ) {
message = message.split('\n')[3];
errors.push( {
lineNumber: info.loc.first_line - 1,
message: message
} );
};
try {
jsonlint.parse( string );
} catch ( error ) {
// ignore failed error recovery
}
break;
case 'glsl':
try {
var shaderType = currentScript === 'vertexShader' ?
glslprep.Shader.VERTEX : glslprep.Shader.FRAGMENT;
glslprep.parseGlsl( string, shaderType );
} catch( error ) {
if ( error instanceof glslprep.SyntaxError ) {
errors.push( {
lineNumber: error.line,
message: "Syntax Error: " + error.message
} );
} else {
console.error( error.stack || error );
}
}
if ( errors.length !== 0 ) break;
if ( renderer instanceof THREE.WebGLRenderer === false ) break;
currentObject.material[ currentScript ] = string;
currentObject.material.needsUpdate = true;
signals.materialChanged.dispatch( currentObject.material );
var programs = renderer.info.programs;
valid = true;
var parseMessage = /^(?:ERROR|WARNING): \d+:(\d+): (.*)/g;
for ( var i = 0, n = programs.length; i !== n; ++ i ) {
var diagnostics = programs[i].diagnostics;
if ( diagnostics === undefined ||
diagnostics.material !== currentObject.material ) continue;
if ( ! diagnostics.runnable ) valid = false;
var shaderInfo = diagnostics[ currentScript ];
var lineOffset = shaderInfo.prefix.split(/\r\n|\r|\n/).length;
while ( true ) {
var parseResult = parseMessage.exec( shaderInfo.log );
if ( parseResult === null ) break;
errors.push( {
lineNumber: parseResult[ 1 ] - lineOffset,
message: parseResult[ 2 ]
} );
} // messages
break;
} // programs
} // mode switch
for ( var i = 0; i < errors.length; i ++ ) {
var error = errors[ i ];
var message = document.createElement( 'div' );
message.className = 'esprima-error';
message.textContent = error.message;
var lineNumber = Math.max( error.lineNumber, 0 );
errorLines.push( lineNumber );
codemirror.addLineClass( lineNumber, 'background', 'errorLine' );
var widget = codemirror.addLineWidget( lineNumber, message );
widgets.push( widget );
}
return valid !== undefined ? valid : errors.length === 0;
});
};
// tern js autocomplete
var server = new CodeMirror.TernServer( {
caseInsensitive: true,
plugins: { threejs: null }
} );
codemirror.setOption( 'extraKeys', {
'Ctrl-Space': function(cm) { server.complete(cm); },
'Ctrl-I': function(cm) { server.showType(cm); },
'Ctrl-O': function(cm) { server.showDocs(cm); },
'Alt-.': function(cm) { server.jumpToDef(cm); },
'Alt-,': function(cm) { server.jumpBack(cm); },
'Ctrl-Q': function(cm) { server.rename(cm); },
'Ctrl-.': function(cm) { server.selectName(cm); }
} );
codemirror.on( 'cursorActivity', function( cm ) {
if ( currentMode !== 'javascript' ) return;
server.updateArgHints( cm );
} );
codemirror.on( 'keypress', function( cm, kb ) {
if ( currentMode !== 'javascript' ) return;
var typed = String.fromCharCode( kb.which || kb.keyCode );
if ( /[\w\.]/.exec( typed ) ) {
server.complete( cm );
}
} );
//
signals.editorCleared.add( function () {
container.setDisplay( 'none' );
} );
signals.editScript.add( function ( object, script ) {
var mode, name, source;
if ( typeof( script ) === 'object' ) {
mode = 'javascript';
name = script.name;
source = script.source;
title.setValue( object.name + ' / ' + name );
} else {
switch ( script ) {
case 'vertexShader':
mode = 'glsl';
name = 'Vertex Shader';
source = object.material.vertexShader || "";
break;
case 'fragmentShader':
mode = 'glsl';
name = 'Fragment Shader';
source = object.material.fragmentShader || "";
break;
case 'programInfo':
mode = 'json';
name = 'Program Properties';
var json = {
defines: object.material.defines,
uniforms: object.material.uniforms,
attributes: object.material.attributes
};
source = JSON.stringify( json, null, '\t' );
}
title.setValue( object.material.name + ' / ' + name );
}
currentMode = mode;
currentScript = script;
currentObject = object;
container.setDisplay( '' );
codemirror.setValue( source );
codemirror.clearHistory();
if ( mode === 'json' ) mode = { name: 'javascript', json: true };
codemirror.setOption( 'mode', mode );
} );
signals.scriptRemoved.add( function ( script ) {
if ( currentScript === script ) {
container.setDisplay( 'none' );
}
} );
return container;
};
|
// VexFlow - Trill Tests
Vex.Flow.Test.GraceNote = {};
Vex.Flow.Test.GraceNote.Start = function() {
module("Grace Notes");
Vex.Flow.Test.runTest("Grace Note Basic", Vex.Flow.Test.GraceNote.basic);
Vex.Flow.Test.runTest("Grace Note Basic with Slurs", Vex.Flow.Test.GraceNote.basicSlurred);
Vex.Flow.Test.runTest("Grace Notes Multiple Voices", Vex.Flow.Test.GraceNote.multipleVoices);
}
Vex.Flow.Test.GraceNote.helper = function(options, contextBuilder, ctxWidth, staveWidth){
var ctx = contextBuilder(options.canvas_sel, ctxWidth, 130);
ctx.scale(1.0, 1.0); ctx.fillStyle = "#221"; ctx.strokeStyle = "#221";
var stave = new Vex.Flow.Stave(10, 10, staveWidth).addClef("treble").setContext(ctx).draw();
return {
ctx: ctx,
stave: stave,
newNote: function newNote(note_struct) {
return new Vex.Flow.StaveNote(note_struct);
}
};
};
Vex.Flow.Test.GraceNote.basic = function(options, contextBuilder) {
var measure = new Vex.Flow.Test.GraceNote.helper(options, contextBuilder, 700, 650);
var note0 = new Vex.Flow.StaveNote({ keys: ["b/4"], duration: "4", auto_stem: true });
var note1 = new Vex.Flow.StaveNote({ keys: ["c/5"], duration: "4", auto_stem: true });
var note2 = new Vex.Flow.StaveNote({ keys: ["c/5", "d/5"], duration: "4", auto_stem: true });
var note3 = new Vex.Flow.StaveNote({ keys: ["a/4"], duration: "4", auto_stem: true });
var note4 = new Vex.Flow.StaveNote({ keys: ["a/4"], duration: "4", auto_stem: true });
var note5 = new Vex.Flow.StaveNote({ keys: ["a/4"], duration: "4", auto_stem: true });
note1.addAccidental(0, new Vex.Flow.Accidental("#"));
var gracenote_group0 = [
{ keys: ["e/4"], duration: "32"},
{ keys: ["f/4"], duration: "32"},
{ keys: ["g/4"], duration: "32"},
{ keys: ["a/4"], duration: "32"}
];
var gracenote_group1 = [
{ keys: ["b/4"], duration: "8", slash: false}
];
var gracenote_group2 = [
{ keys: ["b/4"], duration: "8", slash: true}
];
var gracenote_group3 = [
{ keys: ["e/4"], duration: "8"},
{ keys: ["f/4"], duration: "16"},
{ keys: ["g/4", "e/4"], duration: "8"},
{ keys: ["a/4"], duration: "32"},
{ keys: ["b/4"], duration: "32"}
];
var gracenote_group4 = [
{ keys: ["g/4"], duration: "8"},
{ keys: ["g/4"], duration: "16"},
{ keys: ["g/4"], duration: "16"}
];
function createNote(note_prop) {
return new Vex.Flow.GraceNote(note_prop);
}
var gracenotes = gracenote_group0.map(createNote);
var gracenotes1 = gracenote_group1.map(createNote);
var gracenotes2 = gracenote_group2.map(createNote);
var gracenotes3 = gracenote_group3.map(createNote);
var gracenotes4 = gracenote_group4.map(createNote);
gracenotes[1].addAccidental(0, new Vex.Flow.Accidental('##'));
gracenotes3[3].addAccidental(0, new Vex.Flow.Accidental('bb'));
gracenotes4[0].addDotToAll();
note0.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes).beamNotes());
note1.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes1).beamNotes());
note2.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes2).beamNotes());
note3.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes3).beamNotes());
note4.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes4).beamNotes());
Vex.Flow.Formatter.FormatAndDraw(measure.ctx, measure.stave, [note0, note1, note2, note3, note4], 0);
ok(true, "GraceNoteBasic");
}
Vex.Flow.Test.GraceNote.basicSlurred = function(options, contextBuilder) {
var measure = new Vex.Flow.Test.GraceNote.helper(options, contextBuilder, 700, 650);
var note0 = new Vex.Flow.StaveNote({ keys: ["b/4"], duration: "4", auto_stem: true });
var note1 = new Vex.Flow.StaveNote({ keys: ["c/5"], duration: "4", auto_stem: true });
var note2 = new Vex.Flow.StaveNote({ keys: ["c/5", "d/5"], duration: "4", auto_stem: true });
var note3 = new Vex.Flow.StaveNote({ keys: ["a/4"], duration: "4", auto_stem: true });
var note4 = new Vex.Flow.StaveNote({ keys: ["a/4"], duration: "4", auto_stem: true });
var note5 = new Vex.Flow.StaveNote({ keys: ["a/4"], duration: "4", auto_stem: true });
note1.addAccidental(0, new Vex.Flow.Accidental("#"));
var gracenote_group0 = [
{ keys: ["e/4"], duration: "32"},
{ keys: ["f/4"], duration: "32"},
{ keys: ["g/4"], duration: "32"},
{ keys: ["a/4"], duration: "32"}
];
var gracenote_group1 = [
{ keys: ["b/4"], duration: "8", slash: false}
];
var gracenote_group2 = [
{ keys: ["b/4"], duration: "8", slash: true}
];
var gracenote_group3 = [
{ keys: ["e/4"], duration: "8"},
{ keys: ["f/4"], duration: "16"},
{ keys: ["g/4", "e/4"], duration: "8"},
{ keys: ["a/4"], duration: "32"},
{ keys: ["b/4"], duration: "32"}
];
var gracenote_group4 = [
{ keys: ["a/4"], duration: "8"},
{ keys: ["a/4"], duration: "16"},
{ keys: ["a/4"], duration: "16"}
];
function createNote(note_prop) {
return new Vex.Flow.GraceNote(note_prop);
}
var gracenotes = gracenote_group0.map(createNote);
var gracenotes1 = gracenote_group1.map(createNote);
var gracenotes2 = gracenote_group2.map(createNote);
var gracenotes3 = gracenote_group3.map(createNote);
var gracenotes4 = gracenote_group4.map(createNote);
gracenotes[1].addAccidental(0, new Vex.Flow.Accidental('#'));
gracenotes3[3].addAccidental(0, new Vex.Flow.Accidental('b'));
gracenotes3[2].addAccidental(0, new Vex.Flow.Accidental('n'));
gracenotes4[0].addDotToAll();
note0.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes, true).beamNotes());
note1.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes1, true).beamNotes());
note2.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes2, true).beamNotes());
note3.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes3, true).beamNotes());
note4.addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes4, true).beamNotes());
Vex.Flow.Formatter.FormatAndDraw(measure.ctx, measure.stave, [note0, note1, note2, note3, note4], 0);
ok(true, "GraceNoteBasic");
}
Vex.Flow.Test.GraceNote.multipleVoices = function(options, contextBuilder) {
options.contextBuilder = contextBuilder;
var context = new options.contextBuilder(options.canvas_sel, 450, 140);
context.scale(0.9, 0.9); context.fillStyle = "#221"; context.strokeStyle = "#221";
context.font = " 10pt Arial";
var stave = new Vex.Flow.Stave(10, 10, 450).addTrebleGlyph().
setContext(context).draw();
function newNote(note_struct) { return new Vex.Flow.StaveNote(note_struct); }
function newAcc(type) { return new Vex.Flow.Accidental(type); }
var notes = [
newNote({ keys: ["f/5"], stem_direction: 1, duration: "16"}),
newNote({ keys: ["f/5"], stem_direction: 1, duration: "16"}),
newNote({ keys: ["d/5"], stem_direction: 1, duration: "16"}),
newNote({ keys: ["c/5"], stem_direction: 1, duration: "16"}),
newNote({ keys: ["c/5"], stem_direction: 1, duration: "16"}),
newNote({ keys: ["d/5"], stem_direction: 1, duration: "16"}),
newNote({ keys: ["f/5"], stem_direction: 1, duration: "16"}),
newNote({ keys: ["e/5"], stem_direction: 1, duration: "16"})
];
var notes2 = [
newNote({ keys: ["f/4"], stem_direction: -1, duration: "16"}),
newNote({ keys: ["e/4"], stem_direction: -1, duration: "16"}),
newNote({ keys: ["d/4"], stem_direction: -1, duration: "16"}),
newNote({ keys: ["c/4"], stem_direction: -1, duration: "16"}),
newNote({ keys: ["c/4"], stem_direction: -1, duration: "16"}),
newNote({ keys: ["d/4"], stem_direction: -1, duration: "16"}),
newNote({ keys: ["f/4"], stem_direction: -1, duration: "16"}),
newNote({ keys: ["e/4"], stem_direction: -1, duration: "16"})
];
function createNote(note_prop) {
return new Vex.Flow.GraceNote(note_prop);
}
var gracenote_group0 = [
{ keys: ["b/4"], duration: "8", slash: true}
];
var gracenote_group1 = [
{ keys: ["f/4"], duration: "8", slash: true}
];
var gracenote_group2 = [
{ keys: ["f/4"], duration: "32", stem_direction: -1},
{ keys: ["e/4"], duration: "32", stem_direction: -1}
];
var gracenotes1 = gracenote_group0.map(createNote);
var gracenotes2 = gracenote_group1.map(createNote);
var gracenotes3 = gracenote_group2.map(createNote);
gracenotes2[0].setStemDirection(-1);
gracenotes2[0].addAccidental(0, new Vex.Flow.Accidental('#'));
notes[3].addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes1));
notes2[1].addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes2).beamNotes());
notes2[5].addModifier(0, new Vex.Flow.GraceNoteGroup(gracenotes3).beamNotes());
var voice = new Vex.Flow.Voice(Vex.Flow.Test.TIME4_4).setStrict(false);
var voice2 = new Vex.Flow.Voice(Vex.Flow.Test.TIME4_4).setStrict(false);
voice.addTickables(notes);
voice2.addTickables(notes2);
var formatter = new Vex.Flow.Formatter().joinVoices([voice, voice2]).
formatToStave([voice, voice2], stave);
var beam1_1 = new Vex.Flow.Beam(notes.slice(0, 4));
var beam1_2 = new Vex.Flow.Beam(notes.slice(4, 8));
var beam2_1 = new Vex.Flow.Beam(notes2.slice(0, 4));
var beam2_2 = new Vex.Flow.Beam(notes2.slice(4, 8));
voice.draw(context, stave);
voice2.draw(context, stave);
beam1_1.setContext(context).draw();
beam1_2.setContext(context).draw();
beam2_1.setContext(context).draw();
beam2_2.setContext(context).draw();
ok(true, "Sixteenth Test");
} |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":6,"../lib/Shim.IE8":30}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param {Object} data The data / document to use for lookups.
* @param {Object} options An options object.
* @param {Operation} op An optional operation instance. Pass undefined
* if not being used.
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, op, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, op, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, op, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, op, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, op, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
//regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; }
resultArr._visitedCount++;
resultArr._visitedNodes = resultArr._visitedNodes || [];
resultArr._visitedNodes.push(thisDataPathVal);
result = this.sortAsc(thisDataPathValSubStr, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":26,"./Shared":29}],3:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
Condition,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
Condition = _dereq_('./Condition');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
* @param {Object=} val The data to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
* @param {Boolean=} val The value to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
* @param {Number=} val The value to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
/**
* Adds a job id to the async queue to signal to other parts
* of the application that some async work is currently being
* done.
* @param {String} key The id of the async job.
* @private
*/
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
/**
* Removes a job id from the async queue to signal to other
* parts of the application that some async work has been
* completed. If no further async jobs exist on the queue then
* the "ready" event is emitted from this collection instance.
* @param {String} key The id of the async job.
* @private
*/
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @param {Function=} callback A callback method to call once the
* operation has completed.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection by updating the
* lastChange timestamp on the collection's metaData. This
* only happens if the changeTimestamp option is enabled
* on the collection (it is disabled by default).
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
*/
'*': function (data) {
return this.$main.call(this, data, {});
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Object} options Optional options object.
*/
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Function} callback Optional callback function.
*/
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {*} options Optional options object.
* @param {Function} callback Optional callback function.
*/
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {*} options Optional options object.
* @param {*} callback Optional callback function.
*/
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Object} options Optional options object.
* @param {Function} callback Optional callback function.
*/
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents
* in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Inserts a new document or updates an existing document in a
* collection depending on if a matching primary key exists in
* the collection already or not.
*
* If the document contains a primary key field (based on the
* collections's primary key) then the database will search for
* an existing document with a matching id. If a matching
* document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with
* new data. Any keys that do not currently exist on the document
* will be added to the document.
*
* If the document does not contain an id or the id passed does
* not match an existing document, an insert is performed instead.
* If no id is present a new primary key id is provided for the
* document and the document is inserted.
*
* @param {Object} obj The document object to upsert or an array
* containing documents to upsert.
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains
* either "insert" or "update" depending on the type of operation
* that was performed and "result" contains the return data from
* the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection.
* This will update all matches for 'query' with the data held
* in 'update'. It will not overwrite the matched documents
* with the update document.
*
* @param {Object} query The query that must be matched for a
* document to be operated on.
* @param {Object} update The object containing updated
* key/values. Any keys that match keys on the existing document
* will be overwritten with this data. Any keys that do not
* currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when
* the update is complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
/**
* Handles the update operation that was initiated by a call to update().
* @param {Object} query The query that must be matched for a
* document to be operated on.
* @param {Object} update The object containing updated
* key/values. Any keys that match keys on the existing document
* will be overwritten with this data. Any keys that do not
* currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when
* the update is complete.
* @returns {Array} The items that were updated.
* @private
*/
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this, updated || []); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
} else {
if (callback) { callback.call(this, updated || []); }
}
} else {
if (callback) { callback.call(this, updated || []); }
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references. It does this by removing existing keys
* from the base object and then adding the passed object's keys to
* the existing base object, thereby maintaining any references to
* the existing base object but effectively replacing the object with
* the new one.
* @param {Object} currentObj The base object to alter.
* @param {Object} newObj The new object to overwrite the existing one
* with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document via it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to
* update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update
* the document with.
* @param {Object} query The query object that we need to match to
* perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform,
* if none is specified default is to set new data against matching
* fields.
* @returns {Boolean} True if the document was updated with new /
* changed data or false if it was not updated because the data was
* the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$splicePull':
// Check that the target key is not undefined
if (doc[i] !== undefined) {
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update[i].$index;
if (tempIndex !== undefined) {
// Check for in bounds index
if (tempIndex < doc[i].length) {
this._updateSplicePull(doc[i], tempIndex);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot splicePull without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePull from a key that is not an array! (' + i + ')');
}
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark
* (a dollar at the end of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search
* query key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Collection~insertCallback=} callback Optional callback called
* once the insert is complete.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* The insert operation's callback.
* @callback Collection~insertCallback
* @param {Object} result The result object will contain two arrays (inserted
* and failed) which represent the documents that did get inserted and those
* that didn't for some reason (usually index violation). Failed items also
* contain a reason. Inspect the failed array for further information.
*
* A third field called "deferred" is a boolean value to indicate if the
* insert operation was deferred across more than one CPU cycle (to avoid
* blocking the main thread).
*/
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Collection~insertCallback=} callback Optional callback called
* once the insert is complete.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed});
this.deferEmit('change', {type: 'insert', data: inserted, failed: failed});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param {String} search The string to search for. Case sensitive.
* @param {Object=} options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
// Now process any $groupBy clause
if (options.$groupBy) {
op.data('flag.group', true);
op.time('group');
resultArr = this.group(options.$groupBy, resultArr);
op.time('group');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
/**
* Groups an array of documents into multiple array fields, named by the value
* of the given group path.
* @param {*} groupObj The key path the array objects should be grouped by.
* @param {Array} arr The array of documents to group.
* @returns {Object}
*/
Collection.prototype.group = function (groupObj, arr) {
// Convert the index object to an array of key val objects
var keys = sharedPathSolver.parse(groupObj, true),
groupPathSolver = new Path(),
groupValue,
groupResult = {},
keyIndex,
i;
if (keys.length) {
for (keyIndex = 0; keyIndex < keys.length; keyIndex++) {
groupPathSolver.path(keys[keyIndex].path);
// Execute group
for (i = 0; i < arr.length; i++) {
groupValue = groupPathSolver.get(arr[i]);
groupResult[groupValue] = groupResult[groupValue] || [];
groupResult[groupValue].push(arr[i]);
}
}
}
return groupResult;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param {String} key The path to sort by.
* @param {Array} arr The array of objects to sort.
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and
* returns an object containing details about the query which
* can be used to optimise the search.
*
* @param {Object} query The search query to analyse.
* @param {Object} options The query options object.
* @param {Operation} op The instance of the Operation class that
* this operation is using to track things like performance and steps
* taken etc.
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options, op);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options, op);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching
* parent documents from which the sub-documents are queried.
* @param {String} path The path string used to identify the
* key in which sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching
* which sub-documents to return.
* @param {Object=} subDocOptions The options object to use
* when querying for sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents
* that matches the subDocQuery parameter.
* @param {Object} match The query object to use when matching
* parent documents from which the sub-documents are queried.
* @param {String} path The path string used to identify the
* key in which sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching
* which sub-documents to return.
* @param {Object=} subDocOptions The options object to use
* when querying for sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
/**
* Creates a condition handler that will react to changes in data on the
* collection.
* @example Create a condition handler that reacts when data changes.
* var coll = db.collection('test'),
* condition = coll.when({_id: 'test1', val: 1})
* .then(function () {
* console.log('Condition met!');
* })
* .else(function () {
* console.log('Condition un-met');
* });
*
* coll.insert({_id: 'test1', val: 1});
*
* @see Condition
* @param {Object} query The query that will trigger the condition's then()
* callback.
* @returns {Condition}
*/
Collection.prototype.when = function (query) {
var queryId = this.objectId();
this._when = this._when || {};
this._when[queryId] = this._when[queryId] || new Condition(this, queryId, query);
return this._when[queryId];
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the
* primary key field on the collection objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the
* primary key field on the collection objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other
* variants and handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or
* regular expression to use to match collection names against.
* @returns {Array} An array of objects containing details of each
* collection the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Condition":5,"./Index2d":9,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],5:[function(_dereq_,module,exports){
"use strict";
/**
* The condition class monitors a data source and updates it's internal
* state depending on clauses that it has been given. When all clauses
* are satisfied the then() callback is fired. If conditions were met
* but data changed that made them un-met, the else() callback is fired.
*/
var //Overload = require('./Overload'),
Shared,
Condition;
Shared = _dereq_('./Shared');
/**
* Create a constructor method that calls the instance's init method.
* This allows the constructor to be overridden by other modules because
* they can override the init method with their own.
*/
Condition = function () {
this.init.apply(this, arguments);
};
Condition.prototype.init = function (dataSource, id, clause) {
this._dataSource = dataSource;
this._id = id;
this._query = [clause];
this._started = false;
this._state = [false];
this._satisfied = false;
// Set this to true by default for faster performance
this.earlyExit(true);
};
// Tell ForerunnerDB about our new module
Shared.addModule('Condition', Condition);
// Mixin some commonly used methods
Shared.mixin(Condition.prototype, 'Mixin.Common');
Shared.mixin(Condition.prototype, 'Mixin.ChainReactor');
Shared.synthesize(Condition.prototype, 'id');
Shared.synthesize(Condition.prototype, 'then');
Shared.synthesize(Condition.prototype, 'else');
Shared.synthesize(Condition.prototype, 'earlyExit');
Shared.synthesize(Condition.prototype, 'debug');
/**
* Adds a new clause to the condition.
* @param {Object} clause The query clause to add to the condition.
* @returns {Condition}
*/
Condition.prototype.and = function (clause) {
this._query.push(clause);
this._state.push(false);
return this;
};
/**
* Starts the condition so that changes to data will call callback
* methods according to clauses being met.
* @param {*} initialState Initial state of condition.
* @returns {Condition}
*/
Condition.prototype.start = function (initialState) {
if (!this._started) {
var self = this;
if (arguments.length !== 0) {
this._satisfied = initialState;
}
// Resolve the current state
this._updateStates();
self._onChange = function () {
self._updateStates();
};
// Create a chain reactor link to the data source so we start receiving CRUD ops from it
this._dataSource.on('change', self._onChange);
this._started = true;
}
return this;
};
/**
* Updates the internal status of all the clauses against the underlying
* data source.
* @private
*/
Condition.prototype._updateStates = function () {
var satisfied = true,
i;
for (i = 0; i < this._query.length; i++) {
this._state[i] = this._dataSource.count(this._query[i]) > 0;
if (this._debug) {
console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]);
}
if (!this._state[i]) {
satisfied = false;
// Early exit since we have found a state that is not true
if (this._earlyExit) {
break;
}
}
}
if (this._satisfied !== satisfied) {
// Our state has changed, fire the relevant operation
if (satisfied) {
// Fire the "then" operation
if (this._then) {
this._then();
}
} else {
// Fire the "else" operation
if (this._else) {
this._else();
}
}
this._satisfied = satisfied;
}
};
/**
* Stops the condition so that callbacks will no longer fire.
* @returns {Condition}
*/
Condition.prototype.stop = function () {
if (this._started) {
this._dataSource.off('change', this._onChange);
delete this._onChange;
this._started = false;
}
return this;
};
/**
* Drops the condition and removes it from memory.
* @returns {Condition}
*/
Condition.prototype.drop = function () {
this.stop();
delete this._dataSource.when[this._id];
return this;
};
// Tell ForerunnerDB that our module has finished loading
Shared.finishModule('Condition');
module.exports = Condition;
},{"./Shared":29}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":7,"./Metrics.js":13,"./Overload":25,"./Shared":29}],7:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - rob@irrelon.com
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders,
PI180 = Math.PI / 180,
PI180R = 180 / Math.PI,
earthRadius = 6371; // mean radius of the earth
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
/**
* Converts degrees to radians.
* @param {Number} degrees
* @return {Number} radians
*/
GeoHash.prototype.radians = function radians (degrees) {
return degrees * PI180;
};
/**
* Converts radians to degrees.
* @param {Number} radians
* @return {Number} degrees
*/
GeoHash.prototype.degrees = function (radians) {
return radians * PI180R;
};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates a new lat/lng by travelling from the center point in the
* bearing specified for the distance specified.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param {Number} distanceKm The distance to travel in kilometers.
* @param {Number} bearing The bearing to travel in degrees (zero is
* north).
* @returns {{lat: Number, lng: Number}}
*/
GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) {
var curLon = centerPoint[1],
curLat = centerPoint[0],
destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))),
tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)),
destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º
return {
lat: this.degrees(destLat),
lng: this.degrees(destLon)
};
};
/**
* Calculates the extents of a bounding box around the center point which
* encompasses the radius in kilometers passed.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param radiusKm Radius in kilometers.
* @returns {{lat: Array, lng: Array}}
*/
GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) {
var maxWest,
maxEast,
maxNorth,
maxSouth,
lat = [],
lng = [];
maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0);
maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90);
maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180);
maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270);
lat[0] = maxNorth.lat;
lat[1] = maxSouth.lat;
lng[0] = maxWest.lng;
lng[1] = maxEast.lng;
return {
lat: lat,
lng: lng
};
};
/**
* Calculates all the geohashes that make up the bounding box that surrounds
* the circle created from the center point and radius passed.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param {Number} radiusKm The radius in kilometers to encompass.
* @param {Number} precision The number of characters to limit the returned
* geohash strings to.
* @returns {Array} The array of geohashes that encompass the bounding box.
*/
GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) {
var extent = this.calculateExtentByRadius(centerPoint, radiusKm),
northWest = [extent.lat[0], extent.lng[0]],
northEast = [extent.lat[0], extent.lng[1]],
southWest = [extent.lat[1], extent.lng[0]],
northWestHash = this.encode(northWest[0], northWest[1], precision),
northEastHash = this.encode(northEast[0], northEast[1], precision),
southWestHash = this.encode(southWest[0], southWest[1], precision),
hash,
widthCount = 0,
heightCount = 0,
widthIndex,
heightIndex,
hashArray = [];
hash = northWestHash;
hashArray.push(hash);
// Walk from north west to north east until we find the north east geohash
while (hash !== northEastHash) {
hash = this.calculateAdjacent(hash, 'right');
widthCount++;
hashArray.push(hash);
}
hash = northWestHash;
// Walk from north west to south west until we find the south west geohash
while (hash !== southWestHash) {
hash = this.calculateAdjacent(hash, 'bottom');
heightCount++;
}
// We now know the width and height in hash boxes of the area, fill in the
// rest of the hashes into the hashArray array
for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) {
hash = hashArray[widthIndex];
for (heightIndex = 0; heightIndex < heightCount; heightIndex++) {
hash = this.calculateAdjacent(hash, 'bottom');
hashArray.push(hash);
}
}
return hashArray;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to a longitude/latitude array.
* The array contains three latitudes and three longitudes. The
* first of each is the lower extent of the geohash bounding box,
* the second is the upper extent and the third is the center
* of the geohash bounding box.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
lat: lat,
lng: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
if (typeof module !== 'undefined') { module.exports = GeoHash; }
},{}],9:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
/**
* Looks up records that match the passed query and options.
* @param query The query to execute.
* @param options A query options object.
* @param {Operation=} op Optional operation instance that allows
* us to provide operation diagnostics and analytics back to the
* main calling instance as the process is running.
* @returns {*}
*/
Index2d.prototype.lookup = function (query, options, op) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options, op));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options, op) {
var self = this,
neighbours,
visitedCount,
visitedNodes,
visitedData,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i + 1;
break;
}
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i + 1;
break;
}
}
}
if (precision === 0) {
precision = 1;
}
// Calculate 9 box geohashes
if (op) { op.time('index2d.calculateHashArea'); }
neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision);
if (op) { op.time('index2d.calculateHashArea'); }
if (op) {
op.data('index2d.near.precision', precision);
op.data('index2d.near.hashArea', neighbours);
op.data('index2d.near.maxDistanceKm', maxDistanceKm);
op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]);
}
// Lookup all matching co-ordinates from the btree
results = [];
visitedCount = 0;
visitedData = {};
visitedNodes = [];
if (op) { op.time('index2d.near.getDocsInsideHashArea'); }
for (i = 0; i < neighbours.length; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visitedData[neighbours[i]] = search;
visitedCount += search._visitedCount;
visitedNodes = visitedNodes.concat(search._visitedNodes);
results = results.concat(search);
}
if (op) {
op.time('index2d.near.getDocsInsideHashArea');
op.data('index2d.near.startsWith', visitedData);
op.data('index2d.near.visitedTreeNodes', visitedNodes);
}
// Work with original data
if (op) { op.time('index2d.near.lookupDocsById'); }
results = this._collection._primaryIndex.lookup(results);
if (op) { op.time('index2d.near.lookupDocsById'); }
if (query.$distanceField) {
// Decouple the results before we modify them
results = this.decouple(results);
}
if (results.length) {
distance = {};
if (op) { op.time('index2d.near.calculateDistanceFromCenter'); }
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
if (query.$distanceField) {
// Options specify a field to add the distance data to
// so add it now
sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371));
}
if (query.$geoHashField) {
// Options specify a field to add the distance data to
// so add it now
sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision));
}
// Add item as it is inside radius distance
finalResults.push(results[i]);
}
}
if (op) { op.time('index2d.near.calculateDistanceFromCenter'); }
// Sort by distance from center
if (op) { op.time('index2d.near.sortResultsByDistance'); }
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
if (op) { op.time('index2d.near.sortResultsByDistance'); }
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.');
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":2,"./GeoHash":8,"./Path":26,"./Shared":29}],10:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options, op) {
return this._btree.lookup(query, options, op);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":2,"./Path":26,"./Shared":29}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":26,"./Shared":29}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk] !== undefined && val[pk] !== null) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":29}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":24,"./Shared":29}],14:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],15:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Gets / sets the flag that will enable / disable chain reactor sending
* from this instance. Chain reactor sending is enabled by default on all
* instances.
* @param {Boolean} val True or false to enable or disable chain sending.
* @returns {*}
*/
chainEnabled: function (val) {
if (val !== undefined) {
this._chainDisabled = !val;
return this;
}
return !this._chainDisabled;
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain && !this._chainDisabled);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain && !this._chainDisabled) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],16:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":25,"./Serialiser":28}],17:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
fired = false,
internalCallback = function () {
if (!fired) {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
fired = true;
}
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
fired = false,
internalCallback = function () {
if (!fired) {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
fired = true;
}
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
var self = this;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event);
});
} else {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
}
return this;
},
'string, function': function (event, listener) {
var self = this,
arr,
index;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event, listener);
});
} else {
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
var self = this;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event, id, listener);
});
} else {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
},
'string, *': function (event, id) {
var self = this;
if (this._emitting) {
this._eventRemovalQueue = this._eventRemovalQueue || [];
this._eventRemovalQueue.push(function () {
self.off(event, id);
});
} else {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
this._emitting = true;
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
this._emitting = false;
this._processRemovalQueue();
return this;
},
/**
* If events are cleared with the off() method while the event emitter is
* actively processing any events then the off() calls get added to a
* queue to be executed after the event emitter is finished. This stops
* errors that might occur by potentially modifying the event queue while
* the emitter is running through them. This method is called after the
* event emitter is finished processing.
* @private
*/
_processRemovalQueue: function () {
var i;
if (this._eventRemovalQueue && this._eventRemovalQueue.length) {
// Execute each removal call
for (i = 0; i < this._eventRemovalQueue.length; i++) {
this._eventRemovalQueue[i]();
}
// Clear the removal queue
this._eventRemovalQueue = [];
}
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":25}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
if (sourceType === 'object' && source === null) {
sourceType = 'null';
}
if (testType === 'object' && test === null) {
testType = 'null';
}
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number' || sourceType === 'null' || testType === 'null') {
// Number or null comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$fastIn':
if (test instanceof Array) {
// Source is a string or number, use indexOf to identify match in array
return test.indexOf(source) !== -1;
} else {
console.log(this.logIdentifier() + ' Cannot use an $fastIn operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],20:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
self.triggerStack = {};
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
/**
* Tells the current instance to fire or ignore all triggers whether they
* are enabled or not.
* @param {Boolean} val Set to true to ignore triggers or false to not
* ignore them.
* @returns {*}
*/
ignoreTriggers: function (val) {
if (val !== undefined) {
this._ignoreTriggers = val;
return this;
}
return this._ignoreTriggers;
},
/**
* Generates triggers that fire in the after phase for all CRUD ops
* that automatically transform data back and forth and keep both
* import and export collections in sync with each other.
* @param {String} id The unique id for this link IO.
* @param {Object} ioData The settings for the link IO.
*/
addLinkIO: function (id, ioData) {
var self = this,
matchAll,
exportData,
importData,
exportTriggerMethod,
importTriggerMethod,
exportTo,
importFrom,
allTypes,
i;
// Store the linkIO
self._linkIO = self._linkIO || {};
self._linkIO[id] = ioData;
exportData = ioData['export'];
importData = ioData['import'];
if (exportData) {
exportTo = self.db().collection(exportData.to);
}
if (importData) {
importFrom = self.db().collection(importData.from);
}
allTypes = [
self.TYPE_INSERT,
self.TYPE_UPDATE,
self.TYPE_REMOVE
];
matchAll = function (data, callback) {
// Match all
callback(false, true);
};
if (exportData) {
// Check for export match method
if (!exportData.match) {
// No match method found, use the match all method
exportData.match = matchAll;
}
// Check for export types
if (!exportData.types) {
exportData.types = allTypes;
}
exportTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
exportData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
exportData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
exportTo.upsert(data, callback);
} else {
// Do remove
exportTo.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (importData) {
// Check for import match method
if (!importData.match) {
// No match method found, use the match all method
importData.match = matchAll;
}
// Check for import types
if (!importData.types) {
importData.types = allTypes;
}
importTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
importData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
importData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
self.upsert(data, callback);
} else {
// Do remove
self.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod);
}
}
if (importData) {
for (i = 0; i < importData.types.length; i++) {
importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod);
}
}
},
/**
* Removes a previously added link IO via it's ID.
* @param {String} id The id of the link IO to remove.
* @returns {boolean} True if successful, false if the link IO
* was not found.
*/
removeLinkIO: function (id) {
var self = this,
linkIO = self._linkIO[id],
exportData,
importData,
importFrom,
i;
if (linkIO) {
exportData = linkIO['export'];
importData = linkIO['import'];
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER);
}
}
if (importData) {
importFrom = self.db().collection(importData.from);
for (i = 0; i < importData.types.length; i++) {
importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER);
}
}
delete self._linkIO[id];
return true;
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response,
typeName,
phaseName;
if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (self.debug()) {
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Check if the trigger is already in the stack, if it is,
// don't fire it again (this is so we avoid infinite loops
// where a trigger triggers another trigger which calls this
// one and so on)
if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) {
// The trigger is already in the stack, do not fire the trigger again
if (self.debug()) {
console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!');
}
continue;
}
// Add the trigger to the stack so we don't go down an endless
// trigger loop
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = true;
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Remove the trigger from the stack
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = false;
// Check the response for a non-expected result (anything other than
// [undefined, true or false] is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":25}],23:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Removes an item from the passed array at the specified index.
* @param {Array} arr The array to remove from.
* @param {Number} index The index of the item to remove.
* @param {Number} count The number of items to remove.
* @private
*/
_updateSplicePull: function (arr, index, count) {
if (!count) { count = 1; }
arr.splice(index, count);
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":26,"./Shared":29}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":29}],27:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":29}],28:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],29:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.829',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Hls = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],2:[function(require,module,exports){
var bundleFn = arguments[3];
var sources = arguments[4];
var cache = arguments[5];
var stringify = JSON.stringify;
module.exports = function (fn) {
var keys = [];
var wkey;
var cacheKeys = Object.keys(cache);
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
var exp = cache[key].exports;
// Using babel as a transpiler to use esmodule, the export will always
// be an object with the default export as a property of it. To ensure
// the existing api and babel esmodule exports are both supported we
// check for both
if (exp === fn || exp.default === fn) {
wkey = key;
break;
}
}
if (!wkey) {
wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var wcache = {};
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
wcache[key] = key;
}
sources[wkey] = [
Function(['require','module','exports'], '(' + fn + ')(self)'),
wcache
];
}
var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var scache = {}; scache[wkey] = wkey;
sources[skey] = [
Function(['require'], (
// try to call default if defined to also support babel esmodule
// exports
'var f = require(' + stringify(wkey) + ');' +
'(f.default ? f.default : f)(self);'
)),
scache
];
var src = '(' + bundleFn + ')({'
+ Object.keys(sources).map(function (key) {
return stringify(key) + ':['
+ sources[key][0]
+ ',' + stringify(sources[key][1]) + ']'
;
}).join(',')
+ '},{},[' + stringify(skey) + '])'
;
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
return new Worker(URL.createObjectURL(
new Blob([src], { type: 'text/javascript' })
));
};
},{}],3:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _bufferHelper = require('../helper/buffer-helper');
var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
var _errors = require('../errors');
var _logger = require('../utils/logger');
var _ewmaBandwidthEstimator = require('./ewma-bandwidth-estimator');
var _ewmaBandwidthEstimator2 = _interopRequireDefault(_ewmaBandwidthEstimator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* simple ABR Controller
* - compute next level based on last fragment bw heuristics
* - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
*/
var AbrController = function (_EventHandler) {
_inherits(AbrController, _EventHandler);
function AbrController(hls) {
_classCallCheck(this, AbrController);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AbrController).call(this, hls, _events2.default.FRAG_LOADING, _events2.default.FRAG_LOADED, _events2.default.ERROR));
_this.lastLoadedFragLevel = 0;
_this._autoLevelCapping = -1;
_this._nextAutoLevel = -1;
_this.hls = hls;
_this.bwEstimator = new _ewmaBandwidthEstimator2.default(hls);
_this.onCheck = _this.abandonRulesCheck.bind(_this);
return _this;
}
_createClass(AbrController, [{
key: 'destroy',
value: function destroy() {
this.clearTimer();
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onFragLoading',
value: function onFragLoading(data) {
if (!this.timer) {
this.timer = setInterval(this.onCheck, 100);
}
var frag = data.frag;
frag.trequest = performance.now();
this.fragCurrent = frag;
}
}, {
key: 'abandonRulesCheck',
value: function abandonRulesCheck() {
/*
monitor fragment retrieval time...
we compute expected time of arrival of the complete fragment.
we compare it to expected time of buffer starvation
*/
var hls = this.hls,
v = hls.media,
frag = this.fragCurrent;
// if loader has been destroyed or loading has been aborted, stop timer and return
if (!frag.loader || frag.loader.stats && frag.loader.stats.aborted) {
_logger.logger.warn('frag loader destroy or aborted, disarm abandonRulesCheck');
this.clearTimer();
return;
}
/* only monitor frag retrieval time if
(video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
if (v && (!v.paused || !v.readyState) && frag.autoLevel && frag.level) {
var requestDelay = performance.now() - frag.trequest;
// monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
if (requestDelay > 500 * frag.duration) {
var levels = hls.levels,
loadRate = Math.max(1, frag.loaded * 1000 / requestDelay),
// byte/s; at least 1 byte/s to avoid division by zero
// compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
expectedLen = Math.max(frag.loaded, Math.round(frag.duration * levels[frag.level].bitrate / 8));
var pos = v.currentTime;
var fragLoadedDelay = (expectedLen - frag.loaded) / loadRate;
var bufferStarvationDelay = _bufferHelper2.default.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos;
// consider emergency switch down only if we have less than 2 frag buffered AND
// time to finish loading current fragment is bigger than buffer starvation delay
// ie if we risk buffer starvation if bw does not increase quickly
if (bufferStarvationDelay < 2 * frag.duration && fragLoadedDelay > bufferStarvationDelay) {
var fragLevelNextLoadedDelay = void 0,
nextLoadLevel = void 0;
// lets iterate through lower level and try to find the biggest one that could avoid rebuffering
// we start from current level - 1 and we step down , until we find a matching level
for (nextLoadLevel = frag.level - 1; nextLoadLevel >= 0; nextLoadLevel--) {
// compute time to load next fragment at lower level
// 0.8 : consider only 80% of current bw to be conservative
// 8 = bits per byte (bps/Bps)
fragLevelNextLoadedDelay = frag.duration * levels[nextLoadLevel].bitrate / (8 * 0.8 * loadRate);
_logger.logger.log('fragLoadedDelay/bufferStarvationDelay/fragLevelNextLoadedDelay[' + nextLoadLevel + '] :' + fragLoadedDelay.toFixed(1) + '/' + bufferStarvationDelay.toFixed(1) + '/' + fragLevelNextLoadedDelay.toFixed(1));
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
// we found a lower level that be rebuffering free with current estimated bw !
break;
}
}
// only emergency switch down if it takes less time to load new fragment at lowest level instead
// of finishing loading current one ...
if (fragLevelNextLoadedDelay < fragLoadedDelay) {
// ensure nextLoadLevel is not negative
nextLoadLevel = Math.max(0, nextLoadLevel);
// force next load level in auto mode
hls.nextLoadLevel = nextLoadLevel;
// update bw estimate for this fragment before cancelling load (this will help reducing the bw)
this.bwEstimator.sample(requestDelay, frag.loaded);
// abort fragment loading ...
_logger.logger.warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel);
//abort fragment loading
frag.loader.abort();
this.clearTimer();
hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag });
}
}
}
}
}
}, {
key: 'onFragLoaded',
value: function onFragLoaded(data) {
var stats = data.stats;
// only update stats on first frag loading
// if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
// and leading to wrong bw estimation
if (stats.aborted === undefined && data.frag.loadCounter === 1) {
this.bwEstimator.sample(performance.now() - stats.trequest, stats.loaded);
}
// stop monitoring bw once frag loaded
this.clearTimer();
// store level id after successful fragment load
this.lastLoadedFragLevel = data.frag.level;
// reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
}
}, {
key: 'onError',
value: function onError(data) {
// stop timer in case of frag loading error
switch (data.details) {
case _errors.ErrorDetails.FRAG_LOAD_ERROR:
case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
}
}, {
key: 'clearTimer',
value: function clearTimer() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
}, {
key: 'autoLevelCapping',
get: function get() {
return this._autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
,
set: function set(newLevel) {
this._autoLevelCapping = newLevel;
}
}, {
key: 'nextAutoLevel',
get: function get() {
var hls = this.hls,
i,
maxAutoLevel,
levels = hls.levels,
config = hls.config;
if (this._autoLevelCapping === -1 && levels && levels.length) {
maxAutoLevel = levels.length - 1;
} else {
maxAutoLevel = this._autoLevelCapping;
}
// in case next auto level has been forced, return it straight-away (but capped)
if (this._nextAutoLevel !== -1) {
return Math.min(this._nextAutoLevel, maxAutoLevel);
}
var avgbw = this.bwEstimator.getEstimate(),
adjustedbw = void 0;
// follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
for (i = 0; i <= maxAutoLevel; i++) {
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (i <= this.lastLoadedFragLevel) {
adjustedbw = config.abrBandWidthFactor * avgbw;
} else {
adjustedbw = config.abrBandWidthUpFactor * avgbw;
}
if (adjustedbw < levels[i].bitrate) {
return Math.max(0, i - 1);
}
}
return i - 1;
},
set: function set(nextLevel) {
this._nextAutoLevel = nextLevel;
}
}]);
return AbrController;
}(_eventHandler2.default);
exports.default = AbrController;
},{"../errors":21,"../event-handler":22,"../events":23,"../helper/buffer-helper":24,"../utils/logger":38,"./ewma-bandwidth-estimator":6}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _logger = require('../utils/logger');
var _errors = require('../errors');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* Buffer Controller
*/
var BufferController = function (_EventHandler) {
_inherits(BufferController, _EventHandler);
function BufferController(hls) {
_classCallCheck(this, BufferController);
// the value that we have set mediasource.duration to
// (the actual duration may be tweaked slighly by the browser)
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(BufferController).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.BUFFER_RESET, _events2.default.BUFFER_APPENDING, _events2.default.BUFFER_CODECS, _events2.default.BUFFER_EOS, _events2.default.BUFFER_FLUSHING, _events2.default.LEVEL_UPDATED));
_this._msDuration = null;
// the value that we want to set mediaSource.duration to
_this._levelDuration = null;
// Source Buffer listeners
_this.onsbue = _this.onSBUpdateEnd.bind(_this);
_this.onsbe = _this.onSBUpdateError.bind(_this);
return _this;
}
_createClass(BufferController, [{
key: 'destroy',
value: function destroy() {
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onMediaAttaching',
value: function onMediaAttaching(data) {
var media = this.media = data.media;
if (media) {
// setup the media source
var ms = this.mediaSource = new MediaSource();
//Media Source listeners
this.onmso = this.onMediaSourceOpen.bind(this);
this.onmse = this.onMediaSourceEnded.bind(this);
this.onmsc = this.onMediaSourceClose.bind(this);
ms.addEventListener('sourceopen', this.onmso);
ms.addEventListener('sourceended', this.onmse);
ms.addEventListener('sourceclose', this.onmsc);
// link video and media Source
media.src = URL.createObjectURL(ms);
}
}
}, {
key: 'onMediaDetaching',
value: function onMediaDetaching() {
var ms = this.mediaSource;
if (ms) {
if (ms.readyState === 'open') {
try {
// endOfStream could trigger exception if any sourcebuffer is in updating state
// we don't really care about checking sourcebuffer state here,
// as we are anyway detaching the MediaSource
// let's just avoid this exception to propagate
ms.endOfStream();
} catch (err) {
_logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
}
}
ms.removeEventListener('sourceopen', this.onmso);
ms.removeEventListener('sourceended', this.onmse);
ms.removeEventListener('sourceclose', this.onmsc);
try {
// unlink MediaSource from video tag
this.media.src = '';
this.media.removeAttribute('src');
} catch (err) {
_logger.logger.warn('onMediaDetaching:' + err.message + ' while unlinking video.src');
}
this.mediaSource = null;
this.media = null;
this.pendingTracks = null;
this.sourceBuffer = null;
}
this.onmso = this.onmse = this.onmsc = null;
this.hls.trigger(_events2.default.MEDIA_DETACHED);
}
}, {
key: 'onMediaSourceOpen',
value: function onMediaSourceOpen() {
_logger.logger.log('media source opened');
this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media });
// once received, don't listen anymore to sourceopen event
this.mediaSource.removeEventListener('sourceopen', this.onmso);
// if any buffer codecs pending, treat it here.
var pendingTracks = this.pendingTracks;
if (pendingTracks) {
this.onBufferCodecs(pendingTracks);
this.pendingTracks = null;
this.doAppending();
}
}
}, {
key: 'onMediaSourceClose',
value: function onMediaSourceClose() {
_logger.logger.log('media source closed');
}
}, {
key: 'onMediaSourceEnded',
value: function onMediaSourceEnded() {
_logger.logger.log('media source ended');
}
}, {
key: 'onSBUpdateEnd',
value: function onSBUpdateEnd() {
if (this._needsFlush) {
this.doFlush();
}
if (this._needsEos) {
this.onBufferEos();
}
this.hls.trigger(_events2.default.BUFFER_APPENDED);
this.doAppending();
}
}, {
key: 'onSBUpdateError',
value: function onSBUpdateError(event) {
_logger.logger.error('sourceBuffer error:' + event);
// according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// this error might not always be fatal (it is fatal if decode error is set, in that case
// it will be followed by a mediaElement error ...)
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
// we don't need to do more than that, as accordin to the spec, updateend will be fired just after
}
}, {
key: 'onBufferReset',
value: function onBufferReset() {
var sourceBuffer = this.sourceBuffer;
if (sourceBuffer) {
for (var type in sourceBuffer) {
var sb = sourceBuffer[type];
try {
this.mediaSource.removeSourceBuffer(sb);
sb.removeEventListener('updateend', this.onsbue);
sb.removeEventListener('error', this.onsbe);
} catch (err) {}
}
this.sourceBuffer = null;
}
this.flushRange = [];
this.appended = 0;
}
}, {
key: 'onBufferCodecs',
value: function onBufferCodecs(tracks) {
var mediaSource = this.mediaSource;
// delay sourcebuffer creation if media source not opened yet
if (!mediaSource || mediaSource.readyState !== 'open') {
this.pendingTracks = tracks;
return;
}
if (!this.sourceBuffer) {
var sourceBuffer = {};
for (var trackName in tracks) {
var track = tracks[trackName];
// use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ';codecs=' + codec;
_logger.logger.log('creating sourceBuffer with mimeType:' + mimeType);
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
sb.addEventListener('updateend', this.onsbue);
sb.addEventListener('error', this.onsbe);
}
this.sourceBuffer = sourceBuffer;
}
}
}, {
key: 'onBufferAppending',
value: function onBufferAppending(data) {
if (!this.segments) {
this.segments = [data];
} else {
this.segments.push(data);
}
this.doAppending();
}
}, {
key: 'onBufferAppendFail',
value: function onBufferAppendFail(data) {
_logger.logger.error('sourceBuffer error:' + data.event);
// according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// this error might not always be fatal (it is fatal if decode error is set, in that case
// it will be followed by a mediaElement error ...)
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false, frag: this.fragCurrent });
}
}, {
key: 'onBufferEos',
value: function onBufferEos() {
var sb = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
return;
}
if (!(sb.audio && sb.audio.updating || sb.video && sb.video.updating)) {
_logger.logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');
//Notify the media element that it now has all of the media data
mediaSource.endOfStream();
this._needsEos = false;
} else {
this._needsEos = true;
}
}
}, {
key: 'onBufferFlushing',
value: function onBufferFlushing(data) {
this.flushRange.push({ start: data.startOffset, end: data.endOffset });
// attempt flush immediatly
this.flushBufferCounter = 0;
this.doFlush();
}
}, {
key: 'onLevelUpdated',
value: function onLevelUpdated(event) {
var details = event.details;
if (details.fragments.length === 0) {
return;
}
this._levelDuration = details.totalduration + details.fragments[0].start;
this.updateMediaElementDuration();
}
// https://github.com/dailymotion/hls.js/issues/355
}, {
key: 'updateMediaElementDuration',
value: function updateMediaElementDuration() {
if (this._levelDuration === null) {
return;
}
var media = this.media;
var mediaSource = this.mediaSource;
if (!media || !mediaSource || media.readyState === 0 || mediaSource.readyState !== 'open') {
return;
}
for (var type in mediaSource.sourceBuffers) {
if (mediaSource.sourceBuffers[type].updating) {
// can't set duration whilst a buffer is updating
return;
}
}
if (this._msDuration === null) {
// initialise to the value that the media source is reporting
this._msDuration = mediaSource.duration;
}
// this._levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update mediasource duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level, as they
if (this._levelDuration > this._msDuration) {
_logger.logger.log('Updating mediasource duration to ' + this._levelDuration);
mediaSource.duration = this._levelDuration;
this._msDuration = this._levelDuration;
}
}
}, {
key: 'doFlush',
value: function doFlush() {
// loop through all buffer ranges to flush
while (this.flushRange.length) {
var range = this.flushRange[0];
// flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
if (this.flushBuffer(range.start, range.end)) {
// range flushed, remove from flush array
this.flushRange.shift();
this.flushBufferCounter = 0;
} else {
this._needsFlush = true;
// avoid looping, wait for SB update end to retrigger a flush
return;
}
}
if (this.flushRange.length === 0) {
// everything flushed
this._needsFlush = false;
// let's recompute this.appended, which is used to avoid flush looping
var appended = 0;
var sourceBuffer = this.sourceBuffer;
if (sourceBuffer) {
for (var type in sourceBuffer) {
appended += sourceBuffer[type].buffered.length;
}
}
this.appended = appended;
this.hls.trigger(_events2.default.BUFFER_FLUSHED);
}
}
}, {
key: 'doAppending',
value: function doAppending() {
var hls = this.hls,
sourceBuffer = this.sourceBuffer,
segments = this.segments;
if (sourceBuffer) {
if (this.media.error) {
segments = [];
_logger.logger.error('trying to append although a media error occured, flush segment and abort');
return;
}
for (var type in sourceBuffer) {
if (sourceBuffer[type].updating) {
//logger.log('sb update in progress');
return;
}
}
if (segments.length) {
var segment = segments.shift();
try {
//logger.log(`appending ${segment.type} SB, size:${segment.data.length});
sourceBuffer[segment.type].appendBuffer(segment.data);
this.appendError = 0;
this.appended++;
} catch (err) {
// in case any error occured while appending, put back segment in segments table
_logger.logger.error('error while trying to append buffer:' + err.message);
segments.unshift(segment);
var event = { type: _errors.ErrorTypes.MEDIA_ERROR };
if (err.code !== 22) {
if (this.appendError) {
this.appendError++;
} else {
this.appendError = 1;
}
event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR;
event.frag = this.fragCurrent;
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. retrying help recovering this
*/
if (this.appendError > hls.config.appendErrorMaxRetry) {
_logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
segments = [];
event.fatal = true;
hls.trigger(_events2.default.ERROR, event);
return;
} else {
event.fatal = false;
hls.trigger(_events2.default.ERROR, event);
}
} else {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
segments = [];
event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR;
hls.trigger(_events2.default.ERROR, event);
}
}
}
}
}
/*
flush specified buffered range,
return true once range has been flushed.
as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
*/
}, {
key: 'flushBuffer',
value: function flushBuffer(startOffset, endOffset) {
var sb, i, bufStart, bufEnd, flushStart, flushEnd;
//logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime + '/' + startOffset + '/' + endOffset);
// safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
if (this.flushBufferCounter < this.appended && this.sourceBuffer) {
for (var type in this.sourceBuffer) {
sb = this.sourceBuffer[type];
if (!sb.updating) {
for (i = 0; i < sb.buffered.length; i++) {
bufStart = sb.buffered.start(i);
bufEnd = sb.buffered.end(i);
// workaround firefox not able to properly flush multiple buffered range.
if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {
flushStart = startOffset;
flushEnd = endOffset;
} else {
flushStart = Math.max(bufStart, startOffset);
flushEnd = Math.min(bufEnd, endOffset);
}
/* sometimes sourcebuffer.remove() does not flush
the exact expected time range.
to avoid rounding issues/infinite loop,
only flush buffer range of length greater than 500ms.
*/
if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) {
this.flushBufferCounter++;
_logger.logger.log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
sb.remove(flushStart, flushEnd);
return false;
}
}
} else {
//logger.log('abort ' + type + ' append in progress');
// this will abort any appending in progress
//sb.abort();
_logger.logger.warn('cannot flush, sb updating in progress');
return false;
}
}
} else {
_logger.logger.warn('abort flushing too many retries');
}
_logger.logger.log('buffer flushed');
// everything flushed !
return true;
}
}]);
return BufferController;
}(_eventHandler2.default);
exports.default = BufferController;
},{"../errors":21,"../event-handler":22,"../events":23,"../utils/logger":38}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* cap stream level to media size dimension controller
*/
var CapLevelController = function (_EventHandler) {
_inherits(CapLevelController, _EventHandler);
function CapLevelController(hls) {
_classCallCheck(this, CapLevelController);
return _possibleConstructorReturn(this, Object.getPrototypeOf(CapLevelController).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MANIFEST_PARSED));
}
_createClass(CapLevelController, [{
key: 'destroy',
value: function destroy() {
if (this.hls.config.capLevelToPlayerSize) {
this.media = null;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
this.timer = clearInterval(this.timer);
}
}
}
}, {
key: 'onMediaAttaching',
value: function onMediaAttaching(data) {
this.media = data.media instanceof HTMLVideoElement ? data.media : null;
}
}, {
key: 'onManifestParsed',
value: function onManifestParsed(data) {
if (this.hls.config.capLevelToPlayerSize) {
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.levels = data.levels;
this.hls.firstLevel = this.getMaxLevel(data.firstLevel);
clearInterval(this.timer);
this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
}
}
}, {
key: 'detectPlayerSize',
value: function detectPlayerSize() {
if (this.media) {
var levelsLength = this.levels ? this.levels.length : 0;
if (levelsLength) {
this.hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
if (this.hls.autoLevelCapping > this.autoLevelCapping) {
// if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
// usually happen when the user go to the fullscreen mode.
this.hls.streamController.nextLevelSwitch();
}
this.autoLevelCapping = this.hls.autoLevelCapping;
}
}
}
/*
* returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
*/
}, {
key: 'getMaxLevel',
value: function getMaxLevel(capLevelIndex) {
var result = void 0,
i = void 0,
level = void 0,
mWidth = this.mediaWidth,
mHeight = this.mediaHeight,
lWidth = 0,
lHeight = 0;
for (i = 0; i <= capLevelIndex; i++) {
level = this.levels[i];
result = i;
lWidth = level.width;
lHeight = level.height;
if (mWidth <= lWidth || mHeight <= lHeight) {
break;
}
}
return result;
}
}, {
key: 'contentScaleFactor',
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = window.devicePixelRatio;
} catch (e) {}
return pixelRatio;
}
}, {
key: 'mediaWidth',
get: function get() {
var width = void 0;
if (this.media) {
width = this.media.width || this.media.clientWidth || this.media.offsetWidth;
width *= this.contentScaleFactor;
}
return width;
}
}, {
key: 'mediaHeight',
get: function get() {
var height = void 0;
if (this.media) {
height = this.media.height || this.media.clientHeight || this.media.offsetHeight;
height *= this.contentScaleFactor;
}
return height;
}
}]);
return CapLevelController;
}(_eventHandler2.default);
exports.default = CapLevelController;
},{"../event-handler":22,"../events":23}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /*
* EWMA Bandwidth Estimator
* - heavily inspired from shaka-player
* Tracks bandwidth samples and estimates available bandwidth.
* Based on the minimum of two exponentially-weighted moving averages with
* different half-lives.
*/
var _ewma = require('../utils/ewma');
var _ewma2 = _interopRequireDefault(_ewma);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var EwmaBandWidthEstimator = function () {
function EwmaBandWidthEstimator(hls) {
_classCallCheck(this, EwmaBandWidthEstimator);
this.hls = hls;
this.defaultEstimate_ = 5e5; // 500kbps
this.minWeight_ = 0.001;
this.minDelayMs_ = 50;
}
_createClass(EwmaBandWidthEstimator, [{
key: 'sample',
value: function sample(durationMs, numBytes) {
durationMs = Math.max(durationMs, this.minDelayMs_);
var bandwidth = 8000 * numBytes / durationMs;
//console.log('instant bw:'+ Math.round(bandwidth));
// we weight sample using loading duration....
var weigth = durationMs / 1000;
// lazy initialization. this allows to take into account config param changes that could happen after Hls instantiation,
// but before first fragment loading. this is useful to A/B tests those params
if (!this.fast_) {
var config = this.hls.config;
this.fast_ = new _ewma2.default(config.abrEwmaFast);
this.slow_ = new _ewma2.default(config.abrEwmaSlow);
}
this.fast_.sample(weigth, bandwidth);
this.slow_.sample(weigth, bandwidth);
}
}, {
key: 'getEstimate',
value: function getEstimate() {
if (!this.fast_ || this.fast_.getTotalWeight() < this.minWeight_) {
return this.defaultEstimate_;
}
//console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
//console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
// Take the minimum of these two estimates. This should have the effect of
// adapting down quickly, but up more slowly.
return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
}
}, {
key: 'destroy',
value: function destroy() {}
}]);
return EwmaBandWidthEstimator;
}();
exports.default = EwmaBandWidthEstimator;
},{"../utils/ewma":37}],7:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _logger = require('../utils/logger');
var _errors = require('../errors');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* Level Controller
*/
var LevelController = function (_EventHandler) {
_inherits(LevelController, _EventHandler);
function LevelController(hls) {
_classCallCheck(this, LevelController);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(LevelController).call(this, hls, _events2.default.MANIFEST_LOADED, _events2.default.LEVEL_LOADED, _events2.default.ERROR));
_this.ontick = _this.tick.bind(_this);
_this._manualLevel = _this._autoLevelCapping = -1;
return _this;
}
_createClass(LevelController, [{
key: 'destroy',
value: function destroy() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this._manualLevel = -1;
}
}, {
key: 'startLoad',
value: function startLoad() {
this.canload = true;
// speed up live playlist refresh if timer exists
if (this.timer) {
this.tick();
}
}
}, {
key: 'stopLoad',
value: function stopLoad() {
this.canload = false;
}
}, {
key: 'onManifestLoaded',
value: function onManifestLoaded(data) {
var levels0 = [],
levels = [],
bitrateStart,
i,
bitrateSet = {},
videoCodecFound = false,
audioCodecFound = false,
hls = this.hls;
// regroup redundant level together
data.levels.forEach(function (level) {
if (level.videoCodec) {
videoCodecFound = true;
}
if (level.audioCodec) {
audioCodecFound = true;
}
var redundantLevelId = bitrateSet[level.bitrate];
if (redundantLevelId === undefined) {
bitrateSet[level.bitrate] = levels0.length;
level.url = [level.url];
level.urlId = 0;
levels0.push(level);
} else {
levels0[redundantLevelId].url.push(level.url);
}
});
// remove audio-only level if we also have levels with audio+video codecs signalled
if (videoCodecFound && audioCodecFound) {
levels0.forEach(function (level) {
if (level.videoCodec) {
levels.push(level);
}
});
} else {
levels = levels0;
}
// only keep level with supported audio/video codecs
levels = levels.filter(function (level) {
var checkSupportedAudio = function checkSupportedAudio(codec) {
return MediaSource.isTypeSupported('audio/mp4;codecs=' + codec);
};
var checkSupportedVideo = function checkSupportedVideo(codec) {
return MediaSource.isTypeSupported('video/mp4;codecs=' + codec);
};
var audioCodec = level.audioCodec,
videoCodec = level.videoCodec;
return (!audioCodec || checkSupportedAudio(audioCodec)) && (!videoCodec || checkSupportedVideo(videoCodec));
});
if (levels.length) {
// start bitrate is the first bitrate of the manifest
bitrateStart = levels[0].bitrate;
// sort level on bitrate
levels.sort(function (a, b) {
return a.bitrate - b.bitrate;
});
this._levels = levels;
// find index of first level in sorted levels
for (i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
_logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
break;
}
}
hls.trigger(_events2.default.MANIFEST_PARSED, { levels: this._levels, firstLevel: this._firstLevel, stats: data.stats });
} else {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest' });
}
return;
}
}, {
key: 'setLevelInternal',
value: function setLevelInternal(newLevel) {
var levels = this._levels;
// check if level idx is valid
if (newLevel >= 0 && newLevel < levels.length) {
// stopping live reloading timer if any
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this._level = newLevel;
_logger.logger.log('switching to level ' + newLevel);
this.hls.trigger(_events2.default.LEVEL_SWITCH, { level: newLevel });
var level = levels[newLevel];
// check if we need to load playlist for this level
if (level.details === undefined || level.details.live === true) {
// level not retrieved yet, or live playlist we need to (re)load it
_logger.logger.log('(re)loading playlist for level ' + newLevel);
var urlId = level.urlId;
this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
}
} else {
// invalid level id given, trigger error
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' });
}
}
}, {
key: 'onError',
value: function onError(data) {
if (data.fatal) {
return;
}
var details = data.details,
hls = this.hls,
levelId = void 0,
level = void 0,
levelError = false;
// try to recover not fatal errors
switch (details) {
case _errors.ErrorDetails.FRAG_LOAD_ERROR:
case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
case _errors.ErrorDetails.KEY_LOAD_ERROR:
case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
levelId = data.frag.level;
break;
case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
levelId = data.level;
levelError = true;
break;
default:
break;
}
/* try to switch to a redundant stream if any available.
* if no redundant stream available, emergency switch down (if in auto mode and current level not 0)
* otherwise, we cannot recover this network error ...
* don't raise FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT as fatal, as it is handled by mediaController
*/
if (levelId !== undefined) {
level = this._levels[levelId];
if (level.urlId < level.url.length - 1) {
level.urlId++;
level.details = undefined;
_logger.logger.warn('level controller,' + details + ' for level ' + levelId + ': switching to redundant stream id ' + level.urlId);
} else {
// we could try to recover if in auto mode and current level not lowest level (0)
var recoverable = this._manualLevel === -1 && levelId;
if (recoverable) {
_logger.logger.warn('level controller,' + details + ': emergency switch-down for next fragment');
hls.abrController.nextAutoLevel = 0;
} else if (level && level.details && level.details.live) {
_logger.logger.warn('level controller,' + details + ' on live stream, discard');
if (levelError) {
// reset this._level so that another call to set level() will retrigger a frag load
this._level = undefined;
}
// FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT are handled by mediaController
} else if (details !== _errors.ErrorDetails.FRAG_LOAD_ERROR && details !== _errors.ErrorDetails.FRAG_LOAD_TIMEOUT) {
_logger.logger.error('cannot recover ' + details + ' error');
this._level = undefined;
// stopping live reloading timer if any
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
// redispatch same error but with fatal set to true
data.fatal = true;
hls.trigger(_events2.default.ERROR, data);
}
}
}
}
}, {
key: 'onLevelLoaded',
value: function onLevelLoaded(data) {
// only process level loaded events matching with expected level
if (data.level === this._level) {
var newDetails = data.details;
// if current playlist is a live playlist, arm a timer to reload it
if (newDetails.live) {
var reloadInterval = 1000 * newDetails.targetduration,
curLevel = this._levels[data.level],
curDetails = curLevel.details;
if (curDetails && newDetails.endSN === curDetails.endSN) {
// follow HLS Spec, If the client reloads a Playlist file and finds that it has not
// changed then it MUST wait for a period of one-half the target
// duration before retrying.
reloadInterval /= 2;
_logger.logger.log('same live playlist, reload twice faster');
}
// decrement reloadInterval with level loading delay
reloadInterval -= performance.now() - data.stats.trequest;
// in any case, don't reload more than every second
reloadInterval = Math.max(1000, Math.round(reloadInterval));
_logger.logger.log('live playlist, reload in ' + reloadInterval + ' ms');
this.timer = setTimeout(this.ontick, reloadInterval);
} else {
this.timer = null;
}
}
}
}, {
key: 'tick',
value: function tick() {
var levelId = this._level;
if (levelId !== undefined && this.canload) {
var level = this._levels[levelId],
urlId = level.urlId;
this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId });
}
}
}, {
key: 'levels',
get: function get() {
return this._levels;
}
}, {
key: 'level',
get: function get() {
return this._level;
},
set: function set(newLevel) {
var levels = this._levels;
if (levels && levels.length > newLevel) {
if (this._level !== newLevel || levels[newLevel].details === undefined) {
this.setLevelInternal(newLevel);
}
}
}
}, {
key: 'manualLevel',
get: function get() {
return this._manualLevel;
},
set: function set(newLevel) {
this._manualLevel = newLevel;
if (this._startLevel === undefined) {
this._startLevel = newLevel;
}
if (newLevel !== -1) {
this.level = newLevel;
}
}
}, {
key: 'firstLevel',
get: function get() {
return this._firstLevel;
},
set: function set(newLevel) {
this._firstLevel = newLevel;
}
}, {
key: 'startLevel',
get: function get() {
if (this._startLevel === undefined) {
return this._firstLevel;
} else {
return this._startLevel;
}
},
set: function set(newLevel) {
this._startLevel = newLevel;
}
}, {
key: 'nextLoadLevel',
get: function get() {
if (this._manualLevel !== -1) {
return this._manualLevel;
} else {
return this.hls.abrController.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this._manualLevel === -1) {
this.hls.abrController.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(_eventHandler2.default);
exports.default = LevelController;
},{"../errors":21,"../event-handler":22,"../events":23,"../utils/logger":38}],8:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _demuxer = require('../demux/demuxer');
var _demuxer2 = _interopRequireDefault(_demuxer);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _logger = require('../utils/logger');
var _binarySearch = require('../utils/binary-search');
var _binarySearch2 = _interopRequireDefault(_binarySearch);
var _bufferHelper = require('../helper/buffer-helper');
var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
var _levelHelper = require('../helper/level-helper');
var _levelHelper2 = _interopRequireDefault(_levelHelper);
var _errors = require('../errors');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* Stream Controller
*/
var State = {
STOPPED: 'STOPPED',
STARTING: 'STARTING',
IDLE: 'IDLE',
PAUSED: 'PAUSED',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_LEVEL: 'WAITING_LEVEL',
PARSING: 'PARSING',
PARSED: 'PARSED',
ENDED: 'ENDED',
ERROR: 'ERROR'
};
var StreamController = function (_EventHandler) {
_inherits(StreamController, _EventHandler);
function StreamController(hls) {
_classCallCheck(this, StreamController);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(StreamController).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_PARSED, _events2.default.LEVEL_LOADED, _events2.default.KEY_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_LOAD_EMERGENCY_ABORTED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.ERROR, _events2.default.BUFFER_APPENDED, _events2.default.BUFFER_FLUSHED));
_this.config = hls.config;
_this.audioCodecSwap = false;
_this.ticks = 0;
_this.ontick = _this.tick.bind(_this);
return _this;
}
_createClass(StreamController, [{
key: 'destroy',
value: function destroy() {
this.stopLoad();
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
_eventHandler2.default.prototype.destroy.call(this);
this.state = State.STOPPED;
}
}, {
key: 'startLoad',
value: function startLoad() {
var startPosition = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
if (this.levels) {
var media = this.media,
lastCurrentTime = this.lastCurrentTime;
this.stopLoad();
this.demuxer = new _demuxer2.default(this.hls);
if (!this.timer) {
this.timer = setInterval(this.ontick, 100);
}
this.level = -1;
this.fragLoadError = 0;
if (media && lastCurrentTime) {
_logger.logger.log('configure startPosition @' + lastCurrentTime);
if (!this.lastPaused) {
_logger.logger.log('resuming video');
media.play();
}
this.state = State.IDLE;
} else {
this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
this.state = State.STARTING;
}
this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
this.tick();
} else {
_logger.logger.warn('cannot start loading as manifest not parsed yet');
this.state = State.STOPPED;
}
}
}, {
key: 'stopLoad',
value: function stopLoad() {
var frag = this.fragCurrent;
if (frag) {
if (frag.loader) {
frag.loader.abort();
}
this.fragCurrent = null;
}
this.fragPrevious = null;
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
this.state = State.STOPPED;
}
}, {
key: 'tick',
value: function tick() {
this.ticks++;
if (this.ticks === 1) {
this.doTick();
if (this.ticks > 1) {
setTimeout(this.tick, 1);
}
this.ticks = 0;
}
}
}, {
key: 'doTick',
value: function doTick() {
var pos,
level,
levelDetails,
hls = this.hls,
config = hls.config,
media = this.media,
isSeeking = media && media.seeking;
//logger.log(this.state);
switch (this.state) {
case State.ERROR:
//don't do anything in error state to avoid breaking further ...
case State.PAUSED:
//don't do anything in paused state either ...
break;
case State.STARTING:
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.fragBitrateTest = true;
}
// set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
this.level = hls.nextLoadLevel = startLevel;
this.state = State.WAITING_LEVEL;
this.loadedmetadata = false;
break;
case State.IDLE:
// if video not attached AND
// start fragment already requested OR start frag prefetch disable
// exit loop
// => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
if (!media && (this.startFragRequested || !config.startFragPrefetch)) {
break;
}
// determine next candidate fragment to be loaded, based on current position and
// end of buffer position
// ensure 60s of buffer upfront
// if we have not yet loaded any fragment, start loading from start position
if (this.loadedmetadata) {
pos = media.currentTime;
} else {
pos = this.nextLoadPosition;
}
level = hls.nextLoadLevel;
var bufferInfo = _bufferHelper2.default.bufferInfo(media, pos, config.maxBufferHole),
bufferLen = bufferInfo.len,
bufferEnd = bufferInfo.end,
fragPrevious = this.fragPrevious,
maxBufLen;
// compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
if (this.levels[level].hasOwnProperty('bitrate')) {
maxBufLen = Math.max(8 * config.maxBufferSize / this.levels[level].bitrate, config.maxBufferLength);
maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
// if buffer length is less than maxBufLen try to load a new fragment
if (bufferLen < maxBufLen) {
// set next load level : this will trigger a playlist load if needed
hls.nextLoadLevel = level;
this.level = level;
levelDetails = this.levels[level].details;
// if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) {
this.state = State.WAITING_LEVEL;
break;
}
// find fragment index, contiguous with end of buffer position
var fragments = levelDetails.fragments,
fragLen = fragments.length,
start = fragments[0].start,
end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
frag = void 0;
// in case of live playlist we need to ensure that requested position is not located before playlist start
if (levelDetails.live) {
// check if requested position is within seekable boundaries :
//logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${media.seeking}`);
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (bufferEnd < Math.max(start, end - maxLatency)) {
var targetLatency = config.liveSyncDuration !== undefined ? config.liveSyncDuration : config.liveSyncDurationCount * levelDetails.targetduration;
var liveSyncPosition = start + Math.max(0, levelDetails.totalduration - targetLatency);
_logger.logger.log('buffer end: ' + bufferEnd + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3));
bufferEnd = liveSyncPosition;
if (media && media.readyState && media.duration > liveSyncPosition) {
media.currentTime = liveSyncPosition;
}
}
// if end of buffer greater than live edge, don't load any fragment
// this could happen if live playlist intermittently slides in the past.
// level 1 loaded [182580161,182580167]
// level 1 loaded [182580162,182580169]
// Loading 182580168 of [182580162 ,182580169],level 1 ..
// Loading 182580169 of [182580162 ,182580169],level 1 ..
// level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
// level 1 loaded [182580164,182580171]
//
if (levelDetails.PTSKnown && bufferEnd > end) {
break;
}
if (this.startFragRequested && !levelDetails.PTSKnown) {
/* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
try to load frag matching with next SN.
even if SN are not synchronized between playlists, loading this frag will help us
compute playlist sliding and find the right one after in case it was not the right consecutive one */
if (fragPrevious) {
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
frag = fragments[targetSN - levelDetails.startSN];
_logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
}
}
if (!frag) {
/* we have no idea about which fragment should be loaded.
so let's load mid fragment. it will help computing playlist sliding and find the right one
*/
frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
_logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
}
}
} else {
// VoD playlist: if bufferEnd before start of playlist, load first fragment
if (bufferEnd < start) {
frag = fragments[0];
}
}
if (!frag) {
(function () {
var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
if (bufferEnd < end) {
// no frag look up tolerance in case bufferEnd close to end, or media seeking
if (bufferEnd > end - maxFragLookUpTolerance || isSeeking) {
maxFragLookUpTolerance = 0;
}
frag = _binarySearch2.default.search(fragments, function (candidate) {
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ø] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
//logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
if (candidate.start + candidate.duration - maxFragLookUpTolerance <= bufferEnd) {
return 1;
} else if (candidate.start - maxFragLookUpTolerance > bufferEnd) {
return -1;
}
return 0;
});
} else {
// reach end of playlist
frag = fragments[fragLen - 1];
}
})();
}
if (frag) {
start = frag.start;
//logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
if (frag.sn < levelDetails.endSN) {
frag = fragments[frag.sn + 1 - levelDetails.startSN];
_logger.logger.log('SN just loaded, load next one: ' + frag.sn);
} else {
// have we reached end of VOD playlist ?
if (!levelDetails.live) {
// Finalize the media stream
this.hls.trigger(_events2.default.BUFFER_EOS);
// We might be loading the last fragment but actually the media
// is currently processing a seek command and waiting for new data to resume at another point.
// Going to ended state while media is seeking can spawn an infinite buffering broken state.
if (!isSeeking) {
this.state = State.ENDED;
}
}
return;
}
}
//logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
if (frag.decryptdata.uri != null && frag.decryptdata.key == null) {
_logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
this.state = State.KEY_LOADING;
hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
} else {
_logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
// ensure that we are not reloading the same fragments in loop ...
if (this.fragLoadIdx !== undefined) {
this.fragLoadIdx++;
} else {
this.fragLoadIdx = 0;
}
if (frag.loadCounter) {
frag.loadCounter++;
var maxThreshold = config.fragLoadingLoopThreshold;
// if this frag has already been loaded 3 times, and if it has been reloaded recently
if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
return;
}
} else {
frag.loadCounter = 1;
}
frag.loadIdx = this.fragLoadIdx;
this.fragCurrent = frag;
this.startFragRequested = true;
frag.autoLevel = hls.autoLevelEnabled;
hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
this.state = State.FRAG_LOADING;
}
}
}
break;
case State.WAITING_LEVEL:
level = this.levels[this.level];
// check if playlist is already loaded
if (level && level.details) {
this.state = State.IDLE;
}
break;
case State.FRAG_LOADING_WAITING_RETRY:
var now = performance.now();
var retryDate = this.retryDate;
// if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || isSeeking) {
_logger.logger.log('mediaController: retryDate reached, switch back to IDLE state');
this.state = State.IDLE;
}
break;
case State.STOPPED:
case State.FRAG_LOADING:
case State.PARSING:
case State.PARSED:
case State.ENDED:
break;
default:
break;
}
// check buffer
this._checkBuffer();
// check/update current fragment
this._checkFragmentChanged();
}
}, {
key: 'getBufferRange',
value: function getBufferRange(position) {
var i,
range,
bufferRange = this.bufferRange;
if (bufferRange) {
for (i = bufferRange.length - 1; i >= 0; i--) {
range = bufferRange[i];
if (position >= range.start && position <= range.end) {
return range;
}
}
}
return null;
}
}, {
key: 'followingBufferRange',
value: function followingBufferRange(range) {
if (range) {
// try to get range of next fragment (500ms after this range)
return this.getBufferRange(range.end + 0.5);
}
return null;
}
}, {
key: 'isBuffered',
value: function isBuffered(position) {
var media = this.media;
if (media) {
var buffered = media.buffered;
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
return false;
}
}, {
key: '_checkFragmentChanged',
value: function _checkFragmentChanged() {
var rangeCurrent,
currentTime,
video = this.media;
if (video && video.seeking === false) {
currentTime = video.currentTime;
/* if video element is in seeked state, currentTime can only increase.
(assuming that playback rate is positive ...)
As sometimes currentTime jumps back to zero after a
media decode error, check this, to avoid seeking back to
wrong position after a media decode error
*/
if (currentTime > video.playbackRate * this.lastCurrentTime) {
this.lastCurrentTime = currentTime;
}
if (this.isBuffered(currentTime)) {
rangeCurrent = this.getBufferRange(currentTime);
} else if (this.isBuffered(currentTime + 0.1)) {
/* ensure that FRAG_CHANGED event is triggered at startup,
when first video frame is displayed and playback is paused.
add a tolerance of 100ms, in case current position is not buffered,
check if current pos+100ms is buffered and use that buffer range
for FRAG_CHANGED event reporting */
rangeCurrent = this.getBufferRange(currentTime + 0.1);
}
if (rangeCurrent) {
var fragPlaying = rangeCurrent.frag;
if (fragPlaying !== this.fragPlaying) {
this.fragPlaying = fragPlaying;
this.hls.trigger(_events2.default.FRAG_CHANGED, { frag: fragPlaying });
}
}
}
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
}, {
key: 'immediateLevelSwitch',
value: function immediateLevelSwitch() {
_logger.logger.log('immediateLevelSwitch');
if (!this.immediateSwitch) {
this.immediateSwitch = true;
this.previouslyPaused = this.media.paused;
this.media.pause();
}
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// increase fragment load Index to avoid frag loop loading error after buffer flush
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
this.state = State.PAUSED;
// flush everything
this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY });
}
/*
on immediate level switch end, after new fragment has been buffered :
- nudge video decoder by slightly adjusting video currentTime
- resume the playback if needed
*/
}, {
key: 'immediateLevelSwitchEnd',
value: function immediateLevelSwitchEnd() {
this.immediateSwitch = false;
var media = this.media;
if (media && media.readyState) {
media.currentTime -= 0.0001;
if (!this.previouslyPaused) {
media.play();
}
}
}
}, {
key: 'nextLevelSwitch',
value: function nextLevelSwitch() {
/* try to switch ASAP without breaking video playback :
in order to ensure smooth but quick level switching,
we need to find the next flushable buffer range
we should take into account new segment fetch time
*/
var media = this.media;
// ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media && media.readyState) {
var fetchdelay = void 0,
currentRange = void 0,
nextRange = void 0;
// increase fragment load Index to avoid frag loop loading error after buffer flush
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
currentRange = this.getBufferRange(media.currentTime);
if (currentRange && currentRange.start > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.state = State.PAUSED;
this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: currentRange.start - 1 });
}
if (!media.paused) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel,
nextLevel = this.levels[nextLevelId],
fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
}
//logger.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
nextRange = this.getBufferRange(media.currentTime + fetchdelay);
if (nextRange) {
// we can flush buffer range following this one without stalling playback
nextRange = this.followingBufferRange(nextRange);
if (nextRange) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// flush position is the start position of this new buffer
this.state = State.PAUSED;
this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: nextRange.start, endOffset: Number.POSITIVE_INFINITY });
}
}
}
}
}, {
key: 'onMediaAttached',
value: function onMediaAttached(data) {
var media = this.media = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('seeked', this.onvseeked);
media.addEventListener('ended', this.onvended);
if (this.levels && this.config.autoStartLoad) {
this.hls.startLoad();
}
}
}, {
key: 'onMediaDetaching',
value: function onMediaDetaching() {
var media = this.media;
if (media && media.ended) {
_logger.logger.log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
}
// reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
var levels = this.levels;
if (levels) {
// reset fragment load counter
levels.forEach(function (level) {
if (level.details) {
level.details.fragments.forEach(function (fragment) {
fragment.loadCounter = undefined;
});
}
});
}
// remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('seeked', this.onvseeked);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvseeked = this.onvended = null;
}
this.media = null;
this.loadedmetadata = false;
this.stopLoad();
}
}, {
key: 'onMediaSeeking',
value: function onMediaSeeking() {
if (this.state === State.FRAG_LOADING) {
// check if currently loaded fragment is inside buffer.
//if outside, cancel fragment loading, otherwise do nothing
if (_bufferHelper2.default.bufferInfo(this.media, this.media.currentTime, this.config.maxBufferHole).len === 0) {
_logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
var fragCurrent = this.fragCurrent;
if (fragCurrent) {
if (fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
}
this.fragPrevious = null;
// switch to IDLE state to load new fragment
this.state = State.IDLE;
}
} else if (this.state === State.ENDED) {
// switch to IDLE state to check for potential new fragment
this.state = State.IDLE;
}
if (this.media) {
this.lastCurrentTime = this.media.currentTime;
}
// avoid reporting fragment loop loading error in case user is seeking several times on same position
if (this.fragLoadIdx !== undefined) {
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
}
// tick to speed up processing
this.tick();
}
}, {
key: 'onMediaSeeked',
value: function onMediaSeeked() {
// tick to speed up FRAGMENT_PLAYING triggering
this.tick();
}
}, {
key: 'onMediaEnded',
value: function onMediaEnded() {
_logger.logger.log('media ended');
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
}
}, {
key: 'onManifestLoading',
value: function onManifestLoading() {
// reset buffer on manifest loading
_logger.logger.log('trigger BUFFER_RESET');
this.hls.trigger(_events2.default.BUFFER_RESET);
this.bufferRange = [];
this.stalled = false;
}
}, {
key: 'onManifestParsed',
value: function onManifestParsed(data) {
var aac = false,
heaac = false,
codec;
data.levels.forEach(function (level) {
// detect if we have different kind of audio codecs used amongst playlists
codec = level.audioCodec;
if (codec) {
if (codec.indexOf('mp4a.40.2') !== -1) {
aac = true;
}
if (codec.indexOf('mp4a.40.5') !== -1) {
heaac = true;
}
}
});
this.audioCodecSwitch = aac && heaac;
if (this.audioCodecSwitch) {
_logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.levels = data.levels;
this.startLevelLoaded = false;
this.startFragRequested = false;
if (this.config.autoStartLoad) {
this.hls.startLoad();
}
}
}, {
key: 'onLevelLoaded',
value: function onLevelLoaded(data) {
var newDetails = data.details,
newLevelId = data.level,
curLevel = this.levels[newLevelId],
duration = newDetails.totalduration,
sliding = 0;
_logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
this.levelLastLoaded = newLevelId;
if (newDetails.live) {
var curDetails = curLevel.details;
if (curDetails) {
// we already have details for that level, merge them
_levelHelper2.default.mergeDetails(curDetails, newDetails);
sliding = newDetails.fragments[0].start;
if (newDetails.PTSKnown) {
_logger.logger.log('live playlist sliding:' + sliding.toFixed(3));
} else {
_logger.logger.log('live playlist - outdated PTS, unknown sliding');
}
} else {
newDetails.PTSKnown = false;
_logger.logger.log('live playlist - first load, unknown sliding');
}
} else {
newDetails.PTSKnown = false;
}
// override level info
curLevel.details = newDetails;
this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
// compute start position
if (this.startFragRequested === false) {
// if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
if (newDetails.live) {
var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * newDetails.targetduration;
this.startPosition = Math.max(0, sliding + duration - targetLatency);
}
this.nextLoadPosition = this.startPosition;
}
// only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === State.WAITING_LEVEL) {
this.state = State.IDLE;
}
//trigger handler right now
this.tick();
}
}, {
key: 'onKeyLoaded',
value: function onKeyLoaded() {
if (this.state === State.KEY_LOADING) {
this.state = State.IDLE;
this.tick();
}
}
}, {
key: 'onFragLoaded',
value: function onFragLoaded(data) {
var fragCurrent = this.fragCurrent;
if (this.state === State.FRAG_LOADING && fragCurrent && data.frag.level === fragCurrent.level && data.frag.sn === fragCurrent.sn) {
_logger.logger.log('Loaded ' + fragCurrent.sn + ' of level ' + fragCurrent.level);
if (this.fragBitrateTest === true) {
// switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
this.state = State.IDLE;
this.fragBitrateTest = false;
this.startFragRequested = false;
data.stats.tparsed = data.stats.tbuffered = performance.now();
this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: data.stats, frag: fragCurrent });
} else {
this.state = State.PARSING;
// transmux the MPEG-TS data to ISO-BMFF segments
this.stats = data.stats;
var currentLevel = this.levels[this.level],
details = currentLevel.details,
duration = details.totalduration,
start = fragCurrent.startDTS !== undefined ? fragCurrent.startDTS : fragCurrent.start,
level = fragCurrent.level,
sn = fragCurrent.sn,
audioCodec = currentLevel.audioCodec || this.config.defaultAudioCodec;
if (this.audioCodecSwap) {
_logger.logger.log('swapping playlist audio codec');
if (audioCodec === undefined) {
audioCodec = this.lastAudioCodec;
}
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
}
this.pendingAppending = 0;
_logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level);
var demuxer = this.demuxer;
if (demuxer) {
demuxer.push(data.payload, audioCodec, currentLevel.videoCodec, start, fragCurrent.cc, level, sn, duration, fragCurrent.decryptdata);
}
}
}
this.fragLoadError = 0;
}
}, {
key: 'onFragParsingInitSegment',
value: function onFragParsingInitSegment(data) {
if (this.state === State.PARSING) {
var tracks = data.tracks,
trackName,
track;
// include levelCodec in audio and video tracks
track = tracks.audio;
if (track) {
var audioCodec = this.levels[this.level].audioCodec,
ua = navigator.userAgent.toLowerCase();
if (audioCodec && this.audioCodecSwap) {
_logger.logger.log('swapping playlist audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
// in case AAC and HE-AAC audio codecs are signalled in manifest
// force HE-AAC , as it seems that most browsers prefers that way,
// except for mono streams OR on FF
// these conditions might need to be reviewed ...
if (this.audioCodecSwitch) {
// don't force HE-AAC if mono stream
if (track.metadata.channelCount !== 1 &&
// don't force HE-AAC if firefox
ua.indexOf('firefox') === -1) {
audioCodec = 'mp4a.40.5';
}
}
// HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
if (ua.indexOf('android') !== -1) {
audioCodec = 'mp4a.40.2';
_logger.logger.log('Android: force audio codec to' + audioCodec);
}
track.levelCodec = audioCodec;
}
track = tracks.video;
if (track) {
track.levelCodec = this.levels[this.level].videoCodec;
}
// if remuxer specify that a unique track needs to generated,
// let's merge all tracks together
if (data.unique) {
var mergedTrack = {
codec: '',
levelCodec: ''
};
for (trackName in data.tracks) {
track = tracks[trackName];
mergedTrack.container = track.container;
if (mergedTrack.codec) {
mergedTrack.codec += ',';
mergedTrack.levelCodec += ',';
}
if (track.codec) {
mergedTrack.codec += track.codec;
}
if (track.levelCodec) {
mergedTrack.levelCodec += track.levelCodec;
}
}
tracks = { audiovideo: mergedTrack };
}
this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
// loop through tracks that are going to be provided to bufferController
for (trackName in tracks) {
track = tracks[trackName];
_logger.logger.log('track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
var initSegment = track.initSegment;
if (initSegment) {
this.pendingAppending++;
this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment });
}
}
//trigger handler right now
this.tick();
}
}
}, {
key: 'onFragParsingData',
value: function onFragParsingData(data) {
var _this2 = this;
if (this.state === State.PARSING) {
this.tparse2 = Date.now();
var level = this.levels[this.level],
frag = this.fragCurrent;
_logger.logger.log('parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb);
var drift = _levelHelper2.default.updateFragPTSDTS(level.details, frag.sn, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
hls = this.hls;
hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift });
[data.data1, data.data2].forEach(function (buffer) {
if (buffer) {
_this2.pendingAppending++;
hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer });
}
});
this.nextLoadPosition = data.endPTS;
this.bufferRange.push({ type: data.type, start: data.startPTS, end: data.endPTS, frag: frag });
//trigger handler right now
this.tick();
} else {
_logger.logger.warn('not in PARSING state but ' + this.state + ', ignoring FRAG_PARSING_DATA event');
}
}
}, {
key: 'onFragParsed',
value: function onFragParsed() {
if (this.state === State.PARSING) {
this.stats.tparsed = performance.now();
this.state = State.PARSED;
this._checkAppendedParsed();
}
}
}, {
key: 'onBufferAppended',
value: function onBufferAppended() {
switch (this.state) {
case State.PARSING:
case State.PARSED:
this.pendingAppending--;
this._checkAppendedParsed();
break;
default:
break;
}
}
}, {
key: '_checkAppendedParsed',
value: function _checkAppendedParsed() {
//trigger handler right now
if (this.state === State.PARSED && this.pendingAppending === 0) {
var frag = this.fragCurrent,
stats = this.stats;
if (frag) {
this.fragPrevious = frag;
stats.tbuffered = performance.now();
this.fragLastKbps = Math.round(8 * stats.length / (stats.tbuffered - stats.tfirst));
this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag });
_logger.logger.log('media buffered : ' + this.timeRangesToString(this.media.buffered));
this.state = State.IDLE;
}
this.tick();
}
}
}, {
key: 'onError',
value: function onError(data) {
switch (data.details) {
case _errors.ErrorDetails.FRAG_LOAD_ERROR:
case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
if (!data.fatal) {
var loadError = this.fragLoadError;
if (loadError) {
loadError++;
} else {
loadError = 1;
}
if (loadError <= this.config.fragLoadingMaxRetry) {
this.fragLoadError = loadError;
// reset load counter to avoid frag loop loading error
data.frag.loadCounter = 0;
// exponential backoff capped to 64s
var delay = Math.min(Math.pow(2, loadError - 1) * this.config.fragLoadingRetryDelay, 64000);
_logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
this.retryDate = performance.now() + delay;
// retry loading state
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else {
_logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
// redispatch same error but with fatal set to true
data.fatal = true;
this.hls.trigger(_events2.default.ERROR, data);
this.state = State.ERROR;
}
}
break;
case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
case _errors.ErrorDetails.KEY_LOAD_ERROR:
case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
// when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
if (this.state !== State.ERROR) {
// if fatal error, stop processing, otherwise move to IDLE to retry loading
this.state = data.fatal ? State.ERROR : State.IDLE;
_logger.logger.warn('mediaController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...');
}
break;
case _errors.ErrorDetails.BUFFER_FULL_ERROR:
// trigger a smooth level switch to empty buffers
// also reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
this.config.maxMaxBufferLength /= 2;
_logger.logger.warn('reduce max buffer length to ' + this.config.maxMaxBufferLength + 's and trigger a nextLevelSwitch to flush old buffer and fix QuotaExceededError');
this.nextLevelSwitch();
break;
default:
break;
}
}
}, {
key: '_checkBuffer',
value: function _checkBuffer() {
var media = this.media;
// if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek
if (media && media.readyState) {
var currentTime = media.currentTime,
buffered = media.buffered;
// adjust currentTime to start position on loaded metadata
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
// only adjust currentTime if startPosition not equal to 0
var startPosition = this.startPosition;
// if currentTime === 0 AND not matching with expected startPosition
if (!currentTime && currentTime !== startPosition) {
if (startPosition) {
_logger.logger.log('target start position:' + startPosition);
// at that stage, there should be only one buffered range, as we reach that code after first fragment has been
var bufferStart = buffered.start(0),
bufferEnd = buffered.end(0);
// if startPosition not buffered, let's seek to buffered.start(0)
if (startPosition < bufferStart || startPosition > bufferEnd) {
startPosition = bufferStart;
_logger.logger.log('target start position not buffered, seek to buffered.start(0) ' + bufferStart);
}
_logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + startPosition);
media.currentTime = startPosition;
}
}
} else {
var bufferInfo = _bufferHelper2.default.bufferInfo(media, currentTime, 0),
expectedPlaying = !(media.paused || // not playing when media is paused
media.ended || // not playing when media is ended
media.buffered.length === 0),
// not playing if nothing buffered
jumpThreshold = 0.4,
// tolerance needed as some browsers stalls playback before reaching buffered range end
playheadMoving = currentTime > media.playbackRate * this.lastCurrentTime;
if (this.stalled && playheadMoving) {
this.stalled = false;
_logger.logger.log('playback not stuck anymore @' + currentTime);
}
// check buffer upfront
// if less than jumpThreshold second is buffered, let's check in more details
if (expectedPlaying && bufferInfo.len <= jumpThreshold) {
if (playheadMoving) {
// playhead moving
jumpThreshold = 0;
this.seekHoleNudgeDuration = 0;
} else {
// playhead not moving AND media expected to play
if (!this.stalled) {
this.seekHoleNudgeDuration = 0;
_logger.logger.log('playback seems stuck @' + currentTime);
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false });
this.stalled = true;
} else {
this.seekHoleNudgeDuration += this.config.seekHoleNudgeDuration;
}
}
// if we are below threshold, try to jump to start of next buffer range if close
if (bufferInfo.len <= jumpThreshold) {
// no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)
var nextBufferStart = bufferInfo.nextStart,
delta = nextBufferStart - currentTime;
if (nextBufferStart && delta < this.config.maxSeekHole && delta > 0) {
// next buffer is close ! adjust currentTime to nextBufferStart
// this will ensure effective video decoding
_logger.logger.log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + this.seekHoleNudgeDuration);
var hole = nextBufferStart + this.seekHoleNudgeDuration - media.currentTime;
media.currentTime = nextBufferStart + this.seekHoleNudgeDuration;
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole: hole });
}
}
}
}
}
}
}, {
key: 'onFragLoadEmergencyAborted',
value: function onFragLoadEmergencyAborted() {
this.state = State.IDLE;
this.tick();
}
}, {
key: 'onBufferFlushed',
value: function onBufferFlushed() {
/* after successful buffer flushing, rebuild buffer Range array
loop through existing buffer range and check if
corresponding range is still buffered. only push to new array already buffered range
*/
var newRange = [],
range,
i;
for (i = 0; i < this.bufferRange.length; i++) {
range = this.bufferRange[i];
if (this.isBuffered((range.start + range.end) / 2)) {
newRange.push(range);
}
}
this.bufferRange = newRange;
// handle end of immediate switching if needed
if (this.immediateSwitch) {
this.immediateLevelSwitchEnd();
}
// move to IDLE once flush complete. this should trigger new fragment loading
this.state = State.IDLE;
// reset reference to frag
this.fragPrevious = null;
}
}, {
key: 'swapAudioCodec',
value: function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
}, {
key: 'timeRangesToString',
value: function timeRangesToString(r) {
var log = '',
len = r.length;
for (var i = 0; i < len; i++) {
log += '[' + r.start(i) + ',' + r.end(i) + ']';
}
return log;
}
}, {
key: 'currentLevel',
get: function get() {
if (this.media) {
var range = this.getBufferRange(this.media.currentTime);
if (range) {
return range.frag.level;
}
}
return -1;
}
}, {
key: 'nextBufferRange',
get: function get() {
if (this.media) {
// first get end range of current fragment
return this.followingBufferRange(this.getBufferRange(this.media.currentTime));
} else {
return null;
}
}
}, {
key: 'nextLevel',
get: function get() {
var range = this.nextBufferRange;
if (range) {
return range.frag.level;
} else {
return -1;
}
}
}]);
return StreamController;
}(_eventHandler2.default);
exports.default = StreamController;
},{"../demux/demuxer":17,"../errors":21,"../event-handler":22,"../events":23,"../helper/buffer-helper":24,"../helper/level-helper":25,"../utils/binary-search":35,"../utils/logger":38}],9:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _cea708Interpreter = require('../utils/cea-708-interpreter');
var _cea708Interpreter2 = _interopRequireDefault(_cea708Interpreter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* Timeline Controller
*/
var TimelineController = function (_EventHandler) {
_inherits(TimelineController, _EventHandler);
function TimelineController(hls) {
_classCallCheck(this, TimelineController);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(TimelineController).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_USERDATA, _events2.default.MANIFEST_LOADING, _events2.default.FRAG_LOADED));
_this.hls = hls;
_this.config = hls.config;
if (_this.config.enableCEA708Captions) {
_this.cea708Interpreter = new _cea708Interpreter2.default();
}
return _this;
}
_createClass(TimelineController, [{
key: 'destroy',
value: function destroy() {
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onMediaAttaching',
value: function onMediaAttaching(data) {
var media = this.media = data.media;
this.cea708Interpreter.attach(media);
}
}, {
key: 'onMediaDetaching',
value: function onMediaDetaching() {
this.cea708Interpreter.detach();
}
}, {
key: 'onManifestLoading',
value: function onManifestLoading() {
this.lastPts = Number.POSITIVE_INFINITY;
}
}, {
key: 'onFragLoaded',
value: function onFragLoaded(data) {
var pts = data.frag.start; //Number.POSITIVE_INFINITY;
// if this is a frag for a previously loaded timerange, remove all captions
// TODO: consider just removing captions for the timerange
if (pts <= this.lastPts) {
this.cea708Interpreter.clear();
}
this.lastPts = pts;
}
}, {
key: 'onFragParsingUserdata',
value: function onFragParsingUserdata(data) {
// push all of the CEA-708 messages into the interpreter
// immediately. It will create the proper timestamps based on our PTS value
for (var i = 0; i < data.samples.length; i++) {
this.cea708Interpreter.push(data.samples[i].pts, data.samples[i].bytes);
}
}
}]);
return TimelineController;
}(_eventHandler2.default);
exports.default = TimelineController;
},{"../event-handler":22,"../events":23,"../utils/cea-708-interpreter":36}],10:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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"); } }
/*
*
* This file contains an adaptation of the AES decryption algorithm
* from the Standford Javascript Cryptography Library. That work is
* covered by the following copyright and permissions notice:
*
* Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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 AUTHORS ``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 <COPYRIGHT HOLDER> 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.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the authors.
*/
var AES = function () {
/**
* Schedule out an AES key for both encryption and decryption. This
* is a low-level class. Use a cipher mode to do bulk encryption.
*
* @constructor
* @param key {Array} The key as an array of 4, 6 or 8 words.
*/
function AES(key) {
_classCallCheck(this, AES);
/**
* The expanded S-box and inverse S-box tables. These will be computed
* on the client so that we don't have to send them down the wire.
*
* There are two tables, _tables[0] is for encryption and
* _tables[1] is for decryption.
*
* The first 4 sub-tables are the expanded S-box with MixColumns. The
* last (_tables[01][4]) is the S-box itself.
*
* @private
*/
this._tables = [[[], [], [], [], []], [[], [], [], [], []]];
this._precompute();
var i,
j,
tmp,
encKey,
decKey,
sbox = this._tables[0][4],
decTable = this._tables[1],
keyLen = key.length,
rcon = 1;
if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
throw new Error('Invalid aes key size=' + keyLen);
}
encKey = key.slice(0);
decKey = [];
this._key = [encKey, decKey];
// schedule encryption keys
for (i = keyLen; i < 4 * keyLen + 28; i++) {
tmp = encKey[i - 1];
// apply sbox
if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
// shift rows and add rcon
if (i % keyLen === 0) {
tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
rcon = rcon << 1 ^ (rcon >> 7) * 283;
}
}
encKey[i] = encKey[i - keyLen] ^ tmp;
}
// schedule decryption keys
for (j = 0; i; j++, i--) {
tmp = encKey[j & 3 ? i : i - 4];
if (i <= 4 || j < 4) {
decKey[j] = tmp;
} else {
decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
}
}
}
/**
* Expand the S-box tables.
*
* @private
*/
_createClass(AES, [{
key: '_precompute',
value: function _precompute() {
var encTable = this._tables[0],
decTable = this._tables[1],
sbox = encTable[4],
sboxInv = decTable[4],
i,
x,
xInv,
d = [],
th = [],
x2,
x4,
x8,
s,
tEnc,
tDec;
// Compute double and third tables
for (i = 0; i < 256; i++) {
th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
}
for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
// Compute sbox
s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
s = s >> 8 ^ s & 255 ^ 99;
sbox[x] = s;
sboxInv[s] = x;
// Compute MixColumns
x8 = d[x4 = d[x2 = d[x]]];
tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
tEnc = d[s] * 0x101 ^ s * 0x1010100;
for (i = 0; i < 4; i++) {
encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
}
}
// Compactify. Considerable speedup on Firefox.
for (i = 0; i < 5; i++) {
encTable[i] = encTable[i].slice(0);
decTable[i] = decTable[i].slice(0);
}
}
/**
* Decrypt 16 bytes, specified as four 32-bit words.
* @param encrypted0 {number} the first word to decrypt
* @param encrypted1 {number} the second word to decrypt
* @param encrypted2 {number} the third word to decrypt
* @param encrypted3 {number} the fourth word to decrypt
* @param out {Int32Array} the array to write the decrypted words
* into
* @param offset {number} the offset into the output array to start
* writing results
* @return {Array} The plaintext.
*/
}, {
key: 'decrypt',
value: function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
var key = this._key[1],
// state variables a,b,c,d are loaded with pre-whitened data
a = encrypted0 ^ key[0],
b = encrypted3 ^ key[1],
c = encrypted2 ^ key[2],
d = encrypted1 ^ key[3],
a2,
b2,
c2,
nInnerRounds = key.length / 4 - 2,
// key.length === 2 ?
i,
kIndex = 4,
table = this._tables[1],
// load up the tables
table0 = table[0],
table1 = table[1],
table2 = table[2],
table3 = table[3],
sbox = table[4];
// Inner rounds. Cribbed from OpenSSL.
for (i = 0; i < nInnerRounds; i++) {
a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
kIndex += 4;
a = a2;b = b2;c = c2;
}
// Last round.
for (i = 0; i < 4; i++) {
out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
a2 = a;a = b;b = c;c = d;d = a2;
}
}
}]);
return AES;
}();
exports.default = AES;
},{}],11:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /*
*
* This file contains an adaptation of the AES decryption algorithm
* from the Standford Javascript Cryptography Library. That work is
* covered by the following copyright and permissions notice:
*
* Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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 AUTHORS ``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 <COPYRIGHT HOLDER> 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.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the authors.
*/
var _aes = require('./aes');
var _aes2 = _interopRequireDefault(_aes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var AES128Decrypter = function () {
function AES128Decrypter(key, initVector) {
_classCallCheck(this, AES128Decrypter);
this.key = key;
this.iv = initVector;
}
/**
* Convert network-order (big-endian) bytes into their little-endian
* representation.
*/
_createClass(AES128Decrypter, [{
key: 'ntoh',
value: function ntoh(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
}
/**
* Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
* @param encrypted {Uint8Array} the encrypted bytes
* @param key {Uint32Array} the bytes of the decryption key
* @param initVector {Uint32Array} the initialization vector (IV) to
* use for the first round of CBC.
* @return {Uint8Array} the decrypted bytes
*
* @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
* @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
* @see https://tools.ietf.org/html/rfc2315
*/
}, {
key: 'doDecrypt',
value: function doDecrypt(encrypted, key, initVector) {
var
// word-level access to the encrypted bytes
encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2),
decipher = new _aes2.default(Array.prototype.slice.call(key)),
// byte and word-level access for the decrypted output
decrypted = new Uint8Array(encrypted.byteLength),
decrypted32 = new Int32Array(decrypted.buffer),
// temporary variables for working with the IV, encrypted, and
// decrypted data
init0,
init1,
init2,
init3,
encrypted0,
encrypted1,
encrypted2,
encrypted3,
// iteration variable
wordIx;
// pull out the words of the IV to ensure we don't modify the
// passed-in reference and easier access
init0 = ~ ~initVector[0];
init1 = ~ ~initVector[1];
init2 = ~ ~initVector[2];
init3 = ~ ~initVector[3];
// decrypt four word sequences, applying cipher-block chaining (CBC)
// to each decrypted block
for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
// convert big-endian (network order) words into little-endian
// (javascript order)
encrypted0 = ~ ~this.ntoh(encrypted32[wordIx]);
encrypted1 = ~ ~this.ntoh(encrypted32[wordIx + 1]);
encrypted2 = ~ ~this.ntoh(encrypted32[wordIx + 2]);
encrypted3 = ~ ~this.ntoh(encrypted32[wordIx + 3]);
// decrypt the block
decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx);
// XOR with the IV, and restore network byte-order to obtain the
// plaintext
decrypted32[wordIx] = this.ntoh(decrypted32[wordIx] ^ init0);
decrypted32[wordIx + 1] = this.ntoh(decrypted32[wordIx + 1] ^ init1);
decrypted32[wordIx + 2] = this.ntoh(decrypted32[wordIx + 2] ^ init2);
decrypted32[wordIx + 3] = this.ntoh(decrypted32[wordIx + 3] ^ init3);
// setup the IV for the next round
init0 = encrypted0;
init1 = encrypted1;
init2 = encrypted2;
init3 = encrypted3;
}
return decrypted;
}
}, {
key: 'localDecrypt',
value: function localDecrypt(encrypted, key, initVector, decrypted) {
var bytes = this.doDecrypt(encrypted, key, initVector);
decrypted.set(bytes, encrypted.byteOffset);
}
}, {
key: 'decrypt',
value: function decrypt(encrypted) {
var step = 4 * 8000,
//encrypted32 = new Int32Array(encrypted.buffer),
encrypted32 = new Int32Array(encrypted),
decrypted = new Uint8Array(encrypted.byteLength),
i = 0;
// split up the encryption job and do the individual chunks asynchronously
var key = this.key;
var initVector = this.iv;
this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted);
for (i = step; i < encrypted32.length; i += step) {
initVector = new Uint32Array([this.ntoh(encrypted32[i - 4]), this.ntoh(encrypted32[i - 3]), this.ntoh(encrypted32[i - 2]), this.ntoh(encrypted32[i - 1])]);
this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted);
}
return decrypted;
}
}]);
return AES128Decrypter;
}();
exports.default = AES128Decrypter;
},{"./aes":10}],12:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /*
* AES128 decryption.
*/
var _aes128Decrypter = require('./aes128-decrypter');
var _aes128Decrypter2 = _interopRequireDefault(_aes128Decrypter);
var _errors = require('../errors');
var _logger = require('../utils/logger');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Decrypter = function () {
function Decrypter(hls) {
_classCallCheck(this, Decrypter);
this.hls = hls;
try {
var browserCrypto = window ? window.crypto : crypto;
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
this.disableWebCrypto = !this.subtle;
} catch (e) {
this.disableWebCrypto = true;
}
}
_createClass(Decrypter, [{
key: 'destroy',
value: function destroy() {}
}, {
key: 'decrypt',
value: function decrypt(data, key, iv, callback) {
if (this.disableWebCrypto && this.hls.config.enableSoftwareAES) {
this.decryptBySoftware(data, key, iv, callback);
} else {
this.decryptByWebCrypto(data, key, iv, callback);
}
}
}, {
key: 'decryptByWebCrypto',
value: function decryptByWebCrypto(data, key, iv, callback) {
var _this = this;
_logger.logger.log('decrypting by WebCrypto API');
this.subtle.importKey('raw', key, { name: 'AES-CBC', length: 128 }, false, ['decrypt']).then(function (importedKey) {
_this.subtle.decrypt({ name: 'AES-CBC', iv: iv.buffer }, importedKey, data).then(callback).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
});
}).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
});
}
}, {
key: 'decryptBySoftware',
value: function decryptBySoftware(data, key8, iv8, callback) {
_logger.logger.log('decrypting by JavaScript Implementation');
var view = new DataView(key8.buffer);
var key = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
view = new DataView(iv8.buffer);
var iv = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
var decrypter = new _aes128Decrypter2.default(key, iv);
callback(decrypter.decrypt(data).buffer);
}
}, {
key: 'onWebCryptoError',
value: function onWebCryptoError(err, data, key, iv, callback) {
if (this.hls.config.enableSoftwareAES) {
_logger.logger.log('disabling to use WebCrypto API');
this.disableWebCrypto = true;
this.decryptBySoftware(data, key, iv, callback);
} else {
_logger.logger.error('decrypting error : ' + err.message);
this.hls.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
}
}
}]);
return Decrypter;
}();
exports.default = Decrypter;
},{"../errors":21,"../utils/logger":38,"./aes128-decrypter":11}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* AAC demuxer
*/
var _adts = require('./adts');
var _adts2 = _interopRequireDefault(_adts);
var _logger = require('../utils/logger');
var _id = require('../demux/id3');
var _id2 = _interopRequireDefault(_id);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var AACDemuxer = function () {
function AACDemuxer(observer, remuxerClass) {
_classCallCheck(this, AACDemuxer);
this.observer = observer;
this.remuxerClass = remuxerClass;
this.remuxer = new this.remuxerClass(observer);
this._aacTrack = { container: 'audio/adts', type: 'audio', id: -1, sequenceNumber: 0, samples: [], len: 0 };
}
_createClass(AACDemuxer, [{
key: 'push',
// feed incoming data to the front of the parsing pipeline
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
var track = this._aacTrack,
id3 = new _id2.default(data),
pts = 90 * id3.timeStamp,
config,
frameLength,
frameDuration,
frameIndex,
offset,
headerLength,
stamp,
len,
aacSample;
// look for ADTS header (0xFFFx)
for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
if (!track.audiosamplerate) {
config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec);
track.config = config.config;
track.audiosamplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.duration = duration;
_logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
}
frameIndex = 0;
frameDuration = 1024 * 90000 / track.audiosamplerate;
while (offset + 5 < len) {
// The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
// retrieve frame size
frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
frameLength -= headerLength;
//stamp = pes.pts;
if (frameLength > 0 && offset + headerLength + frameLength <= len) {
stamp = pts + frameIndex * frameDuration;
//logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
track.samples.push(aacSample);
track.len += frameLength;
offset += frameLength + headerLength;
frameIndex++;
// look for ADTS header (0xFFFx)
for (; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
} else {
break;
}
}
this.remuxer.remux(this._aacTrack, { samples: [] }, { samples: [{ pts: pts, dts: pts, unit: id3.payload }] }, { samples: [] }, timeOffset);
}
}, {
key: 'destroy',
value: function destroy() {}
}], [{
key: 'probe',
value: function probe(data) {
// check if data contains ID3 timestamp and ADTS sync worc
var id3 = new _id2.default(data),
offset,
len;
if (id3.hasTimeStamp) {
// look for ADTS header (0xFFFx)
for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
//logger.log('ADTS sync word found !');
return true;
}
}
}
return false;
}
}]);
return AACDemuxer;
}();
exports.default = AACDemuxer;
},{"../demux/id3":19,"../utils/logger":38,"./adts":14}],14:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* ADTS parser helper
*/
var _logger = require('../utils/logger');
var _errors = require('../errors');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ADTS = function () {
function ADTS() {
_classCallCheck(this, ADTS);
}
_createClass(ADTS, null, [{
key: 'getAudioConfig',
value: function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType,
// :int
adtsSampleingIndex,
// :int
adtsExtensionSampleingIndex,
// :int
adtsChanelConfig,
// :int
config,
userAgent = navigator.userAgent.toLowerCase(),
adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
// byte 2
adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
// byte 3
adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
_logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
// firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (userAgent.indexOf('firefox') !== -1) {
if (adtsSampleingIndex >= 6) {
adtsObjectType = 5;
config = new Array(4);
// HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
} else {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
}
// Android : always use AAC
} else if (userAgent.indexOf('android') !== -1) {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
} else {
/* for other browsers (chrome ...)
always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
*/
adtsObjectType = 5;
config = new Array(4);
// if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
// HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
} else {
// if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
// Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || !audioCodec && adtsChanelConfig === 1) {
adtsObjectType = 2;
config = new Array(2);
}
adtsExtensionSampleingIndex = adtsSampleingIndex;
}
}
/* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
Audio Profile / Audio Object Type
0: Null
1: AAC Main
2: AAC LC (Low Complexity)
3: AAC SSR (Scalable Sample Rate)
4: AAC LTP (Long Term Prediction)
5: SBR (Spectral Band Replication)
6: AAC Scalable
sampling freq
0: 96000 Hz
1: 88200 Hz
2: 64000 Hz
3: 48000 Hz
4: 44100 Hz
5: 32000 Hz
6: 24000 Hz
7: 22050 Hz
8: 16000 Hz
9: 12000 Hz
10: 11025 Hz
11: 8000 Hz
12: 7350 Hz
13: Reserved
14: Reserved
15: frequency is written explictly
Channel Configurations
These are the channel configurations:
0: Defined in AOT Specifc Config
1: 1 channel: front-center
2: 2 channels: front-left, front-right
*/
// audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
config[0] = adtsObjectType << 3;
// samplingFrequencyIndex
config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
config[1] |= (adtsSampleingIndex & 0x01) << 7;
// channelConfiguration
config[1] |= adtsChanelConfig << 3;
if (adtsObjectType === 5) {
// adtsExtensionSampleingIndex
config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
// adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
// https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
config[2] |= 2 << 2;
config[3] = 0;
}
return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType };
}
}]);
return ADTS;
}();
exports.default = ADTS;
},{"../errors":21,"../utils/logger":38}],15:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /* inline demuxer.
* probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
*/
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _errors = require('../errors');
var _aacdemuxer = require('../demux/aacdemuxer');
var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer);
var _tsdemuxer = require('../demux/tsdemuxer');
var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer);
var _mp4Remuxer = require('../remux/mp4-remuxer');
var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
var _passthroughRemuxer = require('../remux/passthrough-remuxer');
var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var DemuxerInline = function () {
function DemuxerInline(hls, typeSupported) {
_classCallCheck(this, DemuxerInline);
this.hls = hls;
this.typeSupported = typeSupported;
}
_createClass(DemuxerInline, [{
key: 'destroy',
value: function destroy() {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.destroy();
}
}
}, {
key: 'push',
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
var demuxer = this.demuxer;
if (!demuxer) {
var hls = this.hls;
// probe for content type
if (_tsdemuxer2.default.probe(data)) {
if (this.typeSupported.mp2t === true) {
demuxer = new _tsdemuxer2.default(hls, _passthroughRemuxer2.default);
} else {
demuxer = new _tsdemuxer2.default(hls, _mp4Remuxer2.default);
}
} else if (_aacdemuxer2.default.probe(data)) {
demuxer = new _aacdemuxer2.default(hls, _mp4Remuxer2.default);
} else {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });
return;
}
this.demuxer = demuxer;
}
demuxer.push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
}
}]);
return DemuxerInline;
}();
exports.default = DemuxerInline;
},{"../demux/aacdemuxer":13,"../demux/tsdemuxer":20,"../errors":21,"../events":23,"../remux/mp4-remuxer":32,"../remux/passthrough-remuxer":33}],16:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _demuxerInline = require('../demux/demuxer-inline');
var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _events3 = require('events');
var _events4 = _interopRequireDefault(_events3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DemuxerWorker = function DemuxerWorker(self) {
// observer setup
var observer = new _events4.default();
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
self.addEventListener('message', function (ev) {
var data = ev.data;
//console.log('demuxer cmd:' + data.cmd);
switch (data.cmd) {
case 'init':
self.demuxer = new _demuxerInline2.default(observer, data.typeSupported);
break;
case 'demux':
self.demuxer.push(new Uint8Array(data.data), data.audioCodec, data.videoCodec, data.timeOffset, data.cc, data.level, data.sn, data.duration);
break;
default:
break;
}
});
// listen to events triggered by Demuxer
observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, function (ev, data) {
self.postMessage({ event: ev, tracks: data.tracks, unique: data.unique });
});
observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) {
var objData = { event: ev, type: data.type, startPTS: data.startPTS, endPTS: data.endPTS, startDTS: data.startDTS, endDTS: data.endDTS, data1: data.data1.buffer, data2: data.data2.buffer, nb: data.nb };
// pass data1/data2 as transferable object (no copy)
self.postMessage(objData, [objData.data1, objData.data2]);
});
observer.on(_events2.default.FRAG_PARSED, function (event) {
self.postMessage({ event: event });
});
observer.on(_events2.default.ERROR, function (event, data) {
self.postMessage({ event: event, data: data });
});
observer.on(_events2.default.FRAG_PARSING_METADATA, function (event, data) {
var objData = { event: event, samples: data.samples };
self.postMessage(objData);
});
observer.on(_events2.default.FRAG_PARSING_USERDATA, function (event, data) {
var objData = { event: event, samples: data.samples };
self.postMessage(objData);
});
}; /* demuxer web worker.
* - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
* - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.
*/
exports.default = DemuxerWorker;
},{"../demux/demuxer-inline":15,"../events":23,"events":1}],17:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _demuxerInline = require('../demux/demuxer-inline');
var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
var _demuxerWorker = require('../demux/demuxer-worker');
var _demuxerWorker2 = _interopRequireDefault(_demuxerWorker);
var _logger = require('../utils/logger');
var _decrypter = require('../crypt/decrypter');
var _decrypter2 = _interopRequireDefault(_decrypter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Demuxer = function () {
function Demuxer(hls) {
_classCallCheck(this, Demuxer);
this.hls = hls;
var typeSupported = {
mp4: MediaSource.isTypeSupported('video/mp4'),
mp2t: hls.config.enableMP2TPassThrough && MediaSource.isTypeSupported('video/mp2t')
};
if (hls.config.enableWorker && typeof Worker !== 'undefined') {
_logger.logger.log('demuxing in webworker');
try {
var work = require('webworkify');
this.w = work(_demuxerWorker2.default);
this.onwmsg = this.onWorkerMessage.bind(this);
this.w.addEventListener('message', this.onwmsg);
this.w.postMessage({ cmd: 'init', typeSupported: typeSupported });
} catch (err) {
_logger.logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline');
this.demuxer = new _demuxerInline2.default(hls, typeSupported);
}
} else {
this.demuxer = new _demuxerInline2.default(hls, typeSupported);
}
this.demuxInitialized = true;
}
_createClass(Demuxer, [{
key: 'destroy',
value: function destroy() {
if (this.w) {
this.w.removeEventListener('message', this.onwmsg);
this.w.terminate();
this.w = null;
} else {
this.demuxer.destroy();
this.demuxer = null;
}
if (this.decrypter) {
this.decrypter.destroy();
this.decrypter = null;
}
}
}, {
key: 'pushDecrypted',
value: function pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
if (this.w) {
// post fragment payload as transferable objects (no copy)
this.w.postMessage({ cmd: 'demux', data: data, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, cc: cc, level: level, sn: sn, duration: duration }, [data]);
} else {
this.demuxer.push(new Uint8Array(data), audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
}
}
}, {
key: 'push',
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, decryptdata) {
if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
if (this.decrypter == null) {
this.decrypter = new _decrypter2.default(this.hls);
}
var localthis = this;
this.decrypter.decrypt(data, decryptdata.key, decryptdata.iv, function (decryptedData) {
localthis.pushDecrypted(decryptedData, audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
});
} else {
this.pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
}
}
}, {
key: 'onWorkerMessage',
value: function onWorkerMessage(ev) {
var data = ev.data;
//console.log('onWorkerMessage:' + data.event);
switch (data.event) {
case _events2.default.FRAG_PARSING_INIT_SEGMENT:
var obj = {};
obj.tracks = data.tracks;
obj.unique = data.unique;
this.hls.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, obj);
break;
case _events2.default.FRAG_PARSING_DATA:
this.hls.trigger(_events2.default.FRAG_PARSING_DATA, {
data1: new Uint8Array(data.data1),
data2: new Uint8Array(data.data2),
startPTS: data.startPTS,
endPTS: data.endPTS,
startDTS: data.startDTS,
endDTS: data.endDTS,
type: data.type,
nb: data.nb
});
break;
case _events2.default.FRAG_PARSING_METADATA:
this.hls.trigger(_events2.default.FRAG_PARSING_METADATA, {
samples: data.samples
});
break;
case _events2.default.FRAG_PARSING_USERDATA:
this.hls.trigger(_events2.default.FRAG_PARSING_USERDATA, {
samples: data.samples
});
break;
default:
this.hls.trigger(data.event, data.data);
break;
}
}
}]);
return Demuxer;
}();
exports.default = Demuxer;
},{"../crypt/decrypter":12,"../demux/demuxer-inline":15,"../demux/demuxer-worker":16,"../events":23,"../utils/logger":38,"webworkify":2}],18:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ExpGolomb = function () {
function ExpGolomb(data) {
_classCallCheck(this, ExpGolomb);
this.data = data;
// the number of bytes left to examine in this.data
this.bytesAvailable = this.data.byteLength;
// the current word being examined
this.word = 0; // :uint
// the number of bits left to examine in the current word
this.bitsAvailable = 0; // :uint
}
// ():void
_createClass(ExpGolomb, [{
key: 'loadWord',
value: function loadWord() {
var position = this.data.byteLength - this.bytesAvailable,
workingBytes = new Uint8Array(4),
availableBytes = Math.min(4, this.bytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(this.data.subarray(position, position + availableBytes));
this.word = new DataView(workingBytes.buffer).getUint32(0);
// track the amount of this.data that has been processed
this.bitsAvailable = availableBytes * 8;
this.bytesAvailable -= availableBytes;
}
// (count:int):void
}, {
key: 'skipBits',
value: function skipBits(count) {
var skipBytes; // :int
if (this.bitsAvailable > count) {
this.word <<= count;
this.bitsAvailable -= count;
} else {
count -= this.bitsAvailable;
skipBytes = count >> 3;
count -= skipBytes >> 3;
this.bytesAvailable -= skipBytes;
this.loadWord();
this.word <<= count;
this.bitsAvailable -= count;
}
}
// (size:int):uint
}, {
key: 'readBits',
value: function readBits(size) {
var bits = Math.min(this.bitsAvailable, size),
// :uint
valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
_logger.logger.error('Cannot read more than 32 bits at a time');
}
this.bitsAvailable -= bits;
if (this.bitsAvailable > 0) {
this.word <<= bits;
} else if (this.bytesAvailable > 0) {
this.loadWord();
}
bits = size - bits;
if (bits > 0) {
return valu << bits | this.readBits(bits);
} else {
return valu;
}
}
// ():uint
}, {
key: 'skipLZ',
value: function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) {
// the first bit of working word is 1
this.word <<= leadingZeroCount;
this.bitsAvailable -= leadingZeroCount;
return leadingZeroCount;
}
}
// we exhausted word and still have not found a 1
this.loadWord();
return leadingZeroCount + this.skipLZ();
}
// ():void
}, {
key: 'skipUEG',
value: function skipUEG() {
this.skipBits(1 + this.skipLZ());
}
// ():void
}, {
key: 'skipEG',
value: function skipEG() {
this.skipBits(1 + this.skipLZ());
}
// ():uint
}, {
key: 'readUEG',
value: function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
}
// ():int
}, {
key: 'readEG',
value: function readEG() {
var valu = this.readUEG(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
} else {
return -1 * (valu >>> 1); // divide by two then make it negative
}
}
// Some convenience functions
// :Boolean
}, {
key: 'readBoolean',
value: function readBoolean() {
return 1 === this.readBits(1);
}
// ():int
}, {
key: 'readUByte',
value: function readUByte() {
return this.readBits(8);
}
// ():int
}, {
key: 'readUShort',
value: function readUShort() {
return this.readBits(16);
}
// ():int
}, {
key: 'readUInt',
value: function readUInt() {
return this.readBits(32);
}
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count {number} the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
}, {
key: 'skipScalingList',
value: function skipScalingList(count) {
var lastScale = 8,
nextScale = 8,
j,
deltaScale;
for (j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = this.readEG();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = nextScale === 0 ? lastScale : nextScale;
}
}
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
}, {
key: 'readSPS',
value: function readSPS() {
var frameCropLeftOffset = 0,
frameCropRightOffset = 0,
frameCropTopOffset = 0,
frameCropBottomOffset = 0,
sarScale = 1,
profileIdc,
profileCompat,
levelIdc,
numRefFramesInPicOrderCntCycle,
picWidthInMbsMinus1,
picHeightInMapUnitsMinus1,
frameMbsOnlyFlag,
scalingListCount,
i;
this.readUByte();
profileIdc = this.readUByte(); // profile_idc
profileCompat = this.readBits(5); // constraint_set[0-4]_flag, u(5)
this.skipBits(3); // reserved_zero_3bits u(3),
levelIdc = this.readUByte(); //level_idc u(8)
this.skipUEG(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
var chromaFormatIdc = this.readUEG();
if (chromaFormatIdc === 3) {
this.skipBits(1); // separate_colour_plane_flag
}
this.skipUEG(); // bit_depth_luma_minus8
this.skipUEG(); // bit_depth_chroma_minus8
this.skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (this.readBoolean()) {
// seq_scaling_matrix_present_flag
scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (this.readBoolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
this.skipScalingList(16);
} else {
this.skipScalingList(64);
}
}
}
}
}
this.skipUEG(); // log2_max_frame_num_minus4
var picOrderCntType = this.readUEG();
if (picOrderCntType === 0) {
this.readUEG(); //log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
this.skipBits(1); // delta_pic_order_always_zero_flag
this.skipEG(); // offset_for_non_ref_pic
this.skipEG(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = this.readUEG();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
this.skipEG(); // offset_for_ref_frame[ i ]
}
}
this.skipUEG(); // max_num_ref_frames
this.skipBits(1); // gaps_in_frame_num_value_allowed_flag
picWidthInMbsMinus1 = this.readUEG();
picHeightInMapUnitsMinus1 = this.readUEG();
frameMbsOnlyFlag = this.readBits(1);
if (frameMbsOnlyFlag === 0) {
this.skipBits(1); // mb_adaptive_frame_field_flag
}
this.skipBits(1); // direct_8x8_inference_flag
if (this.readBoolean()) {
// frame_cropping_flag
frameCropLeftOffset = this.readUEG();
frameCropRightOffset = this.readUEG();
frameCropTopOffset = this.readUEG();
frameCropBottomOffset = this.readUEG();
}
if (this.readBoolean()) {
// vui_parameters_present_flag
if (this.readBoolean()) {
// aspect_ratio_info_present_flag
var sarRatio = void 0;
var aspectRatioIdc = this.readUByte();
switch (aspectRatioIdc) {
case 1:
sarRatio = [1, 1];break;
case 2:
sarRatio = [12, 11];break;
case 3:
sarRatio = [10, 11];break;
case 4:
sarRatio = [16, 11];break;
case 5:
sarRatio = [40, 33];break;
case 6:
sarRatio = [24, 11];break;
case 7:
sarRatio = [20, 11];break;
case 8:
sarRatio = [32, 11];break;
case 9:
sarRatio = [80, 33];break;
case 10:
sarRatio = [18, 11];break;
case 11:
sarRatio = [15, 11];break;
case 12:
sarRatio = [64, 33];break;
case 13:
sarRatio = [160, 99];break;
case 14:
sarRatio = [4, 3];break;
case 15:
sarRatio = [3, 2];break;
case 16:
sarRatio = [2, 1];break;
case 255:
{
sarRatio = [this.readUByte() << 8 | this.readUByte(), this.readUByte() << 8 | this.readUByte()];
break;
}
}
if (sarRatio) {
sarScale = sarRatio[0] / sarRatio[1];
}
}
}
return {
width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)
};
}
}, {
key: 'readSliceType',
value: function readSliceType() {
// skip NALu type
this.readUByte();
// discard first_mb_in_slice
this.readUEG();
// return slice_type
return this.readUEG();
}
}]);
return ExpGolomb;
}();
exports.default = ExpGolomb;
},{"../utils/logger":38}],19:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* ID3 parser
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//import Hex from '../utils/hex';
var ID3 = function () {
function ID3(data) {
_classCallCheck(this, ID3);
this._hasTimeStamp = false;
var offset = 0,
byte1,
byte2,
byte3,
byte4,
tagSize,
endPos,
header,
len;
do {
header = this.readUTF(data, offset, 3);
offset += 3;
// first check for ID3 header
if (header === 'ID3') {
// skip 24 bits
offset += 3;
// retrieve tag(s) length
byte1 = data[offset++] & 0x7f;
byte2 = data[offset++] & 0x7f;
byte3 = data[offset++] & 0x7f;
byte4 = data[offset++] & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
endPos = offset + tagSize;
//logger.log(`ID3 tag found, size/end: ${tagSize}/${endPos}`);
// read ID3 tags
this._parseID3Frames(data, offset, endPos);
offset = endPos;
} else if (header === '3DI') {
// http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer
offset += 7;
_logger.logger.log('3DI footer found, end: ' + offset);
} else {
offset -= 3;
len = offset;
if (len) {
//logger.log(`ID3 len: ${len}`);
if (!this.hasTimeStamp) {
_logger.logger.warn('ID3 tag found, but no timestamp');
}
this._length = len;
this._payload = data.subarray(0, len);
}
return;
}
} while (true);
}
_createClass(ID3, [{
key: 'readUTF',
value: function readUTF(data, start, len) {
var result = '',
offset = start,
end = start + len;
do {
result += String.fromCharCode(data[offset++]);
} while (offset < end);
return result;
}
}, {
key: '_parseID3Frames',
value: function _parseID3Frames(data, offset, endPos) {
var tagId, tagLen, tagStart, tagFlags, timestamp;
while (offset + 8 <= endPos) {
tagId = this.readUTF(data, offset, 4);
offset += 4;
tagLen = data[offset++] << 24 + data[offset++] << 16 + data[offset++] << 8 + data[offset++];
tagFlags = data[offset++] << 8 + data[offset++];
tagStart = offset;
//logger.log("ID3 tag id:" + tagId);
switch (tagId) {
case 'PRIV':
//logger.log('parse frame:' + Hex.hexDump(data.subarray(offset,endPos)));
// owner should be "com.apple.streaming.transportStreamTimestamp"
if (this.readUTF(data, offset, 44) === 'com.apple.streaming.transportStreamTimestamp') {
offset += 44;
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
offset += 4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts33Bit = data[offset++] & 0x1;
this._hasTimeStamp = true;
timestamp = ((data[offset++] << 23) + (data[offset++] << 15) + (data[offset++] << 7) + data[offset++]) / 45;
if (pts33Bit) {
timestamp += 47721858.84; // 2^32 / 90
}
timestamp = Math.round(timestamp);
_logger.logger.trace('ID3 timestamp found: ' + timestamp);
this._timeStamp = timestamp;
}
break;
default:
break;
}
}
}
}, {
key: 'hasTimeStamp',
get: function get() {
return this._hasTimeStamp;
}
}, {
key: 'timeStamp',
get: function get() {
return this._timeStamp;
}
}, {
key: 'length',
get: function get() {
return this._length;
}
}, {
key: 'payload',
get: function get() {
return this._payload;
}
}]);
return ID3;
}();
exports.default = ID3;
},{"../utils/logger":38}],20:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* highly optimized TS demuxer:
* parse PAT, PMT
* extract PES packet from audio and video PIDs
* extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
* trigger the remuxer upon parsing completion
* it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
* it also controls the remuxing process :
* upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
*/
// import Hex from '../utils/hex';
var _adts = require('./adts');
var _adts2 = _interopRequireDefault(_adts);
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _expGolomb = require('./exp-golomb');
var _expGolomb2 = _interopRequireDefault(_expGolomb);
var _logger = require('../utils/logger');
var _errors = require('../errors');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var TSDemuxer = function () {
function TSDemuxer(observer, remuxerClass) {
_classCallCheck(this, TSDemuxer);
this.observer = observer;
this.remuxerClass = remuxerClass;
this.lastCC = 0;
this.remuxer = new this.remuxerClass(observer);
}
_createClass(TSDemuxer, [{
key: 'switchLevel',
value: function switchLevel() {
this.pmtParsed = false;
this._pmtId = -1;
this._avcTrack = { container: 'video/mp2t', type: 'video', id: -1, sequenceNumber: 0, samples: [], len: 0, nbNalu: 0 };
this._aacTrack = { container: 'video/mp2t', type: 'audio', id: -1, sequenceNumber: 0, samples: [], len: 0 };
this._id3Track = { type: 'id3', id: -1, sequenceNumber: 0, samples: [], len: 0 };
this._txtTrack = { type: 'text', id: -1, sequenceNumber: 0, samples: [], len: 0 };
// flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = null;
this.avcNaluState = 0;
this.remuxer.switchLevel();
}
}, {
key: 'insertDiscontinuity',
value: function insertDiscontinuity() {
this.switchLevel();
this.remuxer.insertDiscontinuity();
}
// feed incoming data to the front of the parsing pipeline
}, {
key: 'push',
value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
var avcData,
aacData,
id3Data,
start,
len = data.length,
stt,
pid,
atf,
offset,
codecsOnly = this.remuxer.passthrough,
unknownPIDs = false;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.timeOffset = timeOffset;
this._duration = duration;
this.contiguous = false;
if (cc !== this.lastCC) {
_logger.logger.log('discontinuity detected');
this.insertDiscontinuity();
this.lastCC = cc;
}
if (level !== this.lastLevel) {
_logger.logger.log('level switch detected');
this.switchLevel();
this.lastLevel = level;
} else if (sn === this.lastSN + 1) {
this.contiguous = true;
}
this.lastSN = sn;
var pmtParsed = this.pmtParsed,
avcId = this._avcTrack.id,
aacId = this._aacTrack.id,
id3Id = this._id3Track.id;
// don't parse last TS packet if incomplete
len -= len % 188;
// loop through TS packets
for (start = 0; start < len; start += 188) {
if (data[start] === 0x47) {
stt = !!(data[start + 1] & 0x40);
// pid is a 13-bit field starting at the last bit of TS[1]
pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
atf = (data[start + 3] & 0x30) >> 4;
// if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
if (atf > 1) {
offset = start + 5 + data[start + 4];
// continue if there is only adaptation field
if (offset === start + 188) {
continue;
}
} else {
offset = start + 4;
}
if (pmtParsed) {
if (pid === avcId) {
if (stt) {
if (avcData) {
this._parseAVCPES(this._parsePES(avcData));
if (codecsOnly) {
// if we have video codec info AND
// if audio PID is undefined OR if we have audio codec info,
// we have all codec info !
if (this._avcTrack.codec && (aacId === -1 || this._aacTrack.codec)) {
this.remux(data);
return;
}
}
}
avcData = { data: [], size: 0 };
}
if (avcData) {
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
}
} else if (pid === aacId) {
if (stt) {
if (aacData) {
this._parseAACPES(this._parsePES(aacData));
if (codecsOnly) {
// here we now that we have audio codec info
// if video PID is undefined OR if we have video codec info,
// we have all codec infos !
if (this._aacTrack.codec && (avcId === -1 || this._avcTrack.codec)) {
this.remux(data);
return;
}
}
}
aacData = { data: [], size: 0 };
}
if (aacData) {
aacData.data.push(data.subarray(offset, start + 188));
aacData.size += start + 188 - offset;
}
} else if (pid === id3Id) {
if (stt) {
if (id3Data) {
this._parseID3PES(this._parsePES(id3Data));
}
id3Data = { data: [], size: 0 };
}
if (id3Data) {
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
}
}
} else {
if (stt) {
offset += data[offset] + 1;
}
if (pid === 0) {
this._parsePAT(data, offset);
} else if (pid === this._pmtId) {
this._parsePMT(data, offset);
pmtParsed = this.pmtParsed = true;
avcId = this._avcTrack.id;
aacId = this._aacTrack.id;
id3Id = this._id3Track.id;
if (unknownPIDs) {
_logger.logger.log('reparse from beginning');
unknownPIDs = false;
// we set it to -188, the += 188 in the for loop will reset start to 0
start = -188;
}
} else {
_logger.logger.log('unknown PID found before PAT/PMT');
unknownPIDs = true;
}
}
} else {
this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });
}
}
// parse last PES packet
if (avcData) {
this._parseAVCPES(this._parsePES(avcData));
}
if (aacData) {
this._parseAACPES(this._parsePES(aacData));
}
if (id3Data) {
this._parseID3PES(this._parsePES(id3Data));
}
this.remux(null);
}
}, {
key: 'remux',
value: function remux(data) {
this.remuxer.remux(this._aacTrack, this._avcTrack, this._id3Track, this._txtTrack, this.timeOffset, this.contiguous, data);
}
}, {
key: 'destroy',
value: function destroy() {
this.switchLevel();
this._initPTS = this._initDTS = undefined;
this._duration = 0;
}
}, {
key: '_parsePAT',
value: function _parsePAT(data, offset) {
// skip the PSI header and parse the first PMT entry
this._pmtId = (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
//logger.log('PMT PID:' + this._pmtId);
}
}, {
key: '_parsePMT',
value: function _parsePMT(data, offset) {
var sectionLength, tableEnd, programInfoLength, pid;
sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
tableEnd = offset + 3 + sectionLength - 4;
// to determine where the table is, we have to figure out how
// long the program info descriptors are
programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
// advance the offset to the first entry in the mapping table
offset += 12 + programInfoLength;
while (offset < tableEnd) {
pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
switch (data[offset]) {
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
case 0x0f:
//logger.log('AAC PID:' + pid);
this._aacTrack.id = pid;
break;
// Packetized metadata (ID3)
case 0x15:
//logger.log('ID3 PID:' + pid);
this._id3Track.id = pid;
break;
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
case 0x1b:
//logger.log('AVC PID:' + pid);
this._avcTrack.id = pid;
break;
default:
_logger.logger.log('unkown stream type:' + data[offset]);
break;
}
// move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
}
}
}, {
key: '_parsePES',
value: function _parsePES(stream) {
var i = 0,
frag,
pesFlags,
pesPrefix,
pesLen,
pesHdrLen,
pesData,
pesPts,
pesDts,
payloadStartOffset,
data = stream.data;
//retrieve PTS/DTS from first fragment
frag = data[0];
pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5];
pesFlags = frag[7];
if (pesFlags & 0xC0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
(frag[10] & 0xFF) * 4194304 + // 1 << 22
(frag[11] & 0xFE) * 16384 + // 1 << 14
(frag[12] & 0xFF) * 128 + // 1 << 7
(frag[13] & 0xFE) / 2;
// check if greater than 2^32 -1
if (pesPts > 4294967295) {
// decrement 2^33
pesPts -= 8589934592;
}
if (pesFlags & 0x40) {
pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
(frag[15] & 0xFF) * 4194304 + // 1 << 22
(frag[16] & 0xFE) * 16384 + // 1 << 14
(frag[17] & 0xFF) * 128 + // 1 << 7
(frag[18] & 0xFE) / 2;
// check if greater than 2^32 -1
if (pesDts > 4294967295) {
// decrement 2^33
pesDts -= 8589934592;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8];
payloadStartOffset = pesHdrLen + 9;
stream.size -= payloadStartOffset;
//reassemble PES packet
pesData = new Uint8Array(stream.size);
while (data.length) {
frag = data.shift();
var len = frag.byteLength;
if (payloadStartOffset) {
if (payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
} else {
return null;
}
}
}, {
key: '_parseAVCPES',
value: function _parseAVCPES(pes) {
var _this = this;
var track = this._avcTrack,
samples = track.samples,
units = this._parseAVCNALu(pes.data),
units2 = [],
debug = false,
key = false,
length = 0,
expGolombDecoder,
avcSample,
push,
i;
// no NALu found
if (units.length === 0 && samples.length > 0) {
// append pes.data to previous NAL unit
var lastavcSample = samples[samples.length - 1];
var lastUnit = lastavcSample.units.units[lastavcSample.units.units.length - 1];
var tmp = new Uint8Array(lastUnit.data.byteLength + pes.data.byteLength);
tmp.set(lastUnit.data, 0);
tmp.set(pes.data, lastUnit.data.byteLength);
lastUnit.data = tmp;
lastavcSample.units.length += pes.data.byteLength;
track.len += pes.data.byteLength;
}
//free pes.data to save up some memory
pes.data = null;
var debugString = '';
var pushAccesUnit = function () {
if (units2.length) {
// only push AVC sample if keyframe already found in this fragment OR
// keyframe found in last fragment (track.sps) AND
// samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
if (key === true || track.sps && (samples.length || this.contiguous)) {
avcSample = { units: { units: units2, length: length }, pts: pes.pts, dts: pes.dts, key: key };
samples.push(avcSample);
track.len += length;
track.nbNalu += units2.length;
}
units2 = [];
length = 0;
}
}.bind(this);
units.forEach(function (unit) {
switch (unit.type) {
//NDR
case 1:
push = true;
if (debug) {
debugString += 'NDR ';
}
break;
//IDR
case 5:
push = true;
if (debug) {
debugString += 'IDR ';
}
key = true;
break;
//SEI
case 6:
push = true;
if (debug) {
debugString += 'SEI ';
}
expGolombDecoder = new _expGolomb2.default(unit.data);
// skip frameType
expGolombDecoder.readUByte();
var payloadType = expGolombDecoder.readUByte();
// TODO: there can be more than one payload in an SEI packet...
// TODO: need to read type and size in a while loop to get them all
if (payloadType === 4) {
var payloadSize = 0;
do {
payloadSize = expGolombDecoder.readUByte();
} while (payloadSize === 255);
var countryCode = expGolombDecoder.readUByte();
if (countryCode === 181) {
var providerCode = expGolombDecoder.readUShort();
if (providerCode === 49) {
var userStructure = expGolombDecoder.readUInt();
if (userStructure === 0x47413934) {
var userDataType = expGolombDecoder.readUByte();
// Raw CEA-608 bytes wrapped in CEA-708 packet
if (userDataType === 3) {
var firstByte = expGolombDecoder.readUByte();
var secondByte = expGolombDecoder.readUByte();
var totalCCs = 31 & firstByte;
var byteArray = [firstByte, secondByte];
for (i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
_this._txtTrack.samples.push({ type: 3, pts: pes.pts, bytes: byteArray });
}
}
}
}
}
break;
//SPS
case 7:
push = true;
if (debug) {
debugString += 'SPS ';
}
if (!track.sps) {
expGolombDecoder = new _expGolomb2.default(unit.data);
var config = expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (i = 0; i < 3; i++) {
var h = codecarray[i].toString(16);
if (h.length < 2) {
h = '0' + h;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
//PPS
case 8:
push = true;
if (debug) {
debugString += 'PPS ';
}
if (!track.pps) {
track.pps = [unit.data];
}
break;
case 9:
push = false;
if (debug) {
debugString += 'AUD ';
}
pushAccesUnit();
break;
default:
push = false;
debugString += 'unknown NAL ' + unit.type + ' ';
break;
}
if (push) {
units2.push(unit);
length += unit.data.byteLength;
}
});
if (debug || debugString.length) {
_logger.logger.log(debugString);
}
pushAccesUnit();
}
}, {
key: '_parseAVCNALu',
value: function _parseAVCNALu(array) {
var i = 0,
len = array.byteLength,
value,
overflow,
state = this.avcNaluState;
var units = [],
unit,
unitType,
lastUnitStart,
lastUnitType;
//logger.log('PES:' + Hex.hexDump(array));
while (i < len) {
value = array[i++];
// finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01)
switch (state) {
case 0:
if (value === 0) {
state = 1;
}
break;
case 1:
if (value === 0) {
state = 2;
} else {
state = 0;
}
break;
case 2:
case 3:
if (value === 0) {
state = 3;
} else if (value === 1 && i < len) {
unitType = array[i] & 0x1f;
//logger.log('find NALU @ offset:' + i + ',type:' + unitType);
if (lastUnitStart) {
unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
//logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
units.push(unit);
} else {
// lastUnitStart is undefined => this is the first start code found in this PES packet
// first check if start code delimiter is overlapping between 2 PES packets,
// ie it started in last packet (lastState not zero)
// and ended at the beginning of this PES packet (i <= 4 - lastState)
var lastState = this.avcNaluState;
if (lastState && i <= 4 - lastState) {
// start delimiter overlapping between PES packets
// strip start delimiter bytes from the end of last NAL unit
var track = this._avcTrack,
samples = track.samples;
if (samples.length) {
var lastavcSample = samples[samples.length - 1],
lastUnits = lastavcSample.units.units,
lastUnit = lastUnits[lastUnits.length - 1];
// check if lastUnit had a state different from zero
if (lastUnit.state) {
// strip last bytes
lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
lastavcSample.units.length -= lastState;
track.len -= lastState;
}
}
}
// If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
overflow = i - state - 1;
if (overflow > 0) {
var _track = this._avcTrack,
_samples = _track.samples;
//logger.log('first NALU found with overflow:' + overflow);
if (_samples.length) {
var _lastavcSample = _samples[_samples.length - 1],
_lastUnits = _lastavcSample.units.units,
_lastUnit = _lastUnits[_lastUnits.length - 1],
tmp = new Uint8Array(_lastUnit.data.byteLength + overflow);
tmp.set(_lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), _lastUnit.data.byteLength);
_lastUnit.data = tmp;
_lastavcSample.units.length += overflow;
_track.len += overflow;
}
}
}
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
state = 0;
}
break;
default:
break;
}
}
if (lastUnitStart) {
unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
units.push(unit);
//logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
this.avcNaluState = state;
}
return units;
}
}, {
key: '_parseAACPES',
value: function _parseAACPES(pes) {
var track = this._aacTrack,
data = pes.data,
pts = pes.pts,
startOffset = 0,
duration = this._duration,
audioCodec = this.audioCodec,
aacOverFlow = this.aacOverFlow,
aacLastPTS = this.aacLastPTS,
config,
frameLength,
frameDuration,
frameIndex,
offset,
headerLength,
stamp,
len,
aacSample;
if (aacOverFlow) {
var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
tmp.set(aacOverFlow, 0);
tmp.set(data, aacOverFlow.byteLength);
//logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
data = tmp;
}
// look for ADTS header (0xFFFx)
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
// if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset) {
var reason, fatal;
if (offset < len - 1) {
reason = 'AAC PES did not start with ADTS header,offset:' + offset;
fatal = false;
} else {
reason = 'no ADTS header found in AAC PES';
fatal = true;
}
this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
if (fatal) {
return;
}
}
if (!track.audiosamplerate) {
config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec);
track.config = config.config;
track.audiosamplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.duration = duration;
_logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
}
frameIndex = 0;
frameDuration = 1024 * 90000 / track.audiosamplerate;
// if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
if (aacOverFlow && aacLastPTS) {
var newPTS = aacLastPTS + frameDuration;
if (Math.abs(newPTS - pts) > 1) {
_logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
pts = newPTS;
}
}
while (offset + 5 < len) {
// The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
// retrieve frame size
frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
frameLength -= headerLength;
//stamp = pes.pts;
if (frameLength > 0 && offset + headerLength + frameLength <= len) {
stamp = pts + frameIndex * frameDuration;
//logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
track.samples.push(aacSample);
track.len += frameLength;
offset += frameLength + headerLength;
frameIndex++;
// look for ADTS header (0xFFFx)
for (; offset < len - 1; offset++) {
if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
break;
}
}
} else {
break;
}
}
if (offset < len) {
aacOverFlow = data.subarray(offset, len);
//logger.log(`AAC: overflow detected:${len-offset}`);
} else {
aacOverFlow = null;
}
this.aacOverFlow = aacOverFlow;
this.aacLastPTS = stamp;
}
}, {
key: '_parseID3PES',
value: function _parseID3PES(pes) {
this._id3Track.samples.push(pes);
}
}], [{
key: 'probe',
value: function probe(data) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if (data.length >= 3 * 188 && data[0] === 0x47 && data[188] === 0x47 && data[2 * 188] === 0x47) {
return true;
} else {
return false;
}
}
}]);
return TSDemuxer;
}();
exports.default = TSDemuxer;
},{"../errors":21,"../events":23,"../utils/logger":38,"./adts":14,"./exp-golomb":18}],21:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var ErrorTypes = exports.ErrorTypes = {
// Identifier for a network error (loading error / timeout ...)
NETWORK_ERROR: 'networkError',
// Identifier for a media Error (video/parsing/mediasource error)
MEDIA_ERROR: 'mediaError',
// Identifier for all other errors
OTHER_ERROR: 'otherError'
};
var ErrorDetails = exports.ErrorDetails = {
// Identifier for a manifest load error - data: { url : faulty URL, response : XHR response}
MANIFEST_LOAD_ERROR: 'manifestLoadError',
// Identifier for a manifest load timeout - data: { url : faulty URL, response : XHR response}
MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
// Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
MANIFEST_PARSING_ERROR: 'manifestParsingError',
// Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
// Identifier for playlist load error - data: { url : faulty URL, response : XHR response}
LEVEL_LOAD_ERROR: 'levelLoadError',
// Identifier for playlist load timeout - data: { url : faulty URL, response : XHR response}
LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
// Identifier for a level switch error - data: { level : faulty level Id, event : error description}
LEVEL_SWITCH_ERROR: 'levelSwitchError',
// Identifier for fragment load error - data: { frag : fragment object, response : XHR response}
FRAG_LOAD_ERROR: 'fragLoadError',
// Identifier for fragment loop loading error - data: { frag : fragment object}
FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',
// Identifier for fragment load timeout error - data: { frag : fragment object}
FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
// Identifier for a fragment decryption error event - data: parsing error description
FRAG_DECRYPT_ERROR: 'fragDecryptError',
// Identifier for a fragment parsing error event - data: parsing error description
FRAG_PARSING_ERROR: 'fragParsingError',
// Identifier for decrypt key load error - data: { frag : fragment object, response : XHR response}
KEY_LOAD_ERROR: 'keyLoadError',
// Identifier for decrypt key load timeout error - data: { frag : fragment object}
KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
// Identifier for a buffer append error - data: append error description
BUFFER_APPEND_ERROR: 'bufferAppendError',
// Identifier for a buffer appending error event - data: appending error description
BUFFER_APPENDING_ERROR: 'bufferAppendingError',
// Identifier for a buffer stalled error event
BUFFER_STALLED_ERROR: 'bufferStalledError',
// Identifier for a buffer full event
BUFFER_FULL_ERROR: 'bufferFullError',
// Identifier for a buffer seek over hole event
BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
// Identifier for an internal exception happening inside hls.js while handling an event
INTERNAL_EXCEPTION: 'internalException'
};
},{}],22:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
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; }; }(); /*
*
* All objects in the event handling chain should inherit from this class
*
*/
var _logger = require('./utils/logger');
var _errors = require('./errors');
var _events = require('./events');
var _events2 = _interopRequireDefault(_events);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var EventHandler = function () {
function EventHandler(hls) {
_classCallCheck(this, EventHandler);
this.hls = hls;
this.onEvent = this.onEvent.bind(this);
for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
events[_key - 1] = arguments[_key];
}
this.handledEvents = events;
this.useGenericHandler = true;
this.registerListeners();
}
_createClass(EventHandler, [{
key: 'destroy',
value: function destroy() {
this.unregisterListeners();
}
}, {
key: 'isEventHandler',
value: function isEventHandler() {
return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
}
}, {
key: 'registerListeners',
value: function registerListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
if (event === 'hlsEventGeneric') {
throw new Error('Forbidden event name: ' + event);
}
this.hls.on(event, this.onEvent);
}.bind(this));
}
}
}, {
key: 'unregisterListeners',
value: function unregisterListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
this.hls.off(event, this.onEvent);
}.bind(this));
}
}
/*
* arguments: event (string), data (any)
*/
}, {
key: 'onEvent',
value: function onEvent(event, data) {
this.onEventGeneric(event, data);
}
}, {
key: 'onEventGeneric',
value: function onEventGeneric(event, data) {
var eventToFunction = function eventToFunction(event, data) {
var funcName = 'on' + event.replace('hls', '');
if (typeof this[funcName] !== 'function') {
throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
}
return this[funcName].bind(this, data);
};
try {
eventToFunction.call(this, event, data).call();
} catch (err) {
_logger.logger.error('internal error happened while processing ' + event + ':' + err.message);
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
}
}
}]);
return EventHandler;
}();
exports.default = EventHandler;
},{"./errors":21,"./events":23,"./utils/logger":38}],23:[function(require,module,exports){
'use strict';
module.exports = {
// fired before MediaSource is attaching to media element - data: { media }
MEDIA_ATTACHING: 'hlsMediaAttaching',
// fired when MediaSource has been succesfully attached to media element - data: { }
MEDIA_ATTACHED: 'hlsMediaAttached',
// fired before detaching MediaSource from media element - data: { }
MEDIA_DETACHING: 'hlsMediaDetaching',
// fired when MediaSource has been detached from media element - data: { }
MEDIA_DETACHED: 'hlsMediaDetached',
// fired when we buffer is going to be resetted
BUFFER_RESET: 'hlsBufferReset',
// fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
BUFFER_CODECS: 'hlsBufferCodecs',
// fired when we append a segment to the buffer - data: { segment: segment object }
BUFFER_APPENDING: 'hlsBufferAppending',
// fired when we are done with appending a media segment to the buffer
BUFFER_APPENDED: 'hlsBufferAppended',
// fired when the stream is finished and we want to notify the media buffer that there will be no more data
BUFFER_EOS: 'hlsBufferEos',
// fired when the media buffer should be flushed - data {startOffset, endOffset}
BUFFER_FLUSHING: 'hlsBufferFlushing',
// fired when the media has been flushed
BUFFER_FLUSHED: 'hlsBufferFlushed',
// fired to signal that a manifest loading starts - data: { url : manifestURL}
MANIFEST_LOADING: 'hlsManifestLoading',
// fired after manifest has been loaded - data: { levels : [available quality levels] , url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
MANIFEST_LOADED: 'hlsManifestLoaded',
// fired after manifest has been parsed - data: { levels : [available quality levels] , firstLevel : index of first quality level appearing in Manifest}
MANIFEST_PARSED: 'hlsManifestParsed',
// fired when a level playlist loading starts - data: { url : level URL level : id of level being loaded}
LEVEL_LOADING: 'hlsLevelLoading',
// fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
LEVEL_LOADED: 'hlsLevelLoaded',
// fired when a level's details have been updated based on previous details, after it has been loaded. - data: { details : levelDetails object, level : id of updated level }
LEVEL_UPDATED: 'hlsLevelUpdated',
// fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
// fired when a level switch is requested - data: { level : id of new level }
LEVEL_SWITCH: 'hlsLevelSwitch',
// fired when a fragment loading starts - data: { frag : fragment object}
FRAG_LOADING: 'hlsFragLoading',
// fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded}}
FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
// Identifier for fragment load aborting for emergency switch down - data: {frag : fragment object}
FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
// fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}}
FRAG_LOADED: 'hlsFragLoaded',
// fired when Init Segment has been extracted from fragment - data: { moov : moov MP4 box, codecs : codecs found while parsing fragment}
FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
// fired when parsing sei text is completed - data: { samples : [ sei samples pes ] }
FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
// fired when parsing id3 is completed - data: { samples : [ id3 samples pes ] }
FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
// fired when data have been extracted from fragment - data: { data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
FRAG_PARSING_DATA: 'hlsFragParsingData',
// fired when fragment parsing is completed - data: undefined
FRAG_PARSED: 'hlsFragParsed',
// fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} }
FRAG_BUFFERED: 'hlsFragBuffered',
// fired when fragment matching with current media position is changing - data : { frag : fragment object }
FRAG_CHANGED: 'hlsFragChanged',
// Identifier for a FPS drop event - data: {curentDropped, currentDecoded, totalDroppedFrames}
FPS_DROP: 'hlsFpsDrop',
// Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data}
ERROR: 'hlsError',
// fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example
DESTROYING: 'hlsDestroying',
// fired when a decrypt key loading starts - data: { frag : fragment object}
KEY_LOADING: 'hlsKeyLoading',
// fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length}}
KEY_LOADED: 'hlsKeyLoaded'
};
},{}],24:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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"); } }
/**
* Buffer Helper class, providing methods dealing buffer length retrieval
*/
var BufferHelper = function () {
function BufferHelper() {
_classCallCheck(this, BufferHelper);
}
_createClass(BufferHelper, null, [{
key: "bufferInfo",
value: function bufferInfo(media, pos, maxHoleDuration) {
if (media) {
var vbuffered = media.buffered,
buffered = [],
i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
} else {
return { len: 0, start: 0, end: 0, nextStart: undefined };
}
}
}, {
key: "bufferedInfo",
value: function bufferedInfo(buffered, pos, maxHoleDuration) {
var buffered2 = [],
// bufferStart and bufferEnd are buffer boundaries around current video position
bufferLen,
bufferStart,
bufferEnd,
bufferStartNext,
i;
// sort on buffer.start/smaller end (IE does not always return sorted buffered range)
buffered.sort(function (a, b) {
var diff = a.start - b.start;
if (diff) {
return diff;
} else {
return b.end - a.end;
}
});
// there might be some small holes between buffer time range
// consider that holes smaller than maxHoleDuration are irrelevant and build another
// buffer time range representations that discards those holes
for (i = 0; i < buffered.length; i++) {
var buf2len = buffered2.length;
if (buf2len) {
var buf2end = buffered2[buf2len - 1].end;
// if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
if (buffered[i].start - buf2end < maxHoleDuration) {
// merge overlapping time ranges
// update lastRange.end only if smaller than item.end
// e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
// whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
if (buffered[i].end > buf2end) {
buffered2[buf2len - 1].end = buffered[i].end;
}
} else {
// big hole
buffered2.push(buffered[i]);
}
} else {
// first value
buffered2.push(buffered[i]);
}
}
for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
var start = buffered2[i].start,
end = buffered2[i].end;
//logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
if (pos + maxHoleDuration >= start && pos < end) {
// play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
bufferStart = start;
bufferEnd = end;
bufferLen = bufferEnd - pos;
} else if (pos + maxHoleDuration < start) {
bufferStartNext = start;
break;
}
}
return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
}
}]);
return BufferHelper;
}();
exports.default = BufferHelper;
},{}],25:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* Level Helper class, providing methods dealing with playlist sliding and drift
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var LevelHelper = function () {
function LevelHelper() {
_classCallCheck(this, LevelHelper);
}
_createClass(LevelHelper, null, [{
key: 'mergeDetails',
value: function mergeDetails(oldDetails, newDetails) {
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN,
end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN,
delta = newDetails.startSN - oldDetails.startSN,
oldfragments = oldDetails.fragments,
newfragments = newDetails.fragments,
ccOffset = 0,
PTSFrag;
// check if old/new playlists have fragments in common
if (end < start) {
newDetails.PTSKnown = false;
return;
}
// loop through overlapping SN and update startPTS , cc, and duration if any found
for (var i = start; i <= end; i++) {
var oldFrag = oldfragments[delta + i],
newFrag = newfragments[i];
ccOffset = oldFrag.cc - newFrag.cc;
if (!isNaN(oldFrag.startPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.duration = oldFrag.duration;
PTSFrag = newFrag;
}
}
if (ccOffset) {
_logger.logger.log('discontinuity sliding from playlist, take drift into account');
for (i = 0; i < newfragments.length; i++) {
newfragments[i].cc += ccOffset;
}
}
// if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
LevelHelper.updateFragPTSDTS(newDetails, PTSFrag.sn, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
} else {
// ensure that delta is within oldfragments range
// also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
// in that case we also need to adjust start offset of all fragments
if (delta >= 0 && delta < oldfragments.length) {
// adjust start by sliding offset
var sliding = oldfragments[delta].start;
for (i = 0; i < newfragments.length; i++) {
newfragments[i].start += sliding;
}
}
}
// if we are here, it means we have fragments overlapping between
// old and new level. reliable PTS info is thus relying on old level
newDetails.PTSKnown = oldDetails.PTSKnown;
return;
}
}, {
key: 'updateFragPTSDTS',
value: function updateFragPTSDTS(details, sn, startPTS, endPTS, startDTS, endDTS) {
var fragIdx, fragments, frag, i;
// exit if sn out of range
if (sn < details.startSN || sn > details.endSN) {
return 0;
}
fragIdx = sn - details.startSN;
fragments = details.fragments;
frag = fragments[fragIdx];
if (!isNaN(frag.startPTS)) {
startPTS = Math.min(startPTS, frag.startPTS);
endPTS = Math.max(endPTS, frag.endPTS);
startDTS = Math.min(startDTS, frag.startDTS);
endDTS = Math.max(endDTS, frag.endDTS);
}
var drift = startPTS - frag.start;
frag.start = frag.startPTS = startPTS;
frag.endPTS = endPTS;
frag.startDTS = startDTS;
frag.endDTS = endDTS;
frag.duration = endPTS - startPTS;
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
LevelHelper.updatePTS(fragments, i, i - 1);
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
LevelHelper.updatePTS(fragments, i, i + 1);
}
details.PTSKnown = true;
//logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);
return drift;
}
}, {
key: 'updatePTS',
value: function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx],
fragTo = fragments[toIdx],
fragToPTS = fragTo.startPTS;
// if we know startPTS[toIdx]
if (!isNaN(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
if (toIdx > fromIdx) {
fragFrom.duration = fragToPTS - fragFrom.start;
if (fragFrom.duration < 0) {
_logger.logger.error('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
}
} else {
fragTo.duration = fragFrom.start - fragToPTS;
if (fragTo.duration < 0) {
_logger.logger.error('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
}
}
} else {
// we dont know startPTS[toIdx]
if (toIdx > fromIdx) {
fragTo.start = fragFrom.start + fragFrom.duration;
} else {
fragTo.start = fragFrom.start - fragTo.duration;
}
}
}
}]);
return LevelHelper;
}();
exports.default = LevelHelper;
},{"../utils/logger":38}],26:[function(require,module,exports){
/**
* HLS interface
*/
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
//import FPSController from './controller/fps-controller';
var _events = require('./events');
var _events2 = _interopRequireDefault(_events);
var _errors = require('./errors');
var _playlistLoader = require('./loader/playlist-loader');
var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
var _fragmentLoader = require('./loader/fragment-loader');
var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader);
var _abrController = require('./controller/abr-controller');
var _abrController2 = _interopRequireDefault(_abrController);
var _bufferController = require('./controller/buffer-controller');
var _bufferController2 = _interopRequireDefault(_bufferController);
var _capLevelController = require('./controller/cap-level-controller');
var _capLevelController2 = _interopRequireDefault(_capLevelController);
var _streamController = require('./controller/stream-controller');
var _streamController2 = _interopRequireDefault(_streamController);
var _levelController = require('./controller/level-controller');
var _levelController2 = _interopRequireDefault(_levelController);
var _timelineController = require('./controller/timeline-controller');
var _timelineController2 = _interopRequireDefault(_timelineController);
var _logger = require('./utils/logger');
var _xhrLoader = require('./utils/xhr-loader');
var _xhrLoader2 = _interopRequireDefault(_xhrLoader);
var _events3 = require('events');
var _events4 = _interopRequireDefault(_events3);
var _keyLoader = require('./loader/key-loader');
var _keyLoader2 = _interopRequireDefault(_keyLoader);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Hls = function () {
_createClass(Hls, null, [{
key: 'isSupported',
value: function isSupported() {
return window.MediaSource && typeof window.MediaSource.isTypeSupported === 'function' && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
}
}, {
key: 'Events',
get: function get() {
return _events2.default;
}
}, {
key: 'ErrorTypes',
get: function get() {
return _errors.ErrorTypes;
}
}, {
key: 'ErrorDetails',
get: function get() {
return _errors.ErrorDetails;
}
}, {
key: 'DefaultConfig',
get: function get() {
if (!Hls.defaultConfig) {
Hls.defaultConfig = {
autoStartLoad: true,
debug: false,
capLevelToPlayerSize: false,
maxBufferLength: 30,
maxBufferSize: 60 * 1000 * 1000,
maxBufferHole: 0.5,
maxSeekHole: 2,
seekHoleNudgeDuration: 0.01,
stalledInBufferedNudgeThreshold: 10,
maxFragLookUpTolerance: 0.2,
liveSyncDurationCount: 3,
liveMaxLatencyDurationCount: Infinity,
liveSyncDuration: undefined,
liveMaxLatencyDuration: undefined,
maxMaxBufferLength: 600,
enableWorker: true,
enableSoftwareAES: true,
manifestLoadingTimeOut: 10000,
manifestLoadingMaxRetry: 1,
manifestLoadingRetryDelay: 1000,
levelLoadingTimeOut: 10000,
levelLoadingMaxRetry: 4,
levelLoadingRetryDelay: 1000,
fragLoadingTimeOut: 20000,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 1000,
fragLoadingLoopThreshold: 3,
startFragPrefetch: false,
// fpsDroppedMonitoringPeriod: 5000,
// fpsDroppedMonitoringThreshold: 0.2,
appendErrorMaxRetry: 3,
loader: _xhrLoader2.default,
fLoader: undefined,
pLoader: undefined,
abrController: _abrController2.default,
bufferController: _bufferController2.default,
capLevelController: _capLevelController2.default,
streamController: _streamController2.default,
timelineController: _timelineController2.default,
enableCEA708Captions: true,
enableMP2TPassThrough: false,
abrEwmaFast: 0,
abrEwmaSlow: 0,
abrBandWidthFactor: 0.8,
abrBandWidthUpFactor: 0.7
};
}
return Hls.defaultConfig;
},
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
}]);
function Hls() {
var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, Hls);
var defaultConfig = Hls.DefaultConfig;
if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
}
for (var prop in defaultConfig) {
if (prop in config) {
continue;
}
config[prop] = defaultConfig[prop];
}
if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
}
if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
}
(0, _logger.enableLogs)(config.debug);
this.config = config;
// observer setup
var observer = this.observer = new _events4.default();
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
this.on = observer.on.bind(observer);
this.off = observer.off.bind(observer);
this.trigger = observer.trigger.bind(observer);
this.playlistLoader = new _playlistLoader2.default(this);
this.fragmentLoader = new _fragmentLoader2.default(this);
this.levelController = new _levelController2.default(this);
this.abrController = new config.abrController(this);
this.bufferController = new config.bufferController(this);
this.capLevelController = new config.capLevelController(this);
this.streamController = new config.streamController(this);
this.timelineController = new config.timelineController(this);
this.keyLoader = new _keyLoader2.default(this);
//this.fpsController = new FPSController(this);
}
_createClass(Hls, [{
key: 'destroy',
value: function destroy() {
_logger.logger.log('destroy');
this.trigger(_events2.default.DESTROYING);
this.detachMedia();
this.playlistLoader.destroy();
this.fragmentLoader.destroy();
this.levelController.destroy();
this.abrController.destroy();
this.bufferController.destroy();
this.capLevelController.destroy();
this.streamController.destroy();
this.timelineController.destroy();
this.keyLoader.destroy();
//this.fpsController.destroy();
this.url = null;
this.observer.removeAllListeners();
}
}, {
key: 'attachMedia',
value: function attachMedia(media) {
_logger.logger.log('attachMedia');
this.media = media;
this.trigger(_events2.default.MEDIA_ATTACHING, { media: media });
}
}, {
key: 'detachMedia',
value: function detachMedia() {
_logger.logger.log('detachMedia');
this.trigger(_events2.default.MEDIA_DETACHING);
this.media = null;
}
}, {
key: 'loadSource',
value: function loadSource(url) {
_logger.logger.log('loadSource:' + url);
this.url = url;
// when attaching to a source URL, trigger a playlist load
this.trigger(_events2.default.MANIFEST_LOADING, { url: url });
}
}, {
key: 'startLoad',
value: function startLoad() {
var startPosition = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
_logger.logger.log('startLoad');
this.levelController.startLoad();
this.streamController.startLoad(startPosition);
}
}, {
key: 'stopLoad',
value: function stopLoad() {
_logger.logger.log('stopLoad');
this.levelController.stopLoad();
this.streamController.stopLoad();
}
}, {
key: 'swapAudioCodec',
value: function swapAudioCodec() {
_logger.logger.log('swapAudioCodec');
this.streamController.swapAudioCodec();
}
}, {
key: 'recoverMediaError',
value: function recoverMediaError() {
_logger.logger.log('recoverMediaError');
var media = this.media;
this.detachMedia();
this.attachMedia(media);
}
/** Return all quality levels **/
}, {
key: 'levels',
get: function get() {
return this.levelController.levels;
}
/** Return current playback quality level **/
}, {
key: 'currentLevel',
get: function get() {
return this.streamController.currentLevel;
}
/* set quality level immediately (-1 for automatic level selection) */
,
set: function set(newLevel) {
_logger.logger.log('set currentLevel:' + newLevel);
this.loadLevel = newLevel;
this.streamController.immediateLevelSwitch();
}
/** Return next playback quality level (quality level of next fragment) **/
}, {
key: 'nextLevel',
get: function get() {
return this.streamController.nextLevel;
}
/* set quality level for next fragment (-1 for automatic level selection) */
,
set: function set(newLevel) {
_logger.logger.log('set nextLevel:' + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/** Return the quality level of current/last loaded fragment **/
}, {
key: 'loadLevel',
get: function get() {
return this.levelController.level;
}
/* set quality level for current/next loaded fragment (-1 for automatic level selection) */
,
set: function set(newLevel) {
_logger.logger.log('set loadLevel:' + newLevel);
this.levelController.manualLevel = newLevel;
}
/** Return the quality level of next loaded fragment **/
}, {
key: 'nextLoadLevel',
get: function get() {
return this.levelController.nextLoadLevel;
}
/** set quality level of next loaded fragment **/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/** Return first level (index of first level referenced in manifest)
**/
}, {
key: 'firstLevel',
get: function get() {
return this.levelController.firstLevel;
}
/** set first level (index of first level referenced in manifest)
**/
,
set: function set(newLevel) {
_logger.logger.log('set firstLevel:' + newLevel);
this.levelController.firstLevel = newLevel;
}
/** Return start level (level of first fragment that will be played back)
if not overrided by user, first level appearing in manifest will be used as start level
if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
**/
}, {
key: 'startLevel',
get: function get() {
return this.levelController.startLevel;
}
/** set start level (level of first fragment that will be played back)
if not overrided by user, first level appearing in manifest will be used as start level
if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
**/
,
set: function set(newLevel) {
_logger.logger.log('set startLevel:' + newLevel);
this.levelController.startLevel = newLevel;
}
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
}, {
key: 'autoLevelCapping',
get: function get() {
return this.abrController.autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
,
set: function set(newLevel) {
_logger.logger.log('set autoLevelCapping:' + newLevel);
this.abrController.autoLevelCapping = newLevel;
}
/* check if we are in automatic level selection mode */
}, {
key: 'autoLevelEnabled',
get: function get() {
return this.levelController.manualLevel === -1;
}
/* return manual level */
}, {
key: 'manualLevel',
get: function get() {
return this.levelController.manualLevel;
}
}]);
return Hls;
}();
exports.default = Hls;
},{"./controller/abr-controller":3,"./controller/buffer-controller":4,"./controller/cap-level-controller":5,"./controller/level-controller":7,"./controller/stream-controller":8,"./controller/timeline-controller":9,"./errors":21,"./events":23,"./loader/fragment-loader":28,"./loader/key-loader":29,"./loader/playlist-loader":30,"./utils/logger":38,"./utils/xhr-loader":40,"events":1}],27:[function(require,module,exports){
'use strict';
// This is mostly for support of the es6 module export
// syntax with the babel compiler, it looks like it doesnt support
// function exports like we are used to in node/commonjs
module.exports = require('./hls.js').default;
},{"./hls.js":26}],28:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _errors = require('../errors');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* Fragment Loader
*/
var FragmentLoader = function (_EventHandler) {
_inherits(FragmentLoader, _EventHandler);
function FragmentLoader(hls) {
_classCallCheck(this, FragmentLoader);
return _possibleConstructorReturn(this, Object.getPrototypeOf(FragmentLoader).call(this, hls, _events2.default.FRAG_LOADING));
}
_createClass(FragmentLoader, [{
key: 'destroy',
value: function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onFragLoading',
value: function onFragLoading(data) {
var frag = data.frag;
this.frag = frag;
this.frag.loaded = 0;
var config = this.hls.config;
frag.loader = this.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config);
this.loader.load(frag.url, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, 1, 0, this.loadprogress.bind(this), frag);
}
}, {
key: 'loadsuccess',
value: function loadsuccess(event, stats) {
var payload = event.currentTarget.response;
stats.length = payload.byteLength;
// detach fragment loader on load success
this.frag.loader = undefined;
this.hls.trigger(_events2.default.FRAG_LOADED, { payload: payload, frag: this.frag, stats: stats });
}
}, {
key: 'loaderror',
value: function loaderror(event) {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: this.frag, response: event });
}
}, {
key: 'loadtimeout',
value: function loadtimeout() {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: this.frag });
}
}, {
key: 'loadprogress',
value: function loadprogress(event, stats) {
this.frag.loaded = stats.loaded;
this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: this.frag, stats: stats });
}
}]);
return FragmentLoader;
}(_eventHandler2.default);
exports.default = FragmentLoader;
},{"../errors":21,"../event-handler":22,"../events":23}],29:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _errors = require('../errors');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /*
* Decrypt key Loader
*/
var KeyLoader = function (_EventHandler) {
_inherits(KeyLoader, _EventHandler);
function KeyLoader(hls) {
_classCallCheck(this, KeyLoader);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(KeyLoader).call(this, hls, _events2.default.KEY_LOADING));
_this.decryptkey = null;
_this.decrypturl = null;
return _this;
}
_createClass(KeyLoader, [{
key: 'destroy',
value: function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onKeyLoading',
value: function onKeyLoading(data) {
var frag = this.frag = data.frag,
decryptdata = frag.decryptdata,
uri = decryptdata.uri;
// if uri is different from previous one or if decrypt key not retrieved yet
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
frag.loader = this.loader = new config.loader(config);
this.decrypturl = uri;
this.decryptkey = null;
frag.loader.load(uri, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, config.fragLoadingMaxRetry, config.fragLoadingRetryDelay, this.loadprogress.bind(this), frag);
} else if (this.decryptkey) {
// we already loaded this key, return it
decryptdata.key = this.decryptkey;
this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
}
}
}, {
key: 'loadsuccess',
value: function loadsuccess(event) {
var frag = this.frag;
this.decryptkey = frag.decryptdata.key = new Uint8Array(event.currentTarget.response);
// detach fragment loader on load success
frag.loader = undefined;
this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
}
}, {
key: 'loaderror',
value: function loaderror(event) {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: this.frag, response: event });
}
}, {
key: 'loadtimeout',
value: function loadtimeout() {
if (this.loader) {
this.loader.abort();
}
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: this.frag });
}
}, {
key: 'loadprogress',
value: function loadprogress() {}
}]);
return KeyLoader;
}(_eventHandler2.default);
exports.default = KeyLoader;
},{"../errors":21,"../event-handler":22,"../events":23}],30:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _eventHandler = require('../event-handler');
var _eventHandler2 = _interopRequireDefault(_eventHandler);
var _errors = require('../errors');
var _url = require('../utils/url');
var _url2 = _interopRequireDefault(_url);
var _attrList = require('../utils/attr-list');
var _attrList2 = _interopRequireDefault(_attrList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; } /**
* Playlist Loader
*/
//import {logger} from '../utils/logger';
var PlaylistLoader = function (_EventHandler) {
_inherits(PlaylistLoader, _EventHandler);
function PlaylistLoader(hls) {
_classCallCheck(this, PlaylistLoader);
return _possibleConstructorReturn(this, Object.getPrototypeOf(PlaylistLoader).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.LEVEL_LOADING));
}
_createClass(PlaylistLoader, [{
key: 'destroy',
value: function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
this.url = this.id = null;
_eventHandler2.default.prototype.destroy.call(this);
}
}, {
key: 'onManifestLoading',
value: function onManifestLoading(data) {
this.load(data.url, null);
}
}, {
key: 'onLevelLoading',
value: function onLevelLoading(data) {
this.load(data.url, data.level, data.id);
}
}, {
key: 'load',
value: function load(url, id1, id2) {
var config = this.hls.config,
retry,
timeout,
retryDelay;
if (this.loading && this.loader) {
if (this.url === url && this.id === id1 && this.id2 === id2) {
// same request than last pending one, don't do anything
return;
} else {
// one playlist load request is pending, but with different params, abort it before loading new playlist
this.loader.abort();
}
}
this.url = url;
this.id = id1;
this.id2 = id2;
if (this.id === null) {
retry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
} else {
retry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
}
this.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config);
this.loading = true;
this.loader.load(url, '', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), timeout, retry, retryDelay);
}
}, {
key: 'resolve',
value: function resolve(url, baseUrl) {
return _url2.default.buildAbsoluteURL(baseUrl, url);
}
}, {
key: 'parseMasterPlaylist',
value: function parseMasterPlaylist(string, baseurl) {
var levels = [],
result = void 0;
// https://regex101.com is your friend
var re = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
while ((result = re.exec(string)) != null) {
var level = {};
var attrs = level.attrs = new _attrList2.default(result[1]);
level.url = this.resolve(result[2], baseurl);
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
level.name = attrs.NAME;
var codecs = attrs.CODECS;
if (codecs) {
codecs = codecs.split(',');
for (var i = 0; i < codecs.length; i++) {
var codec = codecs[i];
if (codec.indexOf('avc1') !== -1) {
level.videoCodec = this.avc1toavcoti(codec);
} else {
level.audioCodec = codec;
}
}
}
levels.push(level);
}
return levels;
}
}, {
key: 'avc1toavcoti',
value: function avc1toavcoti(codec) {
var result,
avcdata = codec.split('.');
if (avcdata.length > 2) {
result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
} else {
result = codec;
}
return result;
}
}, {
key: 'cloneObj',
value: function cloneObj(obj) {
return JSON.parse(JSON.stringify(obj));
}
}, {
key: 'parseLevelPlaylist',
value: function parseLevelPlaylist(string, baseurl, id) {
var currentSN = 0,
totalduration = 0,
level = { url: baseurl, fragments: [], live: true, startSN: 0 },
levelkey = { method: null, key: null, iv: null, uri: null },
cc = 0,
programDateTime = null,
frag = null,
result,
regexp,
byteRangeEndOffset,
byteRangeStartOffset;
regexp = /(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*))|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*)[\r\n]+([^#|\r\n]+)?)/g;
while ((result = regexp.exec(string)) !== null) {
result.shift();
result = result.filter(function (n) {
return n !== undefined;
});
switch (result[0]) {
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(result[1]);
break;
case 'TARGETDURATION':
level.targetduration = parseFloat(result[1]);
break;
case 'ENDLIST':
level.live = false;
break;
case 'DIS':
cc++;
break;
case 'BYTERANGE':
var params = result[1].split('@');
if (params.length === 1) {
byteRangeStartOffset = byteRangeEndOffset;
} else {
byteRangeStartOffset = parseInt(params[1]);
}
byteRangeEndOffset = parseInt(params[0]) + byteRangeStartOffset;
if (frag && !frag.url) {
frag.byteRangeStartOffset = byteRangeStartOffset;
frag.byteRangeEndOffset = byteRangeEndOffset;
frag.url = this.resolve(result[2], baseurl);
}
break;
case 'INF':
var duration = parseFloat(result[1]);
if (!isNaN(duration)) {
var fragdecryptdata,
sn = currentSN++;
if (levelkey.method && levelkey.uri && !levelkey.iv) {
fragdecryptdata = this.cloneObj(levelkey);
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = sn >> 8 * (15 - i) & 0xff;
}
fragdecryptdata.iv = uint8View;
} else {
fragdecryptdata = levelkey;
}
var url = result[2] ? this.resolve(result[2], baseurl) : null;
frag = { url: url, duration: duration, start: totalduration, sn: sn, level: id, cc: cc, byteRangeStartOffset: byteRangeStartOffset, byteRangeEndOffset: byteRangeEndOffset, decryptdata: fragdecryptdata, programDateTime: programDateTime };
level.fragments.push(frag);
totalduration += duration;
byteRangeStartOffset = null;
programDateTime = null;
}
break;
case 'KEY':
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
var decryptparams = result[1];
var keyAttrs = new _attrList2.default(decryptparams);
var decryptmethod = keyAttrs.enumeratedString('METHOD'),
decrypturi = keyAttrs.URI,
decryptiv = keyAttrs.hexadecimalInteger('IV');
if (decryptmethod) {
levelkey = { method: null, key: null, iv: null, uri: null };
if (decrypturi && decryptmethod === 'AES-128') {
levelkey.method = decryptmethod;
// URI to get the key
levelkey.uri = this.resolve(decrypturi, baseurl);
levelkey.key = null;
// Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
case 'PROGRAM-DATE-TIME':
programDateTime = new Date(Date.parse(result[1]));
if (frag && !frag.url && result.length >= 3) {
frag.url = this.resolve(result[2], baseurl);
frag.programDateTime = programDateTime;
}
break;
default:
break;
}
}
//logger.log('found ' + level.fragments.length + ' fragments');
if (frag && !frag.url) {
level.fragments.pop();
totalduration -= frag.duration;
}
level.totalduration = totalduration;
level.endSN = currentSN - 1;
return level;
}
}, {
key: 'loadsuccess',
value: function loadsuccess(event, stats) {
var target = event.currentTarget,
string = target.responseText,
url = target.responseURL,
id = this.id,
id2 = this.id2,
hls = this.hls,
levels;
this.loading = false;
// responseURL not supported on some browsers (it is used to detect URL redirection)
if (url === undefined) {
// fallback to initial URL
url = this.url;
}
stats.tload = performance.now();
stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
if (string.indexOf('#EXTM3U') === 0) {
if (string.indexOf('#EXTINF:') > 0) {
// 1 level playlist
// if first request, fire manifest loaded event, level will be reloaded afterwards
// (this is to have a uniform logic for 1 level/multilevel playlists)
if (this.id === null) {
hls.trigger(_events2.default.MANIFEST_LOADED, { levels: [{ url: url }], url: url, stats: stats });
} else {
var levelDetails = this.parseLevelPlaylist(string, url, id);
stats.tparsed = performance.now();
hls.trigger(_events2.default.LEVEL_LOADED, { details: levelDetails, level: id, id: id2, stats: stats });
}
} else {
levels = this.parseMasterPlaylist(string, url);
// multi level playlist, parse level info
if (levels.length) {
hls.trigger(_events2.default.MANIFEST_LOADED, { levels: levels, url: url, stats: stats });
} else {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest' });
}
}
} else {
hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter' });
}
}
}, {
key: 'loaderror',
value: function loaderror(event) {
var details, fatal;
if (this.id === null) {
details = _errors.ErrorDetails.MANIFEST_LOAD_ERROR;
fatal = true;
} else {
details = _errors.ErrorDetails.LEVEL_LOAD_ERROR;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, response: event.currentTarget, level: this.id, id: this.id2 });
}
}, {
key: 'loadtimeout',
value: function loadtimeout() {
var details, fatal;
if (this.id === null) {
details = _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT;
fatal = true;
} else {
details = _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT;
fatal = false;
}
if (this.loader) {
this.loader.abort();
}
this.loading = false;
this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, level: this.id, id: this.id2 });
}
}]);
return PlaylistLoader;
}(_eventHandler2.default);
exports.default = PlaylistLoader;
},{"../errors":21,"../event-handler":22,"../events":23,"../utils/attr-list":34,"../utils/url":39}],31:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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"); } }
/**
* Generate MP4 Box
*/
//import Hex from '../utils/hex';
var MP4 = function () {
function MP4() {
_classCallCheck(this, MP4);
}
_createClass(MP4, null, [{
key: 'init',
value: function init() {
MP4.types = {
avc1: [], // codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
mvex: [],
mvhd: [],
sdtp: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: [],
smhd: []
};
var i;
for (i in MP4.types) {
if (MP4.types.hasOwnProperty(i)) {
MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
}
}
var videoHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
]);
var audioHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
]);
MP4.HDLR_TYPES = {
'video': videoHdlr,
'audio': audioHdlr
};
var dref = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
var stco = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
MP4.STTS = MP4.STSC = MP4.STCO = stco;
MP4.STSZ = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00]);
// sample_count
MP4.VMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
]);
MP4.SMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance
0x00, 0x00 // reserved
]);
MP4.STSD = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01]); // entry_count
var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
var minorVersion = new Uint8Array([0, 0, 0, 1]);
MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
}
}, {
key: 'box',
value: function box(type) {
var payload = Array.prototype.slice.call(arguments, 1),
size = 8,
i = payload.length,
len = i,
result;
// calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
result = new Uint8Array(size);
result[0] = size >> 24 & 0xff;
result[1] = size >> 16 & 0xff;
result[2] = size >> 8 & 0xff;
result[3] = size & 0xff;
result.set(type, 4);
// copy the payload into the result
for (i = 0, size = 8; i < len; i++) {
// copy payload[i] array @ offset size
result.set(payload[i], size);
size += payload[i].byteLength;
}
return result;
}
}, {
key: 'hdlr',
value: function hdlr(type) {
return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
}
}, {
key: 'mdat',
value: function mdat(data) {
return MP4.box(MP4.types.mdat, data);
}
}, {
key: 'mdhd',
value: function mdhd(timescale, duration) {
duration *= timescale;
return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]));
}
}, {
key: 'mdia',
value: function mdia(track) {
return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
}
}, {
key: 'mfhd',
value: function mfhd(sequenceNumber) {
return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF]));
}
}, {
key: 'minf',
// sequence_number
value: function minf(track) {
if (track.type === 'audio') {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
} else {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
}
}
}, {
key: 'moof',
value: function moof(sn, baseMediaDecodeTime, track) {
return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
}
/**
* @param tracks... (optional) {array} the tracks associated with this movie
*/
}, {
key: 'moov',
value: function moov(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = MP4.trak(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
}
}, {
key: 'mvex',
value: function mvex(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = MP4.trex(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
}
}, {
key: 'mvhd',
value: function mvhd(timescale, duration) {
duration *= timescale;
var bytes = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // creation_time
0x00, 0x00, 0x00, 0x02, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
duration >> 24 & 0xFF, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_ID
]);
return MP4.box(MP4.types.mvhd, bytes);
}
}, {
key: 'sdtp',
value: function sdtp(track) {
var samples = track.samples || [],
bytes = new Uint8Array(4 + samples.length),
flags,
i;
// leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
}
return MP4.box(MP4.types.sdtp, bytes);
}
}, {
key: 'stbl',
value: function stbl(track) {
return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
}
}, {
key: 'avc1',
value: function avc1(track) {
var sps = [],
pps = [],
i,
data,
len;
// assemble the SPSs
for (i = 0; i < track.sps.length; i++) {
data = track.sps[i];
len = data.byteLength;
sps.push(len >>> 8 & 0xFF);
sps.push(len & 0xFF);
sps = sps.concat(Array.prototype.slice.call(data)); // SPS
}
// assemble the PPSs
for (i = 0; i < track.pps.length; i++) {
data = track.pps[i];
len = data.byteLength;
pps.push(len >>> 8 & 0xFF);
pps.push(len & 0xFF);
pps = pps.concat(Array.prototype.slice.call(data));
}
var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
sps[3], // profile
sps[4], // profile compat
sps[5], // level
0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
].concat(sps).concat([track.pps.length // numOfPictureParameterSets
]).concat(pps))),
// "PPS"
width = track.width,
height = track.height;
//console.log('avcc:' + Hex.hexDump(avcc));
return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
width >> 8 & 0xFF, width & 0xff, // width
height >> 8 & 0xFF, height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js
0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11]), // pre_defined = -1
avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
0x00, 0x2d, 0xc6, 0xc0])) // avgBitrate
);
}
}, {
key: 'esds',
value: function esds(track) {
var configlen = track.config.length;
return new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x03, // descriptor_type
0x17 + configlen, // length
0x00, 0x01, //es_id
0x00, // stream_priority
0x04, // descriptor_type
0x0f + configlen, // length
0x40, //codec : mpeg4_audio
0x15, // stream_type
0x00, 0x00, 0x00, // buffer_size
0x00, 0x00, 0x00, 0x00, // maxBitrate
0x00, 0x00, 0x00, 0x00, // avgBitrate
0x05 // descriptor_type
].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
}
}, {
key: 'mp4a',
value: function mp4a(track) {
var audiosamplerate = track.audiosamplerate;
return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
audiosamplerate >> 8 & 0xFF, audiosamplerate & 0xff, //
0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
}
}, {
key: 'stsd',
value: function stsd(track) {
if (track.type === 'audio') {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
} else {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
}
}
}, {
key: 'tkhd',
value: function tkhd(track) {
var id = track.id,
duration = track.duration * track.timescale,
width = track.width,
height = track.height;
return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, // creation_time
0x00, 0x00, 0x00, 0x00, // modification_time
id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x00, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
]));
}
}, {
key: 'traf',
value: function traf(track, baseMediaDecodeTime) {
var sampleDependencyTable = MP4.sdtp(track),
id = track.id;
return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF])), // track_ID
MP4.box(MP4.types.tfdt, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
baseMediaDecodeTime >> 24, baseMediaDecodeTime >> 16 & 0XFF, baseMediaDecodeTime >> 8 & 0XFF, baseMediaDecodeTime & 0xFF])), // baseMediaDecodeTime
MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
16 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8), // mdat header
sampleDependencyTable);
}
/**
* Generate a track box.
* @param track {object} a track definition
* @return {Uint8Array} the track box
*/
}, {
key: 'trak',
value: function trak(track) {
track.duration = track.duration || 0xffffffff;
return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
}
}, {
key: 'trex',
value: function trex(track) {
var id = track.id;
return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]));
}
}, {
key: 'trun',
value: function trun(track, offset) {
var samples = track.samples || [],
len = samples.length,
arraylen = 12 + 16 * len,
array = new Uint8Array(arraylen),
i,
sample,
duration,
size,
flags,
cts;
offset += 8 + arraylen;
array.set([0x00, // version 0
0x00, 0x0f, 0x01, // flags
len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
], 0);
for (i = 0; i < len; i++) {
sample = samples[i];
duration = sample.duration;
size = sample.size;
flags = sample.flags;
cts = sample.cts;
array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags
cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
], 12 + 16 * i);
}
return MP4.box(MP4.types.trun, array);
}
}, {
key: 'initSegment',
value: function initSegment(tracks) {
if (!MP4.types) {
MP4.init();
}
var movie = MP4.moov(tracks),
result;
result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
}
}]);
return MP4;
}();
exports.default = MP4;
},{}],32:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* fMP4 remuxer
*/
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
var _logger = require('../utils/logger');
var _mp4Generator = require('../remux/mp4-generator');
var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
var _errors = require('../errors');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var MP4Remuxer = function () {
function MP4Remuxer(observer) {
_classCallCheck(this, MP4Remuxer);
this.observer = observer;
this.ISGenerated = false;
this.PES2MP4SCALEFACTOR = 4;
this.PES_TIMESCALE = 90000;
this.MP4_TIMESCALE = this.PES_TIMESCALE / this.PES2MP4SCALEFACTOR;
}
_createClass(MP4Remuxer, [{
key: 'destroy',
value: function destroy() {}
}, {
key: 'insertDiscontinuity',
value: function insertDiscontinuity() {
this._initPTS = this._initDTS = undefined;
}
}, {
key: 'switchLevel',
value: function switchLevel() {
this.ISGenerated = false;
}
}, {
key: 'remux',
value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous) {
// generate Init Segment if needed
if (!this.ISGenerated) {
this.generateIS(audioTrack, videoTrack, timeOffset);
}
if (this.ISGenerated) {
//logger.log('nb AVC samples:' + videoTrack.samples.length);
if (videoTrack.samples.length) {
this.remuxVideo(videoTrack, timeOffset, contiguous);
}
//logger.log('nb AAC samples:' + audioTrack.samples.length);
if (audioTrack.samples.length) {
this.remuxAudio(audioTrack, timeOffset, contiguous);
}
}
//logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (id3Track.samples.length) {
this.remuxID3(id3Track, timeOffset);
}
//logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (textTrack.samples.length) {
this.remuxText(textTrack, timeOffset);
}
//notify end of parsing
this.observer.trigger(_events2.default.FRAG_PARSED);
}
}, {
key: 'generateIS',
value: function generateIS(audioTrack, videoTrack, timeOffset) {
var observer = this.observer,
audioSamples = audioTrack.samples,
videoSamples = videoTrack.samples,
pesTimeScale = this.PES_TIMESCALE,
tracks = {},
data = { tracks: tracks, unique: false },
computePTSDTS = this._initPTS === undefined,
initPTS,
initDTS;
if (computePTSDTS) {
initPTS = initDTS = Infinity;
}
if (audioTrack.config && audioSamples.length) {
audioTrack.timescale = audioTrack.audiosamplerate;
// MP4 duration (track duration in seconds multiplied by timescale) is coded on 32 bits
// we know that each AAC sample contains 1024 frames....
// in order to avoid overflowing the 32 bit counter for large duration, we use smaller timescale (timescale/gcd)
// we just need to ensure that AAC sample duration will still be an integer (will be 1024/gcd)
if (audioTrack.timescale * audioTrack.duration > Math.pow(2, 32)) {
(function () {
var greatestCommonDivisor = function greatestCommonDivisor(a, b) {
if (!b) {
return a;
}
return greatestCommonDivisor(b, a % b);
};
audioTrack.timescale = audioTrack.audiosamplerate / greatestCommonDivisor(audioTrack.audiosamplerate, 1024);
})();
}
_logger.logger.log('audio mp4 timescale :' + audioTrack.timescale);
tracks.audio = {
container: 'audio/mp4',
codec: audioTrack.codec,
initSegment: _mp4Generator2.default.initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
// remember first PTS of this demuxing context. for audio, PTS + DTS ...
initPTS = initDTS = audioSamples[0].pts - pesTimeScale * timeOffset;
}
}
if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
videoTrack.timescale = this.MP4_TIMESCALE;
tracks.video = {
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: _mp4Generator2.default.initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
initPTS = Math.min(initPTS, videoSamples[0].pts - pesTimeScale * timeOffset);
initDTS = Math.min(initDTS, videoSamples[0].dts - pesTimeScale * timeOffset);
}
}
if (Object.keys(tracks).length) {
observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
} else {
observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
}
}
}, {
key: 'remuxVideo',
value: function remuxVideo(track, timeOffset, contiguous) {
var view,
offset = 8,
pesTimeScale = this.PES_TIMESCALE,
pes2mp4ScaleFactor = this.PES2MP4SCALEFACTOR,
avcSample,
mp4Sample,
mp4SampleLength,
unit,
mdat,
moof,
firstPTS,
firstDTS,
lastDTS,
pts,
dts,
ptsnorm,
dtsnorm,
flags,
samples = [];
/* concatenate the video data and construct the mdat in place
(need 8 more bytes to fill length and mpdat type) */
mdat = new Uint8Array(track.len + 4 * track.nbNalu + 8);
view = new DataView(mdat.buffer);
view.setUint32(0, mdat.byteLength);
mdat.set(_mp4Generator2.default.types.mdat, 4);
while (track.samples.length) {
avcSample = track.samples.shift();
mp4SampleLength = 0;
// convert NALU bitstream to MP4 format (prepend NALU with size field)
while (avcSample.units.units.length) {
unit = avcSample.units.units.shift();
view.setUint32(offset, unit.data.byteLength);
offset += 4;
mdat.set(unit.data, offset);
offset += unit.data.byteLength;
mp4SampleLength += 4 + unit.data.byteLength;
}
pts = avcSample.pts - this._initDTS;
dts = avcSample.dts - this._initDTS;
// ensure DTS is not bigger than PTS
dts = Math.min(pts, dts);
//logger.log(`Video/PTS/DTS:${Math.round(pts/90)}/${Math.round(dts/90)}`);
// if not first AVC sample of video track, normalize PTS/DTS with previous sample value
// and ensure that sample duration is positive
if (lastDTS !== undefined) {
ptsnorm = this._PTSNormalize(pts, lastDTS);
dtsnorm = this._PTSNormalize(dts, lastDTS);
var sampleDuration = (dtsnorm - lastDTS) / pes2mp4ScaleFactor;
if (sampleDuration <= 0) {
_logger.logger.log('invalid sample duration at PTS/DTS: ' + avcSample.pts + '/' + avcSample.dts + ':' + sampleDuration);
sampleDuration = 1;
}
mp4Sample.duration = sampleDuration;
} else {
var nextAvcDts = void 0,
delta = void 0;
if (contiguous) {
nextAvcDts = this.nextAvcDts;
} else {
nextAvcDts = timeOffset * pesTimeScale;
}
// first AVC sample of video track, normalize PTS/DTS
ptsnorm = this._PTSNormalize(pts, nextAvcDts);
dtsnorm = this._PTSNormalize(dts, nextAvcDts);
delta = Math.round((dtsnorm - nextAvcDts) / 90);
// if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
if (delta) {
if (delta > 1) {
_logger.logger.log('AVC:' + delta + ' ms hole between fragments detected,filling it');
} else if (delta < -1) {
_logger.logger.log('AVC:' + -delta + ' ms overlapping between fragments detected');
}
// set DTS to next DTS
dtsnorm = nextAvcDts;
// offset PTS as well, ensure that PTS is smaller or equal than new DTS
ptsnorm = Math.max(ptsnorm - delta, dtsnorm);
_logger.logger.log('Video/PTS/DTS adjusted: ' + ptsnorm + '/' + dtsnorm + ',delta:' + delta);
}
}
// remember first PTS of our avcSamples, ensure value is positive
firstPTS = Math.max(0, ptsnorm);
firstDTS = Math.max(0, dtsnorm);
}
//console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
mp4Sample = {
size: mp4SampleLength,
duration: 0,
cts: (ptsnorm - dtsnorm) / pes2mp4ScaleFactor,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0
}
};
flags = mp4Sample.flags;
if (avcSample.key === true) {
// the current sample is a key frame
flags.dependsOn = 2;
flags.isNonSync = 0;
} else {
flags.dependsOn = 1;
flags.isNonSync = 1;
}
samples.push(mp4Sample);
lastDTS = dtsnorm;
}
var lastSampleDuration = 0;
if (samples.length >= 2) {
lastSampleDuration = samples[samples.length - 2].duration;
mp4Sample.duration = lastSampleDuration;
}
// next AVC sample DTS should be equal to last sample DTS + last sample duration
this.nextAvcDts = dtsnorm + lastSampleDuration * pes2mp4ScaleFactor;
track.len = 0;
track.nbNalu = 0;
if (samples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
flags = samples[0].flags;
// chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
flags.dependsOn = 2;
flags.isNonSync = 0;
}
track.samples = samples;
moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);
track.samples = [];
this.observer.trigger(_events2.default.FRAG_PARSING_DATA, {
data1: moof,
data2: mdat,
startPTS: firstPTS / pesTimeScale,
endPTS: (ptsnorm + pes2mp4ScaleFactor * lastSampleDuration) / pesTimeScale,
startDTS: firstDTS / pesTimeScale,
endDTS: this.nextAvcDts / pesTimeScale,
type: 'video',
nb: samples.length
});
}
}, {
key: 'remuxAudio',
value: function remuxAudio(track, timeOffset, contiguous) {
var view,
offset = 8,
pesTimeScale = this.PES_TIMESCALE,
mp4timeScale = track.timescale,
pes2mp4ScaleFactor = pesTimeScale / mp4timeScale,
expectedSampleDuration = track.timescale * 1024 / track.audiosamplerate,
aacSample,
mp4Sample,
unit,
mdat,
moof,
firstPTS,
firstDTS,
lastDTS,
pts,
dts,
ptsnorm,
dtsnorm,
samples = [],
samples0 = [];
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
samples0 = track.samples;
while (samples0.length) {
aacSample = samples0.shift();
unit = aacSample.unit;
pts = aacSample.pts - this._initDTS;
dts = aacSample.dts - this._initDTS;
//logger.log(`Audio/PTS:${Math.round(pts/90)}`);
// if not first sample
if (lastDTS !== undefined) {
ptsnorm = this._PTSNormalize(pts, lastDTS);
dtsnorm = this._PTSNormalize(dts, lastDTS);
// let's compute sample duration.
// sample Duration should be close to expectedSampleDuration
mp4Sample.duration = (dtsnorm - lastDTS) / pes2mp4ScaleFactor;
if (Math.abs(mp4Sample.duration - expectedSampleDuration) > expectedSampleDuration / 10) {
// more than 10% diff between sample duration and expectedSampleDuration .... lets log that
_logger.logger.log('invalid AAC sample duration at PTS ' + Math.round(pts / 90) + ',should be 1024,found :' + Math.round(mp4Sample.duration * track.audiosamplerate / track.timescale));
}
// always adjust sample duration to avoid av sync issue
mp4Sample.duration = expectedSampleDuration;
ptsnorm = dtsnorm = expectedSampleDuration * pes2mp4ScaleFactor + lastDTS;
} else {
var nextAacPts = void 0,
delta = void 0;
if (contiguous) {
nextAacPts = this.nextAacPts;
} else {
nextAacPts = timeOffset * pesTimeScale;
}
ptsnorm = this._PTSNormalize(pts, nextAacPts);
dtsnorm = this._PTSNormalize(dts, nextAacPts);
delta = Math.round(1000 * (ptsnorm - nextAacPts) / pesTimeScale);
// if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
// log delta
if (delta) {
if (delta > 0) {
_logger.logger.log(delta + ' ms hole between AAC samples detected,filling it');
// if we have frame overlap, overlapping for more than half a frame duration
} else if (delta < -12) {
// drop overlapping audio frames... browser will deal with it
_logger.logger.log(-delta + ' ms overlapping between AAC samples detected, drop frame');
track.len -= unit.byteLength;
continue;
}
// set PTS/DTS to next PTS/DTS
ptsnorm = dtsnorm = nextAacPts;
}
}
// remember first PTS of our aacSamples, ensure value is positive
firstPTS = Math.max(0, ptsnorm);
firstDTS = Math.max(0, dtsnorm);
if (track.len > 0) {
/* concatenate the audio data and construct the mdat in place
(need 8 more bytes to fill length and mdat type) */
mdat = new Uint8Array(track.len + 8);
view = new DataView(mdat.buffer);
view.setUint32(0, mdat.byteLength);
mdat.set(_mp4Generator2.default.types.mdat, 4);
} else {
// no audio samples
return;
}
}
mdat.set(unit, offset);
offset += unit.byteLength;
//console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${aacSample.pts}/${aacSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(aacSample.pts/4294967296).toFixed(3)}');
mp4Sample = {
size: unit.byteLength,
cts: 0,
duration: 0,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: 1
}
};
samples.push(mp4Sample);
lastDTS = dtsnorm;
}
var lastSampleDuration = 0;
var nbSamples = samples.length;
//set last sample duration as being identical to previous sample
if (nbSamples >= 2) {
lastSampleDuration = samples[nbSamples - 2].duration;
mp4Sample.duration = lastSampleDuration;
}
if (nbSamples) {
// next aac sample PTS should be equal to last sample PTS + duration
this.nextAacPts = ptsnorm + pes2mp4ScaleFactor * lastSampleDuration;
//logger.log('Audio/PTS/PTSend:' + aacSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
track.len = 0;
track.samples = samples;
moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);
track.samples = [];
this.observer.trigger(_events2.default.FRAG_PARSING_DATA, {
data1: moof,
data2: mdat,
startPTS: firstPTS / pesTimeScale,
endPTS: this.nextAacPts / pesTimeScale,
startDTS: firstDTS / pesTimeScale,
endDTS: (dtsnorm + pes2mp4ScaleFactor * lastSampleDuration) / pesTimeScale,
type: 'audio',
nb: nbSamples
});
}
}
}, {
key: 'remuxID3',
value: function remuxID3(track, timeOffset) {
var length = track.samples.length,
sample;
// consume samples
if (length) {
for (var index = 0; index < length; index++) {
sample = track.samples[index];
// setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE;
sample.dts = (sample.dts - this._initDTS) / this.PES_TIMESCALE;
}
this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, {
samples: track.samples
});
}
track.samples = [];
timeOffset = timeOffset;
}
}, {
key: 'remuxText',
value: function remuxText(track, timeOffset) {
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
var length = track.samples.length,
sample;
// consume samples
if (length) {
for (var index = 0; index < length; index++) {
sample = track.samples[index];
// setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE;
}
this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, {
samples: track.samples
});
}
track.samples = [];
timeOffset = timeOffset;
}
}, {
key: '_PTSNormalize',
value: function _PTSNormalize(value, reference) {
var offset;
if (reference === undefined) {
return value;
}
if (reference < value) {
// - 2^33
offset = -8589934592;
} else {
// + 2^33
offset = 8589934592;
}
/* PTS is 33bit (from 0 to 2^33 -1)
if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
PTS looping occured. fill the gap */
while (Math.abs(value - reference) > 4294967296) {
value += offset;
}
return value;
}
}, {
key: 'passthrough',
get: function get() {
return false;
}
}]);
return MP4Remuxer;
}();
exports.default = MP4Remuxer;
},{"../errors":21,"../events":23,"../remux/mp4-generator":31,"../utils/logger":38}],33:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* passthrough remuxer
*/
var _events = require('../events');
var _events2 = _interopRequireDefault(_events);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var PassThroughRemuxer = function () {
function PassThroughRemuxer(observer) {
_classCallCheck(this, PassThroughRemuxer);
this.observer = observer;
this.ISGenerated = false;
}
_createClass(PassThroughRemuxer, [{
key: 'destroy',
value: function destroy() {}
}, {
key: 'insertDiscontinuity',
value: function insertDiscontinuity() {}
}, {
key: 'switchLevel',
value: function switchLevel() {
this.ISGenerated = false;
}
}, {
key: 'remux',
value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, rawData) {
var observer = this.observer;
// generate Init Segment if needed
if (!this.ISGenerated) {
var tracks = {},
data = { tracks: tracks, unique: true },
track = videoTrack,
codec = track.codec;
if (codec) {
data.tracks.video = {
container: track.container,
codec: codec,
metadata: {
width: track.width,
height: track.height
}
};
}
track = audioTrack;
codec = track.codec;
if (codec) {
data.tracks.audio = {
container: track.container,
codec: codec,
metadata: {
channelCount: track.channelCount
}
};
}
this.ISGenerated = true;
observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
}
observer.trigger(_events2.default.FRAG_PARSING_DATA, {
data1: rawData,
startPTS: timeOffset,
startDTS: timeOffset,
type: 'audiovideo',
nb: 1
});
}
}, {
key: 'passthrough',
get: function get() {
return true;
}
}]);
return PassThroughRemuxer;
}();
exports.default = PassThroughRemuxer;
},{"../events":23}],34:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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"); } }
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = function () {
function AttrList(attrs) {
_classCallCheck(this, AttrList);
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
_createClass(AttrList, [{
key: 'decimalInteger',
value: function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
}
}, {
key: 'hexadecimalInteger',
value: function hexadecimalInteger(attrName) {
if (this[attrName]) {
var stringValue = (this[attrName] || '0x').slice(2);
stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
var value = new Uint8Array(stringValue.length / 2);
for (var i = 0; i < stringValue.length / 2; i++) {
value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
}
return value;
} else {
return null;
}
}
}, {
key: 'hexadecimalIntegerAsNumber',
value: function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
}
}, {
key: 'decimalFloatingPoint',
value: function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
}
}, {
key: 'enumeratedString',
value: function enumeratedString(attrName) {
return this[attrName];
}
}, {
key: 'decimalResolution',
value: function decimalResolution(attrName) {
var res = /^(\d+)x(\d+)$/.exec(this[attrName]);
if (res === null) {
return undefined;
}
return {
width: parseInt(res[1], 10),
height: parseInt(res[2], 10)
};
}
}], [{
key: 'parseAttrList',
value: function parseAttrList(input) {
var re = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;
var match,
attrs = {};
while ((match = re.exec(input)) !== null) {
var value = match[2],
quote = '"';
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
}
}]);
return AttrList;
}();
exports.default = AttrList;
},{}],35:[function(require,module,exports){
"use strict";
var BinarySearch = {
/**
* Searches for an item in an array which matches a certain condition.
* This requires the condition to only match one item in the array,
* and for the array to be ordered.
*
* @param {Array} list The array to search.
* @param {Function} comparisonFunction
* Called and provided a candidate item as the first argument.
* Should return:
* > -1 if the item should be located at a lower index than the provided item.
* > 1 if the item should be located at a higher index than the provided item.
* > 0 if the item is the item you're looking for.
*
* @return {*} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFunction) {
var minIndex = 0;
var maxIndex = list.length - 1;
var currentIndex = null;
var currentElement = null;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = list[currentIndex];
var comparisonResult = comparisonFunction(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
module.exports = BinarySearch;
},{}],36:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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"); } }
/*
* CEA-708 interpreter
*/
var CEA708Interpreter = function () {
function CEA708Interpreter() {
_classCallCheck(this, CEA708Interpreter);
}
_createClass(CEA708Interpreter, [{
key: 'attach',
value: function attach(media) {
this.media = media;
this.display = [];
this.memory = [];
}
}, {
key: 'detach',
value: function detach() {
this.clear();
}
}, {
key: 'destroy',
value: function destroy() {}
}, {
key: '_createCue',
value: function _createCue() {
var VTTCue = window.VTTCue || window.TextTrackCue;
var cue = this.cue = new VTTCue(-1, -1, '');
cue.text = '';
cue.pauseOnExit = false;
// make sure it doesn't show up before it's ready
cue.startTime = Number.MAX_VALUE;
// show it 'forever' once we do show it
// (we'll set the end time once we know it later)
cue.endTime = Number.MAX_VALUE;
this.memory.push(cue);
}
}, {
key: 'clear',
value: function clear() {
var textTrack = this._textTrack;
if (textTrack && textTrack.cues) {
while (textTrack.cues.length > 0) {
textTrack.removeCue(textTrack.cues[0]);
}
}
}
}, {
key: 'push',
value: function push(timestamp, bytes) {
if (!this.cue) {
this._createCue();
}
var count = bytes[0] & 31;
var position = 2;
var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;
for (var j = 0; j < count; j++) {
tmpByte = bytes[position++];
ccbyte1 = 0x7F & bytes[position++];
ccbyte2 = 0x7F & bytes[position++];
ccValid = (4 & tmpByte) === 0 ? false : true;
ccType = 3 & tmpByte;
if (ccbyte1 === 0 && ccbyte2 === 0) {
continue;
}
if (ccValid) {
if (ccType === 0) // || ccType === 1
{
// Standard Characters
if (0x20 & ccbyte1 || 0x40 & ccbyte1) {
this.cue.text += this._fromCharCode(ccbyte1) + this._fromCharCode(ccbyte2);
}
// Special Characters
else if ((ccbyte1 === 0x11 || ccbyte1 === 0x19) && ccbyte2 >= 0x30 && ccbyte2 <= 0x3F) {
// extended chars, e.g. musical note, accents
switch (ccbyte2) {
case 48:
this.cue.text += '®';
break;
case 49:
this.cue.text += '°';
break;
case 50:
this.cue.text += '½';
break;
case 51:
this.cue.text += '¿';
break;
case 52:
this.cue.text += '™';
break;
case 53:
this.cue.text += '¢';
break;
case 54:
this.cue.text += '';
break;
case 55:
this.cue.text += '£';
break;
case 56:
this.cue.text += '♪';
break;
case 57:
this.cue.text += ' ';
break;
case 58:
this.cue.text += 'è';
break;
case 59:
this.cue.text += 'â';
break;
case 60:
this.cue.text += 'ê';
break;
case 61:
this.cue.text += 'î';
break;
case 62:
this.cue.text += 'ô';
break;
case 63:
this.cue.text += 'û';
break;
}
}
if ((ccbyte1 === 0x11 || ccbyte1 === 0x19) && ccbyte2 >= 0x20 && ccbyte2 <= 0x2F) {
// Mid-row codes: color/underline
switch (ccbyte2) {
case 0x20:
// White
break;
case 0x21:
// White Underline
break;
case 0x22:
// Green
break;
case 0x23:
// Green Underline
break;
case 0x24:
// Blue
break;
case 0x25:
// Blue Underline
break;
case 0x26:
// Cyan
break;
case 0x27:
// Cyan Underline
break;
case 0x28:
// Red
break;
case 0x29:
// Red Underline
break;
case 0x2A:
// Yellow
break;
case 0x2B:
// Yellow Underline
break;
case 0x2C:
// Magenta
break;
case 0x2D:
// Magenta Underline
break;
case 0x2E:
// Italics
break;
case 0x2F:
// Italics Underline
break;
}
}
if ((ccbyte1 === 0x14 || ccbyte1 === 0x1C) && ccbyte2 >= 0x20 && ccbyte2 <= 0x2F) {
// Mid-row codes: color/underline
switch (ccbyte2) {
case 0x20:
// TODO: shouldn't affect roll-ups...
this._clearActiveCues(timestamp);
// RCL: Resume Caption Loading
// begin pop on
break;
case 0x21:
// BS: Backspace
this.cue.text = this.cue.text.substr(0, this.cue.text.length - 1);
break;
case 0x22:
// AOF: reserved (formerly alarm off)
break;
case 0x23:
// AON: reserved (formerly alarm on)
break;
case 0x24:
// DER: Delete to end of row
break;
case 0x25:
// RU2: roll-up 2 rows
//this._rollup(2);
break;
case 0x26:
// RU3: roll-up 3 rows
//this._rollup(3);
break;
case 0x27:
// RU4: roll-up 4 rows
//this._rollup(4);
break;
case 0x28:
// FON: Flash on
break;
case 0x29:
// RDC: Resume direct captioning
this._clearActiveCues(timestamp);
break;
case 0x2A:
// TR: Text Restart
break;
case 0x2B:
// RTD: Resume Text Display
break;
case 0x2C:
// EDM: Erase Displayed Memory
this._clearActiveCues(timestamp);
break;
case 0x2D:
// CR: Carriage Return
// only affects roll-up
//this._rollup(1);
break;
case 0x2E:
// ENM: Erase non-displayed memory
this._text = '';
break;
case 0x2F:
this._flipMemory(timestamp);
// EOC: End of caption
// hide any displayed captions and show any hidden one
break;
}
}
if ((ccbyte1 === 0x17 || ccbyte1 === 0x1F) && ccbyte2 >= 0x21 && ccbyte2 <= 0x23) {
// Mid-row codes: color/underline
switch (ccbyte2) {
case 0x21:
// TO1: tab offset 1 column
break;
case 0x22:
// TO1: tab offset 2 column
break;
case 0x23:
// TO1: tab offset 3 column
break;
}
} else {
// Probably a pre-amble address code
}
}
}
}
}
}, {
key: '_fromCharCode',
value: function _fromCharCode(tmpByte) {
switch (tmpByte) {
case 42:
return 'á';
case 2:
return 'á';
case 2:
return 'é';
case 4:
return 'í';
case 5:
return 'ó';
case 6:
return 'ú';
case 3:
return 'ç';
case 4:
return '÷';
case 5:
return 'Ñ';
case 6:
return 'ñ';
case 7:
return '█';
default:
return String.fromCharCode(tmpByte);
}
}
}, {
key: '_flipMemory',
value: function _flipMemory(timestamp) {
this._clearActiveCues(timestamp);
this._flushCaptions(timestamp);
}
}, {
key: '_flushCaptions',
value: function _flushCaptions(timestamp) {
if (!this._has708) {
this._textTrack = this.media.addTextTrack('captions', 'English', 'en');
this._has708 = true;
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.memory[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var memoryItem = _step.value;
memoryItem.startTime = timestamp;
this._textTrack.addCue(memoryItem);
this.display.push(memoryItem);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this.memory = [];
this.cue = null;
}
}, {
key: '_clearActiveCues',
value: function _clearActiveCues(timestamp) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.display[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var displayItem = _step2.value;
displayItem.endTime = timestamp;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.display = [];
}
/* _rollUp(n)
{
// TODO: implement roll-up captions
}
*/
}, {
key: '_clearBufferedCues',
value: function _clearBufferedCues() {
//remove them all...
}
}]);
return CEA708Interpreter;
}();
exports.default = CEA708Interpreter;
},{}],37:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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"); } }
/*
* compute an Exponential Weighted moving average
* - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
* - heavily inspired from shaka-player
*/
var EWMA = function () {
// About half of the estimated value will be from the last |halfLife| samples by weight.
function EWMA(halfLife) {
_classCallCheck(this, EWMA);
// Larger values of alpha expire historical data more slowly.
this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
this.estimate_ = 0;
this.totalWeight_ = 0;
}
_createClass(EWMA, [{
key: "sample",
value: function sample(weight, value) {
var adjAlpha = Math.pow(this.alpha_, weight);
this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
this.totalWeight_ += weight;
}
}, {
key: "getTotalWeight",
value: function getTotalWeight() {
return this.totalWeight_;
}
}, {
key: "getEstimate",
value: function getEstimate() {
if (this.alpha_) {
var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
return this.estimate_ / zeroFactor;
} else {
return this.estimate_;
}
}
}]);
return EWMA;
}();
exports.default = EWMA;
},{}],38:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
function noop() {}
var fakeLogger = {
trace: noop,
debug: noop,
log: noop,
warn: noop,
info: noop,
error: noop
};
var exportedLogger = fakeLogger;
//let lastCallTime;
// function formatMsgWithTimeInfo(type, msg) {
// const now = Date.now();
// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
// lastCallTime = now;
// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
// return msg;
// }
function formatMsg(type, msg) {
msg = '[' + type + '] > ' + msg;
return msg;
}
function consolePrintFn(type) {
var func = window.console[type];
if (func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args[0]) {
args[0] = formatMsg(type, args[0]);
}
func.apply(window.console, args);
};
}
return noop;
}
function exportLoggerFunctions(debugConfig) {
for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
functions[_key2 - 1] = arguments[_key2];
}
functions.forEach(function (type) {
exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
});
}
var enableLogs = exports.enableLogs = function enableLogs(debugConfig) {
if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
exportLoggerFunctions(debugConfig,
// Remove out from list here to hard-disable a log-level
//'trace',
'debug', 'log', 'info', 'warn', 'error');
// Some browsers don't allow to use bind on console object anyway
// fallback to default if needed
try {
exportedLogger.log();
} catch (e) {
exportedLogger = fakeLogger;
}
} else {
exportedLogger = fakeLogger;
}
};
var logger = exports.logger = exportedLogger;
},{}],39:[function(require,module,exports){
'use strict';
var URLHelper = {
// build an absolute URL from a relative one using the provided baseURL
// if relativeURL is an absolute URL it will be returned as is.
buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL) {
// remove any remaining space and CRLF
relativeURL = relativeURL.trim();
if (/^[a-z]+:/i.test(relativeURL)) {
// complete url, not relative
return relativeURL;
}
var relativeURLQuery = null;
var relativeURLHash = null;
var relativeURLHashSplit = /^([^#]*)(.*)$/.exec(relativeURL);
if (relativeURLHashSplit) {
relativeURLHash = relativeURLHashSplit[2];
relativeURL = relativeURLHashSplit[1];
}
var relativeURLQuerySplit = /^([^\?]*)(.*)$/.exec(relativeURL);
if (relativeURLQuerySplit) {
relativeURLQuery = relativeURLQuerySplit[2];
relativeURL = relativeURLQuerySplit[1];
}
var baseURLHashSplit = /^([^#]*)(.*)$/.exec(baseURL);
if (baseURLHashSplit) {
baseURL = baseURLHashSplit[1];
}
var baseURLQuerySplit = /^([^\?]*)(.*)$/.exec(baseURL);
if (baseURLQuerySplit) {
baseURL = baseURLQuerySplit[1];
}
var baseURLDomainSplit = /^(([a-z]+:)?\/\/[a-z0-9\.\-_~]+(:[0-9]+)?)?(\/.*)$/i.exec(baseURL);
if (!baseURLDomainSplit) {
throw new Error('Error trying to parse base URL.');
}
// e.g. 'http:', 'https:', ''
var baseURLProtocol = baseURLDomainSplit[2] || '';
// e.g. 'http://example.com', '//example.com', ''
var baseURLProtocolDomain = baseURLDomainSplit[1] || '';
// e.g. '/a/b/c/playlist.m3u8'
var baseURLPath = baseURLDomainSplit[4];
var builtURL = null;
if (/^\/\//.test(relativeURL)) {
// relative url starts wth '//' so copy protocol (which may be '' if baseUrl didn't provide one)
builtURL = baseURLProtocol + '//' + URLHelper.buildAbsolutePath('', relativeURL.substring(2));
} else if (/^\//.test(relativeURL)) {
// relative url starts with '/' so start from root of domain
builtURL = baseURLProtocolDomain + '/' + URLHelper.buildAbsolutePath('', relativeURL.substring(1));
} else {
builtURL = URLHelper.buildAbsolutePath(baseURLProtocolDomain + baseURLPath, relativeURL);
}
// put the query and hash parts back
if (relativeURLQuery) {
builtURL += relativeURLQuery;
}
if (relativeURLHash) {
builtURL += relativeURLHash;
}
return builtURL;
},
// build an absolute path using the provided basePath
// adapted from https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Using_relative_URLs_in_the_path_parameter
// this does not handle the case where relativePath is "/" or "//". These cases should be handled outside this.
buildAbsolutePath: function buildAbsolutePath(basePath, relativePath) {
var sRelPath = relativePath;
var nUpLn,
sDir = '',
sPath = basePath.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, '$1'));
for (var nEnd, nStart = 0; nEnd = sPath.indexOf('/../', nStart), nEnd > -1; nStart = nEnd + nUpLn) {
nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp('(?:\\\/+[^\\\/]*){0,' + (nUpLn - 1) / 3 + '}$'), '/');
}
return sDir + sPath.substr(nStart);
}
};
module.exports = URLHelper;
},{}],40:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }(); /**
* XHR based logger
*/
var _logger = require('../utils/logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var XhrLoader = function () {
function XhrLoader(config) {
_classCallCheck(this, XhrLoader);
if (config && config.xhrSetup) {
this.xhrSetup = config.xhrSetup;
}
}
_createClass(XhrLoader, [{
key: 'destroy',
value: function destroy() {
this.abort();
this.loader = null;
}
}, {
key: 'abort',
value: function abort() {
var loader = this.loader,
timeoutHandle = this.timeoutHandle;
if (loader && loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
if (timeoutHandle) {
window.clearTimeout(timeoutHandle);
}
}
}, {
key: 'load',
value: function load(url, responseType, onSuccess, onError, onTimeout, timeout, maxRetry, retryDelay) {
var onProgress = arguments.length <= 8 || arguments[8] === undefined ? null : arguments[8];
var frag = arguments.length <= 9 || arguments[9] === undefined ? null : arguments[9];
this.url = url;
if (frag && !isNaN(frag.byteRangeStartOffset) && !isNaN(frag.byteRangeEndOffset)) {
this.byteRange = frag.byteRangeStartOffset + '-' + (frag.byteRangeEndOffset - 1);
}
this.responseType = responseType;
this.onSuccess = onSuccess;
this.onProgress = onProgress;
this.onTimeout = onTimeout;
this.onError = onError;
this.stats = { trequest: performance.now(), retry: 0 };
this.timeout = timeout;
this.maxRetry = maxRetry;
this.retryDelay = retryDelay;
this.loadInternal();
}
}, {
key: 'loadInternal',
value: function loadInternal() {
var xhr;
if (typeof XDomainRequest !== 'undefined') {
xhr = this.loader = new XDomainRequest();
} else {
xhr = this.loader = new XMLHttpRequest();
}
xhr.onloadend = this.loadend.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
xhr.open('GET', this.url, true);
if (this.byteRange) {
xhr.setRequestHeader('Range', 'bytes=' + this.byteRange);
}
xhr.responseType = this.responseType;
var stats = this.stats;
stats.tfirst = 0;
stats.loaded = 0;
if (this.xhrSetup) {
this.xhrSetup(xhr, this.url);
}
this.timeoutHandle = window.setTimeout(this.loadtimeout.bind(this), this.timeout);
xhr.send();
}
}, {
key: 'loadend',
value: function loadend(event) {
var xhr = event.currentTarget,
status = xhr.status,
stats = this.stats;
// don't proceed if xhr has been aborted
if (!stats.aborted) {
// http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
window.clearTimeout(this.timeoutHandle);
stats.tload = Math.max(stats.tfirst, performance.now());
this.onSuccess(event, stats);
} else {
// error ...
if (stats.retry < this.maxRetry) {
_logger.logger.warn(status + ' while loading ' + this.url + ', retrying in ' + this.retryDelay + '...');
this.destroy();
window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
// exponential backoff
this.retryDelay = Math.min(2 * this.retryDelay, 64000);
stats.retry++;
} else {
window.clearTimeout(this.timeoutHandle);
_logger.logger.error(status + ' while loading ' + this.url);
this.onError(event);
}
}
}
}
}, {
key: 'loadtimeout',
value: function loadtimeout(event) {
_logger.logger.warn('timeout while loading ' + this.url);
this.onTimeout(event, this.stats);
}
}, {
key: 'loadprogress',
value: function loadprogress(event) {
var stats = this.stats;
if (stats.tfirst === 0) {
stats.tfirst = Math.max(performance.now(), stats.trequest);
}
stats.loaded = event.loaded;
if (this.onProgress) {
this.onProgress(event, stats);
}
}
}]);
return XhrLoader;
}();
exports.default = XhrLoader;
},{"../utils/logger":38}]},{},[27])(27)
});
//# sourceMappingURL=hls.js.map
|
// knockout-sortable 0.13.0 | (c) 2016 Ryan Niemeyer | http://www.opensource.org/licenses/mit-license
;(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD anonymous module
define(["knockout", "jquery", "jquery-ui/sortable", "jquery-ui/draggable"], factory);
} else if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
// CommonJS module
var ko = require("knockout"),
jQuery = require("jquery");
require("jquery-ui/sortable");
require("jquery-ui/draggable");
factory(ko, jQuery);
} else {
// No module loader (plain <script> tag) - put directly in global namespace
factory(window.ko, window.jQuery);
}
})(function(ko, $) {
var ITEMKEY = "ko_sortItem",
INDEXKEY = "ko_sourceIndex",
LISTKEY = "ko_sortList",
PARENTKEY = "ko_parentList",
DRAGKEY = "ko_dragItem",
unwrap = ko.utils.unwrapObservable,
dataGet = ko.utils.domData.get,
dataSet = ko.utils.domData.set,
version = $.ui && $.ui.version,
//1.8.24 included a fix for how events were triggered in nested sortables. indexOf checks will fail if version starts with that value (0 vs. -1)
hasNestedSortableFix = version && version.indexOf("1.6.") && version.indexOf("1.7.") && (version.indexOf("1.8.") || version === "1.8.24");
//internal afterRender that adds meta-data to children
var addMetaDataAfterRender = function(elements, data) {
ko.utils.arrayForEach(elements, function(element) {
if (element.nodeType === 1) {
dataSet(element, ITEMKEY, data);
dataSet(element, PARENTKEY, dataGet(element.parentNode, LISTKEY));
}
});
};
//prepare the proper options for the template binding
var prepareTemplateOptions = function(valueAccessor, dataName) {
var result = {},
options = unwrap(valueAccessor()) || {},
actualAfterRender;
//build our options to pass to the template engine
if (options.data) {
result[dataName] = options.data;
result.name = options.template;
} else {
result[dataName] = valueAccessor();
}
ko.utils.arrayForEach(["afterAdd", "afterRender", "as", "beforeRemove", "includeDestroyed", "templateEngine", "templateOptions", "nodes"], function (option) {
if (options.hasOwnProperty(option)) {
result[option] = options[option];
} else if (ko.bindingHandlers.sortable.hasOwnProperty(option)) {
result[option] = ko.bindingHandlers.sortable[option];
}
});
//use an afterRender function to add meta-data
if (dataName === "foreach") {
if (result.afterRender) {
//wrap the existing function, if it was passed
actualAfterRender = result.afterRender;
result.afterRender = function(element, data) {
addMetaDataAfterRender.call(data, element, data);
actualAfterRender.call(data, element, data);
};
} else {
result.afterRender = addMetaDataAfterRender;
}
}
//return options to pass to the template binding
return result;
};
var updateIndexFromDestroyedItems = function(index, items) {
var unwrapped = unwrap(items);
if (unwrapped) {
for (var i = 0; i < index; i++) {
//add one for every destroyed item we find before the targetIndex in the target array
if (unwrapped[i] && unwrap(unwrapped[i]._destroy)) {
index++;
}
}
}
return index;
};
//remove problematic leading/trailing whitespace from templates
var stripTemplateWhitespace = function(element, name) {
var templateSource,
templateElement;
//process named templates
if (name) {
templateElement = document.getElementById(name);
if (templateElement) {
templateSource = new ko.templateSources.domElement(templateElement);
templateSource.text($.trim(templateSource.text()));
}
}
else {
//remove leading/trailing non-elements from anonymous templates
$(element).contents().each(function() {
if (this && this.nodeType !== 1) {
element.removeChild(this);
}
});
}
};
//connect items with observableArrays
ko.bindingHandlers.sortable = {
init: function(element, valueAccessor, allBindingsAccessor, data, context) {
var $element = $(element),
value = unwrap(valueAccessor()) || {},
templateOptions = prepareTemplateOptions(valueAccessor, "foreach"),
sortable = {},
startActual, updateActual;
stripTemplateWhitespace(element, templateOptions.name);
//build a new object that has the global options with overrides from the binding
$.extend(true, sortable, ko.bindingHandlers.sortable);
if (value.options && sortable.options) {
ko.utils.extend(sortable.options, value.options);
delete value.options;
}
ko.utils.extend(sortable, value);
//if allowDrop is an observable or a function, then execute it in a computed observable
if (sortable.connectClass && (ko.isObservable(sortable.allowDrop) || typeof sortable.allowDrop == "function")) {
ko.computed({
read: function() {
var value = unwrap(sortable.allowDrop),
shouldAdd = typeof value == "function" ? value.call(this, templateOptions.foreach) : value;
ko.utils.toggleDomNodeCssClass(element, sortable.connectClass, shouldAdd);
},
disposeWhenNodeIsRemoved: element
}, this);
} else {
ko.utils.toggleDomNodeCssClass(element, sortable.connectClass, sortable.allowDrop);
}
//wrap the template binding
ko.bindingHandlers.template.init(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
//keep a reference to start/update functions that might have been passed in
startActual = sortable.options.start;
updateActual = sortable.options.update;
//ensure draggable table row cells maintain their width while dragging
sortable.options.helper = function(e, ui) {
if (ui.is("tr")) {
ui.children().each(function() {
$(this).width($(this).width());
});
}
return ui;
};
//initialize sortable binding after template binding has rendered in update function
var createTimeout = setTimeout(function() {
var dragItem;
$element.sortable(ko.utils.extend(sortable.options, {
start: function(event, ui) {
//track original index
var el = ui.item[0];
dataSet(el, INDEXKEY, ko.utils.arrayIndexOf(ui.item.parent().children(), el));
//make sure that fields have a chance to update model
ui.item.find("input:focus").change();
if (startActual) {
startActual.apply(this, arguments);
}
},
receive: function(event, ui) {
dragItem = dataGet(ui.item[0], DRAGKEY);
if (dragItem) {
//copy the model item, if a clone option is provided
if (dragItem.clone) {
dragItem = dragItem.clone();
}
//configure a handler to potentially manipulate item before drop
if (sortable.dragged) {
dragItem = sortable.dragged.call(this, dragItem, event, ui) || dragItem;
}
}
},
update: function(event, ui) {
var sourceParent, targetParent, sourceIndex, targetIndex, arg,
el = ui.item[0],
parentEl = ui.item.parent()[0],
item = dataGet(el, ITEMKEY) || dragItem;
dragItem = null;
//make sure that moves only run once, as update fires on multiple containers
if (item && (this === parentEl) || (!hasNestedSortableFix && $.contains(this, parentEl))) {
//identify parents
sourceParent = dataGet(el, PARENTKEY);
sourceIndex = dataGet(el, INDEXKEY);
targetParent = dataGet(el.parentNode, LISTKEY);
targetIndex = ko.utils.arrayIndexOf(ui.item.parent().children(), el);
//take destroyed items into consideration
if (!templateOptions.includeDestroyed) {
sourceIndex = updateIndexFromDestroyedItems(sourceIndex, sourceParent);
targetIndex = updateIndexFromDestroyedItems(targetIndex, targetParent);
}
//build up args for the callbacks
if (sortable.beforeMove || sortable.afterMove) {
arg = {
item: item,
sourceParent: sourceParent,
sourceParentNode: sourceParent && ui.sender || el.parentNode,
sourceIndex: sourceIndex,
targetParent: targetParent,
targetIndex: targetIndex,
cancelDrop: false
};
//execute the configured callback prior to actually moving items
if (sortable.beforeMove) {
sortable.beforeMove.call(this, arg, event, ui);
}
}
//call cancel on the correct list, so KO can take care of DOM manipulation
if (sourceParent) {
$(sourceParent === targetParent ? this : ui.sender || this).sortable("cancel");
}
//for a draggable item just remove the element
else {
$(el).remove();
}
//if beforeMove told us to cancel, then we are done
if (arg && arg.cancelDrop) {
return;
}
//if the strategy option is unset or false, employ the order strategy involving removal and insertion of items
if (!sortable.hasOwnProperty("strategyMove") || sortable.strategyMove === false) {
//do the actual move
if (targetIndex >= 0) {
if (sourceParent) {
sourceParent.splice(sourceIndex, 1);
//if using deferred updates plugin, force updates
if (ko.processAllDeferredBindingUpdates) {
ko.processAllDeferredBindingUpdates();
}
}
targetParent.splice(targetIndex, 0, item);
}
//rendering is handled by manipulating the observableArray; ignore dropped element
dataSet(el, ITEMKEY, null);
}
else { //employ the strategy of moving items
console.log( "strategy move" );
if (targetIndex >= 0) {
if (sourceParent) {
if (sourceParent !== targetParent) {
// moving from one list to another
sourceParent.splice(sourceIndex, 1);
//if using deferred updates plugin, force updates
if (ko.processAllDeferredBindingUpdates) {
ko.processAllDeferredBindingUpdates();
}
targetParent.splice(targetIndex, 0, item);
//rendering is handled by manipulating the observableArray; ignore dropped element
dataSet(el, ITEMKEY, null);
ui.item.remove();
}
else {
// moving within same list
var underlyingList = unwrap(sourceParent);
// notify 'beforeChange' subscribers
sourceParent.valueWillMutate();
// move from source index ...
underlyingList.splice(sourceIndex, 1);
// ... to target index
underlyingList.splice(targetIndex, 0, item);
// notify subscribers
sourceParent.valueHasMutated();
}
}
else {
// drop new element from outside
targetParent.splice(targetIndex, 0, item);
//rendering is handled by manipulating the observableArray; ignore dropped element
dataSet(el, ITEMKEY, null);
ui.item.remove();
}
}
}
//if using deferred updates plugin, force updates
if (ko.processAllDeferredBindingUpdates) {
ko.processAllDeferredBindingUpdates();
}
//allow binding to accept a function to execute after moving the item
if (sortable.afterMove) {
sortable.afterMove.call(this, arg, event, ui);
}
}
if (updateActual) {
updateActual.apply(this, arguments);
}
},
connectWith: sortable.connectClass ? "." + sortable.connectClass : false
}));
//handle enabling/disabling sorting
if (sortable.isEnabled !== undefined) {
ko.computed({
read: function() {
$element.sortable(unwrap(sortable.isEnabled) ? "enable" : "disable");
},
disposeWhenNodeIsRemoved: element
});
}
}, 0);
//handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
//only call destroy if sortable has been created
if ($element.data("ui-sortable") || $element.data("sortable")) {
$element.sortable("destroy");
}
ko.utils.toggleDomNodeCssClass(element, sortable.connectClass, false);
//do not create the sortable if the element has been removed from DOM
clearTimeout(createTimeout);
});
return { 'controlsDescendantBindings': true };
},
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
var templateOptions = prepareTemplateOptions(valueAccessor, "foreach");
//attach meta-data
dataSet(element, LISTKEY, templateOptions.foreach);
//call template binding's update with correct options
ko.bindingHandlers.template.update(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
},
connectClass: 'ko_container',
allowDrop: true,
afterMove: null,
beforeMove: null,
options: {}
};
//create a draggable that is appropriate for dropping into a sortable
ko.bindingHandlers.draggable = {
init: function(element, valueAccessor, allBindingsAccessor, data, context) {
var value = unwrap(valueAccessor()) || {},
options = value.options || {},
draggableOptions = ko.utils.extend({}, ko.bindingHandlers.draggable.options),
templateOptions = prepareTemplateOptions(valueAccessor, "data"),
connectClass = value.connectClass || ko.bindingHandlers.draggable.connectClass,
isEnabled = value.isEnabled !== undefined ? value.isEnabled : ko.bindingHandlers.draggable.isEnabled;
value = "data" in value ? value.data : value;
//set meta-data
dataSet(element, DRAGKEY, value);
//override global options with override options passed in
ko.utils.extend(draggableOptions, options);
//setup connection to a sortable
draggableOptions.connectToSortable = connectClass ? "." + connectClass : false;
//initialize draggable
$(element).draggable(draggableOptions);
//handle enabling/disabling sorting
if (isEnabled !== undefined) {
ko.computed({
read: function() {
$(element).draggable(unwrap(isEnabled) ? "enable" : "disable");
},
disposeWhenNodeIsRemoved: element
});
}
//handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).draggable("destroy");
});
return ko.bindingHandlers.template.init(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
},
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
var templateOptions = prepareTemplateOptions(valueAccessor, "data");
return ko.bindingHandlers.template.update(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
},
connectClass: ko.bindingHandlers.sortable.connectClass,
options: {
helper: "clone"
}
};
});
|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
path = require('path'),
config = require(path.resolve('./config/config')),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User'),
nodemailer = require('nodemailer'),
crypto = require('crypto'),
async = require('async'),
crypto = require('crypto');
/**
* Forgot for reset password (forgot POST)
*/
exports.forgot = function(req, res, next) {
async.waterfall([
// Generate random token
function(done) {
crypto.randomBytes(20, function(err, buffer) {
var token = buffer.toString('hex');
done(err, token);
});
},
// Lookup user by username
function(token, done) {
if (req.body.username) {
User.findOne({
username: req.body.username
}, '-salt -password', function(err, user) {
if (!user) {
return res.status(400).send({
message: 'No account with that username has been found'
});
} else if (user.provider !== 'local') {
return res.status(400).send({
message: 'It seems like you signed up using your ' + user.provider + ' account'
});
} else {
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
}
});
} else {
return res.status(400).send({
message: 'Username field must not be blank'
});
}
},
function(token, user, done) {
res.render(path.resolve('modules/users/server/templates/reset-password-email'), {
name: user.displayName,
appName: config.app.title,
url: 'http://' + req.headers.host + '/api/auth/reset/' + token
}, function(err, emailHTML) {
done(err, emailHTML, user);
});
},
// If valid email, send reset email using service
function(emailHTML, user, done) {
var smtpTransport = nodemailer.createTransport(config.mailer.options);
var mailOptions = {
to: user.email,
from: config.mailer.from,
subject: 'Password Reset',
html: emailHTML
};
smtpTransport.sendMail(mailOptions, function(err) {
if (!err) {
res.send({
message: 'An email has been sent to ' + user.email + ' with further instructions.'
});
}
done(err);
});
}
], function(err) {
if (err) return next(err);
});
};
/**
* Reset password GET from email token
*/
exports.validateResetToken = function(req, res) {
User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: {
$gt: Date.now()
}
}, function(err, user) {
if (!user) {
return res.redirect('/#!/password/reset/invalid');
}
res.redirect('/#!/password/reset/' + req.params.token);
});
};
/**
* Reset password POST from email token
*/
exports.reset = function(req, res, next) {
// Init Variables
var passwordDetails = req.body;
var message = null;
async.waterfall([
function(done) {
User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: {
$gt: Date.now()
}
}, function(err, user) {
if (!err && user) {
if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
user.password = passwordDetails.newPassword;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
// Return authenticated user
res.json(user);
done(err, user);
}
});
}
});
} else {
return res.status(400).send({
message: 'Passwords do not match'
});
}
} else {
return res.status(400).send({
message: 'Password reset token is invalid or has expired.'
});
}
});
},
function(user, done) {
res.render('modules/users/server/templates/reset-password-confirm-email', {
name: user.displayName,
appName: config.app.title
}, function(err, emailHTML) {
done(err, emailHTML, user);
});
},
// If valid email, send reset email using service
function(emailHTML, user, done) {
var smtpTransport = nodemailer.createTransport(config.mailer.options);
var mailOptions = {
to: user.email,
from: config.mailer.from,
subject: 'Your password has been changed',
html: emailHTML
};
smtpTransport.sendMail(mailOptions, function(err) {
done(err, 'done');
});
}
], function(err) {
if (err) return next(err);
});
};
/**
* Change Password
*/
exports.changePassword = function(req, res, next) {
// Init Variables
var passwordDetails = req.body;
var message = null;
if (req.user) {
if (passwordDetails.newPassword) {
User.findById(req.user.id, function(err, user) {
if (!err && user) {
if (user.authenticate(passwordDetails.currentPassword)) {
if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
user.password = passwordDetails.newPassword;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.send({
message: 'Password changed successfully'
});
}
});
}
});
} else {
res.status(400).send({
message: 'Passwords do not match'
});
}
} else {
res.status(400).send({
message: 'Current password is incorrect'
});
}
} else {
res.status(400).send({
message: 'User is not found'
});
}
});
} else {
res.status(400).send({
message: 'Please provide a new password'
});
}
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
|
'use strict';
const path = require('path'); /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/const childProcess = require('child_process');const env = Object.assign({}, process.env, { HGPLAIN: 1 });
function findChangedFiles(cwd, options) {
return new Promise((resolve, reject) => {
let args = ['status', '-amn'];
if (options && options.withAncestor) {
args.push('--rev', 'ancestor(.^)');
} else if (options && options.lastCommit === true) {
args = ['tip', '--template', '{files%"{file}\n"}'];
}
const child = childProcess.spawn('hg', args, { cwd, env });
let stdout = '';
let stderr = '';
child.stdout.on('data', data => stdout += data);
child.stderr.on('data', data => stderr += data);
child.on('error', e => reject(e));
child.on('close', code => {
if (code === 0) {
stdout = stdout.trim();
if (stdout === '') {
resolve([]);
} else {
resolve(
stdout.
split('\n').
map(changedPath => path.resolve(cwd, changedPath)));
}
} else {
reject(code + ': ' + stderr);
}
});
});
}
function isHGRepository(cwd) {
return new Promise(resolve => {
try {
let stdout = '';
const child = childProcess.spawn('hg', ['root'], { cwd, env });
child.stdout.on('data', data => stdout += data);
child.on('error', () => resolve(null));
child.on('close', code => resolve(code === 0 ? stdout.trim() : null));
} catch (e) {
resolve(null);
}
});
}
module.exports = {
findChangedFiles,
isHGRepository }; |
//>>built
define("dojox/atom/widget/nls/uk/PeopleEditor",({add:"Додати",addAuthor:"Додати автора",addContributor:"Додати учасника"}));
|
/*
angular-md5 - v0.1.6
2014-01-14
*/
(function(window, angular, undefined) {
angular.module("angular-md5", [ "gdi2290.md5" ]);
angular.module("ngMd5", [ "gdi2290.md5" ]);
angular.module("gdi2290.md5", []);
"use strict";
angular.module("gdi2290.gravatar-filter", []).filter("gravatar", [ "md5", function(md5) {
return function(text) {
return text ? md5.createHash(text.toString().toLowerCase()) : "";
};
} ]);
"use strict";
angular.module("gdi2290.md5-filter", []).filter("md5", [ "md5", function(md5) {
return function(text) {
return text ? md5.createHash(text.toString().toLowerCase()) : text;
};
} ]);
"use strict";
angular.module("gdi2290.md5", []).factory("md5", [ function() {
var md5 = {
createHash: function(str) {
var xl;
var rotateLeft = function(lValue, iShiftBits) {
return lValue << iShiftBits | lValue >>> 32 - iShiftBits;
};
var addUnsigned = function(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = lX & 2147483648;
lY8 = lY & 2147483648;
lX4 = lX & 1073741824;
lY4 = lY & 1073741824;
lResult = (lX & 1073741823) + (lY & 1073741823);
if (lX4 & lY4) {
return lResult ^ 2147483648 ^ lX8 ^ lY8;
}
if (lX4 | lY4) {
if (lResult & 1073741824) {
return lResult ^ 3221225472 ^ lX8 ^ lY8;
} else {
return lResult ^ 1073741824 ^ lX8 ^ lY8;
}
} else {
return lResult ^ lX8 ^ lY8;
}
};
var _F = function(x, y, z) {
return x & y | ~x & z;
};
var _G = function(x, y, z) {
return x & z | y & ~z;
};
var _H = function(x, y, z) {
return x ^ y ^ z;
};
var _I = function(x, y, z) {
return y ^ (x | ~z);
};
var _FF = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var _GG = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var _HH = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var _II = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var convertToWordArray = function(str) {
var lWordCount;
var lMessageLength = str.length;
var lNumberOfWords_temp1 = lMessageLength + 8;
var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - lNumberOfWords_temp1 % 64) / 64;
var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
var lWordArray = new Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - lByteCount % 4) / 4;
lBytePosition = lByteCount % 4 * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | str.charCodeAt(lByteCount) << lBytePosition;
lByteCount++;
}
lWordCount = (lByteCount - lByteCount % 4) / 4;
lBytePosition = lByteCount % 4 * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | 128 << lBytePosition;
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var wordToHex = function(lValue) {
var wordToHexValue = "", wordToHexValue_temp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = lValue >>> lCount * 8 & 255;
wordToHexValue_temp = "0" + lByte.toString(16);
wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length - 2, 2);
}
return wordToHexValue;
};
var x = [], k, AA, BB, CC, DD, a, b, c, d, S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20, S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21;
x = convertToWordArray(str);
a = 1732584193;
b = 4023233417;
c = 2562383102;
d = 271733878;
xl = x.length;
for (k = 0; k < xl; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = _FF(a, b, c, d, x[k + 0], S11, 3614090360);
d = _FF(d, a, b, c, x[k + 1], S12, 3905402710);
c = _FF(c, d, a, b, x[k + 2], S13, 606105819);
b = _FF(b, c, d, a, x[k + 3], S14, 3250441966);
a = _FF(a, b, c, d, x[k + 4], S11, 4118548399);
d = _FF(d, a, b, c, x[k + 5], S12, 1200080426);
c = _FF(c, d, a, b, x[k + 6], S13, 2821735955);
b = _FF(b, c, d, a, x[k + 7], S14, 4249261313);
a = _FF(a, b, c, d, x[k + 8], S11, 1770035416);
d = _FF(d, a, b, c, x[k + 9], S12, 2336552879);
c = _FF(c, d, a, b, x[k + 10], S13, 4294925233);
b = _FF(b, c, d, a, x[k + 11], S14, 2304563134);
a = _FF(a, b, c, d, x[k + 12], S11, 1804603682);
d = _FF(d, a, b, c, x[k + 13], S12, 4254626195);
c = _FF(c, d, a, b, x[k + 14], S13, 2792965006);
b = _FF(b, c, d, a, x[k + 15], S14, 1236535329);
a = _GG(a, b, c, d, x[k + 1], S21, 4129170786);
d = _GG(d, a, b, c, x[k + 6], S22, 3225465664);
c = _GG(c, d, a, b, x[k + 11], S23, 643717713);
b = _GG(b, c, d, a, x[k + 0], S24, 3921069994);
a = _GG(a, b, c, d, x[k + 5], S21, 3593408605);
d = _GG(d, a, b, c, x[k + 10], S22, 38016083);
c = _GG(c, d, a, b, x[k + 15], S23, 3634488961);
b = _GG(b, c, d, a, x[k + 4], S24, 3889429448);
a = _GG(a, b, c, d, x[k + 9], S21, 568446438);
d = _GG(d, a, b, c, x[k + 14], S22, 3275163606);
c = _GG(c, d, a, b, x[k + 3], S23, 4107603335);
b = _GG(b, c, d, a, x[k + 8], S24, 1163531501);
a = _GG(a, b, c, d, x[k + 13], S21, 2850285829);
d = _GG(d, a, b, c, x[k + 2], S22, 4243563512);
c = _GG(c, d, a, b, x[k + 7], S23, 1735328473);
b = _GG(b, c, d, a, x[k + 12], S24, 2368359562);
a = _HH(a, b, c, d, x[k + 5], S31, 4294588738);
d = _HH(d, a, b, c, x[k + 8], S32, 2272392833);
c = _HH(c, d, a, b, x[k + 11], S33, 1839030562);
b = _HH(b, c, d, a, x[k + 14], S34, 4259657740);
a = _HH(a, b, c, d, x[k + 1], S31, 2763975236);
d = _HH(d, a, b, c, x[k + 4], S32, 1272893353);
c = _HH(c, d, a, b, x[k + 7], S33, 4139469664);
b = _HH(b, c, d, a, x[k + 10], S34, 3200236656);
a = _HH(a, b, c, d, x[k + 13], S31, 681279174);
d = _HH(d, a, b, c, x[k + 0], S32, 3936430074);
c = _HH(c, d, a, b, x[k + 3], S33, 3572445317);
b = _HH(b, c, d, a, x[k + 6], S34, 76029189);
a = _HH(a, b, c, d, x[k + 9], S31, 3654602809);
d = _HH(d, a, b, c, x[k + 12], S32, 3873151461);
c = _HH(c, d, a, b, x[k + 15], S33, 530742520);
b = _HH(b, c, d, a, x[k + 2], S34, 3299628645);
a = _II(a, b, c, d, x[k + 0], S41, 4096336452);
d = _II(d, a, b, c, x[k + 7], S42, 1126891415);
c = _II(c, d, a, b, x[k + 14], S43, 2878612391);
b = _II(b, c, d, a, x[k + 5], S44, 4237533241);
a = _II(a, b, c, d, x[k + 12], S41, 1700485571);
d = _II(d, a, b, c, x[k + 3], S42, 2399980690);
c = _II(c, d, a, b, x[k + 10], S43, 4293915773);
b = _II(b, c, d, a, x[k + 1], S44, 2240044497);
a = _II(a, b, c, d, x[k + 8], S41, 1873313359);
d = _II(d, a, b, c, x[k + 15], S42, 4264355552);
c = _II(c, d, a, b, x[k + 6], S43, 2734768916);
b = _II(b, c, d, a, x[k + 13], S44, 1309151649);
a = _II(a, b, c, d, x[k + 4], S41, 4149444226);
d = _II(d, a, b, c, x[k + 11], S42, 3174756917);
c = _II(c, d, a, b, x[k + 2], S43, 718787259);
b = _II(b, c, d, a, x[k + 9], S44, 3951481745);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
return temp.toLowerCase();
}
};
return md5;
} ]);
})(this, this.angular, void 0); |
/* global CodeMirror */
import Ember from 'ember';
const {Component} = Ember;
export default Component.extend({
classNameBindings: ['isFocused:focused'],
value: '', // make sure a value exists
isFocused: false,
// options for the editor
lineNumbers: true,
indentUnit: 4,
mode: 'htmlmixed',
theme: 'xq-light',
_editor: null, // reference to CodeMirror editor
didInsertElement() {
this._super(...arguments);
let options = this.getProperties('lineNumbers', 'indentUnit', 'mode', 'theme');
let editor = new CodeMirror(this.get('element'), options);
editor.getDoc().setValue(this.get('value'));
// events
editor.on('focus', Ember.run.bind(this, 'set', 'isFocused', true));
editor.on('blur', Ember.run.bind(this, 'set', 'isFocused', false));
editor.on('change', () => {
Ember.run(this, function () {
this.set('value', editor.getDoc().getValue());
});
});
this._editor = editor;
},
willDestroyElement() {
this._super(...arguments);
let editor = this._editor.getWrapperElement();
editor.parentNode.removeChild(editor);
this._editor = null;
}
});
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["InspireTree"] = factory();
else
root["InspireTree"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// Libs
var assign = __webpack_require__(1);
var cloneDeep = __webpack_require__(12);
var cuid = __webpack_require__(17);
var defaultsDeep = __webpack_require__(18);
var each = __webpack_require__(24);
var EventEmitter = __webpack_require__(26);
var find = __webpack_require__(27);
var findIndex = __webpack_require__(33);
var findLast = __webpack_require__(34);
var isArray = __webpack_require__(7);
var isArrayLike = __webpack_require__(37);
var isEmpty = __webpack_require__(38);
var isFunction = __webpack_require__(39);
var isObject = __webpack_require__(41);
var isRegExp = __webpack_require__(42);
var isString = __webpack_require__(40);
var map = __webpack_require__(43);
var remove = __webpack_require__(45);
var slice = __webpack_require__(47);
var sortBy = __webpack_require__(49);
// CSS
__webpack_require__(52);
function InspireTree(opts) {
if (!isObject(opts) || !opts.target) {
throw new TypeError('Property "target" is required, either an element or a selector.');
}
var noop = function() {};
var tree = this;
tree.preventDeselection = false;
// Assign defaults
tree.config = defaultsDeep(opts, {
allowSelection: noop,
contextMenu: false,
dragTargets: false,
dynamic: false,
multiselect: false,
renderer: false,
search: false,
sort: false,
tabindex: -1
});
// Cache some configs
var isDynamic = tree.config.dynamic;
// Rendering
var dom = isFunction(tree.config.renderer) ? tree.config.renderer(tree) : {
applyChanges: noop,
attach: noop,
batch: noop,
end: noop
};
// Webpack has a DOM boolean that when false,
// allows us to exclude this library from our build.
// For those doing their own rendering, it's useless.
if (false) {
dom = new (require('./dom'))(tree);
}
/**
* Represents a singe node object within the tree.
*
* @param {TreeNode} source TreeNode to copy.
* @return {TreeNode} Tree node object.
*/
function TreeNode(source) {
var node = this;
each(source, function(value, key) {
if (isObject(value) && isFunction(value.clone)) {
if (value.clone) {
node[key] = value.clone();
}
}
else if (isObject(value)) {
node[key] = cloneDeep(value);
}
else {
node[key] = value;
}
});
};
/**
* Add a child to this node.
*
* @category TreeNode
* @param {object} child Node object.
* @return {TreeNode} Node object.
*/
TreeNode.prototype.addChild = function(child) {
child = objectToModel(child);
if (!isArrayLike(this.children)) {
this.children = new TreeNodes();
}
child.itree.parent = this;
this.children.push(child);
child.markDirty();
dom.applyChanges();
return child;
};
/**
* Get if node available.
*
* @category TreeNode
* @return {boolean} If available.
*/
TreeNode.prototype.available = function() {
return (!this.hidden() && !this.removed());
};
/**
* Blur focus from this node.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.blur = function() {
return baseStateChange('focused', false, 'blurred', this);
};
/**
* Clones this node.
*
* @category TreeNode
* @return {TreeNode} New node object.
*/
TreeNode.prototype.clone = function() {
var newClone = new TreeNode(this);
if (this.hasChildren()) {
newClone.children = this.children.clone();
}
return newClone;
};
/**
* Collapse this node.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.collapse = function() {
return baseStateChange('collapsed', true, 'collapsed', this);
};
/**
* Get if node collapsed.
*
* @category TreeNode
* @return {boolean} If collapsed.
*/
TreeNode.prototype.collapsed = function() {
return this.itree.state.collapsed;
};
/**
* Copies node to a new tree instance.
*
* @category TreeNode
* @param {boolean} hierarchy Include necessary ancestors to match hierarchy.
* @return {object} Property "to" for defining destination.
*/
TreeNode.prototype.copy = function(hierarchy) {
var node = this;
if (hierarchy) {
node = node.copyHierarchy();
}
return {
/**
* Sets a destination.
*
* @category CopyNode
* @param {object} dest Destination Inspire Tree.
* @return {object} New node object.
*/
to: function(dest) {
if (!isFunction(dest.addNode)) {
throw new Error('Destination must be an Inspire Tree instance.');
}
return dest.addNode(node.export());
}
};
};
/**
* Copies all parents of a node.
*
* @category TreeNode
* @param {boolean} excludeNode Exclude given node from hierarchy.
* @return {TreeNode} Root node object with hierarchy.
*/
TreeNode.prototype.copyHierarchy = function(excludeNode) {
var node = this;
var parents = node.getParents().clone();
// Remove old hierarchy data
map(parents, function(node) {
delete node.itree.parent;
delete node.children;
return node;
});
parents = parents.reverse();
if (!excludeNode) {
parents.push(node);
}
var hierarchy = parents[0];
var pointer = hierarchy;
var l = parents.length;
each(parents, function(parent, key) {
var children = new TreeNodes();
if (key + 1 < l) {
children.push(parents[key + 1]);
pointer.children = children;
pointer = pointer.children[0];
}
});
return hierarchy;
};
/**
* Deselect this node.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.deselect = function() {
return baseStateChange('selected', false, 'deselected', this);
};
/**
* Expand this node.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.expand = function() {
var node = this;
var allow = (node.hasChildren() || isDynamic);
if (allow && (node.collapsed() || node.hidden())) {
node.itree.state.collapsed = false;
node.itree.state.hidden = false;
tree.emit('node.expanded', node);
if (isDynamic && !node.hasChildren()) {
node.loadChildren();
}
else {
node.markDirty();
dom.applyChanges();
}
}
return node;
};
/**
* Expand parent nodes.
*
* @category TreeNode
* @return {void}
*/
TreeNode.prototype.expandParents = function() {
if (this.hasParent()) {
this.getParent().recurseUp(function(node) {
return node.expand();
});
}
};
/**
* Get if node expanded.
*
* @category TreeNode
* @return {boolean} If expanded.
*/
TreeNode.prototype.expanded = function() {
return !this.collapsed();
};
/**
* Clones a node object and removes any
* itree instance information/state.
*
* @category TreeNode
* @return {TreeNode} Cloned/modified node object.
*/
TreeNode.prototype.export = function() {
var nodeClone = this.clone();
tree.recurseDown(nodeClone, function(node) {
node.itree = null;
return node;
});
return nodeClone;
};
/**
* Focus a node without changing its selection.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.focus = function() {
var node = this;
if (!node.focused()) {
// Batch selection changes
dom.batch();
tree.getNodes().blurDeep();
node.itree.state.focused = true;
// Emit this event
tree.emit('node.focused', node);
// Mark hierarchy dirty and apply
node.markDirty();
dom.end();
}
return node;
};
/**
* Get whether node has focus or not.
*
* @category TreeNode
* @return {boolean} If focused.
*/
TreeNode.prototype.focused = function() {
return this.itree.state.focused;
};
/**
* Get the immediate parent, if any.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.getParent = function() {
return this.itree.parent;
};
/**
* Returns parent nodes. Excludes any siblings.
*
* @category TreeNode
* @return {TreeNodes} Node objects.
*/
TreeNode.prototype.getParents = function() {
var parents = new TreeNodes();
var parent = this.getParent();
if (parent) {
parents.push(parent);
parents = parents.concat(parent.getParents());
}
return parents;
};
/**
* Get a textual hierarchy for a given node. An array
* of text from this node's root ancestor to the given node.
*
* @category TreeNode
* @return {array} Array of node texts.
*/
TreeNode.prototype.getTextualHierarchy = function() {
var node = this;
var paths = [];
var parents = node.getParents().reverse();
each(parents, function(parent) {
paths.push(parent.text);
});
paths.push(node.text);
return paths;
};
/**
* If node has any children.
*
* @category TreeNode
* @return {boolean} If children.
*/
TreeNode.prototype.hasChildren = function() {
return (isArrayLike(this.children) && this.children.length > 0);
};
/**
* If node has a parent.
*
* @category TreeNode
* @return {boolean} If parent.
*/
TreeNode.prototype.hasParent = function() {
return Boolean(this.itree.parent);
};
/**
* If node has any visible children.
*
* @category TreeNode
* @return {boolean} If visible children.
*/
TreeNode.prototype.hasVisibleChildren = function() {
var hasVisibleChildren = false;
if (this.hasChildren()) {
// Count visible children
// http://jsperf.com/count-subdoc-state/2
var visibleCount = 0;
each(this.children, function(child) {
if (!child.hidden() && !child.removed()) {
visibleCount++;
}
});
hasVisibleChildren = (visibleCount > 0);
}
return hasVisibleChildren;
};
/**
* Get if node hidden.
*
* @category TreeNode
* @return {boolean} If hidden.
*/
TreeNode.prototype.hidden = function() {
return this.itree.state.hidden;
};
/**
* Hide this node.
*
* @category TreeNode
* @return {object} Node object.
*/
TreeNode.prototype.hide = function() {
var node = baseStateChange('hidden', true, 'hidden', this);
// Update children
if (node.hasChildren()) {
node.children.hide();
}
return node;
};
/**
* Initiate a dynamic load of children for a given node.
*
* This requires `tree.config.data` to be a function which accepts
* three arguments: node, resolve, reject.
*
* Use the `node` to filter results.
*
* On load success, pass the result array to `resolve`.
* On error, pass the Error to `reject`.
*
* @category TreeNode
* @return {void}
*/
TreeNode.prototype.loadChildren = function() {
var node = this;
if (isDynamic) {
node.itree.state.loading = true;
node.markDirty();
dom.applyChanges();
tree.config.data(
node,
function resolver(results) {
dom.batch();
node.itree.state.loading = false;
node.children = collectionToModel(results, node);
node.markDirty();
dom.end();
},
function rejecter(err) {
tree.emit('tree.loaderror', err);
node.itree.state.loading = false;
node.children = new TreeNodes();
node.markDirty();
dom.applyChanges();
}
);
}
};
/**
* Mark a node as dirty, rebuilding this node in the virtual DOM
* and rerendering to the live DOM, next time applyChanges is called.
*
* @category TreeNode
* @param {boolean} noRecursion Skip recursing up parent tree.
* @return {TreeNode} Node object.
*/
TreeNode.prototype.markDirty = function(noRecursion) {
if (noRecursion) {
this.itree.dirty = true;
}
else {
this.recurseUp(function(node) {
return node.markDirty(true);
});
}
return this;
};
/**
* Find next visible child node.
*
* @category TreeNode
* @return {TreeNode} Node object, if any.
*/
TreeNode.prototype.nextVisibleChildNode = function() {
var startingNode = this;
var next;
if (startingNode.hasChildren()) {
next = find(startingNode.children, function(child) {
return child.visible();
});
}
return next;
};
/**
* Get the next visible node.
*
* @category TreeNode
* @return {TreeNode} Node object if any.
*/
TreeNode.prototype.nextVisibleNode = function() {
var startingNode = this;
var next;
// 1. Any visible children
next = startingNode.nextVisibleChildNode();
// 2. Any Siblings
if (!next) {
next = startingNode.nextVisibleSiblingNode();
}
// 3. Find sibling of ancestor(s)
if (!next && startingNode.hasParent()) {
next = startingNode.getParent().nextVisibleSiblingNode();
}
return next;
};
/**
* Find the next visible sibling node.
*
* @category TreeNode
* @return {object} Node object, if any.
*/
TreeNode.prototype.nextVisibleSiblingNode = function() {
var startingNode = this;
var context = (startingNode.hasParent() ? startingNode.getParent().children : tree.getNodes());
var i = findIndex(context, { id: startingNode.id });
return find(slice(context, i + 1), function(node) {
return node.visible();
});
};
/**
* Find the previous visible node.
*
* @category TreeNode
* @return {TreeNode} Node object, if any.
*/
TreeNode.prototype.previousVisibleNode = function() {
var startingNode = this;
var prev;
// 1. Any Siblings
prev = startingNode.previousVisibleSiblingNode();
// 2. If that sibling has children though, go there
if (prev && prev.hasChildren() && !prev.collapsed()) {
prev = findLast(prev.children, function(node) {
return node.visible();
});
}
// 3. Parent
if (!prev && startingNode.hasParent()) {
prev = startingNode.getParent();
}
return prev;
};
/**
* Find the previous visible sibling node.
*
* @category TreeNode
* @return {TreeNode} Node object, if any.
*/
TreeNode.prototype.previousVisibleSiblingNode = function() {
var context = (this.hasParent() ? this.getParent().children : tree.getNodes());
var i = findIndex(context, { id: this.id });
return findLast(slice(context, 0, i), function(node) {
return node.visible();
});
};
/**
* Iterate up a node and its parents.
*
* @category TreeNode
* @param {function} iteratee Iteratee function.
* @return {TreeNode} Resulting node.
*/
TreeNode.prototype.recurseUp = function(iteratee) {
var node = this;
node = iteratee(node);
if (!node) {
throw new TypeError('Invalid recurseUp return value. Did you forget "return"?');
}
if (node.hasParent()) {
node.getParent().recurseUp(iteratee);
}
return node;
};
/**
* Iterate down node and any children.
*
* @category TreeNode
* @param {function} iteratee Iteratee function.
* @return {TreeNode} Resulting node.
*/
TreeNode.prototype.recurseDown = function(iteratee) {
return tree.recurseDown(this, iteratee);
};
/**
* Remove a node from the tree.
*
* @category TreeNode
* @return {void}
*/
TreeNode.prototype.remove = function() {
var node = this;
var context = (node.parent ? node.parent.children : model);
remove(context, { id: node.id });
tree.emit('node.removed', node.export());
dom.applyChanges();
};
/**
* Get if node soft-removed.
*
* @category TreeNode
* @return {boolean} If soft-removed.
*/
TreeNode.prototype.removed = function() {
return this.itree.state.removed;
};
/**
* Restore state if soft-removed.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.restore = function() {
return baseStateChange('removed', false, 'restored', this);
};
/**
* Select this node.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.select = function() {
var node = this;
if (!node.selected() && node.selectable()) {
// Batch selection changes
dom.batch();
node.focus();
if (!tree.preventDeselection) {
tree.getNodes().deselectDeep();
}
node.itree.state.selected = true;
// Emit this event
tree.emit('node.selected', node);
// Mark hierarchy dirty and apply
node.markDirty();
dom.end();
}
return node;
};
/**
* Get if node selectable.
*
* @category TreeNode
* @return {boolean} If node selectable.
*/
TreeNode.prototype.selectable = function() {
var allow = tree.config.allowSelection(this);
return typeof allow === 'boolean' ? allow : this.itree.state.selectable;
};
/**
* Get if node selected.
*
* @category TreeNode
* @return {boolean} If selected.
*/
TreeNode.prototype.selected = function() {
return this.itree.state.selected;
};
/**
* Select this node.
*
* @category TreeNode
* @param {string|number} property Property name.
* @param {*} value New value.
* @return {TreeNode} Node object.
*/
TreeNode.prototype.set = function(property, value) {
this[property] = value;
this.markDirty();
return this;
};
/**
* Show this node.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.show = function() {
return baseStateChange('hidden', false, 'shown', this);
};
/**
* Mark this node as "removed" without actually removing it.
*
* Expand/show methods will never reveal this node until restored.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.softRemove = function() {
return baseStateChange('removed', true, 'softremoved', this);
};
/**
* Toggles collapsed state.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.toggleCollapse = function() {
return (this.collapsed() ? this.expand() : this.collapse());
};
/**
* Toggles collapsed state.
*
* @category TreeNode
* @return {TreeNode} Node object.
*/
TreeNode.prototype.toggleSelect = function() {
return (this.selected() ? this.deselect() : this.select());
};
/**
* Checks whether a node is visible to a user. Returns false
* if it's hidden, or if any ancestor is hidden or collapsed.
*
* @category TreeNode
* @param {object} node Node object.
* @return {boolean} Whether visible.
*/
TreeNode.prototype.visible = function() {
var node = this;
var isVisible = true;
if (node.hidden() || node.removed()) {
isVisible = false;
}
else if (node.hasParent()) {
if (node.getParent().collapsed()) {
isVisible = false;
}
else {
isVisible = node.getParent().visible();
}
}
else {
isVisible = true;
}
return isVisible;
};
/**
* An Array-like collection of TreeNodes.
*
* @category TreeNodes
* @param {array} array Array of TreeNode objects.
* @return {TreeNodes} Collection of TreeNode
*/
function TreeNodes(array) {
var treeNodes = this;
if (isArray(array)) {
each(array, function(node) {
treeNodes.push(node);
});
}
};
TreeNodes.prototype = Object.create(Array.prototype);
TreeNodes.prototype.constructor = TreeNodes;
/**
* Clones (deep) the array of nodes.
*
* @category TreeNodes
* @return {TreeNodes} Array of cloned nodes.
*/
TreeNodes.prototype.clone = function() {
var newArray = new TreeNodes();
each(this, function(node) {
newArray.push(node.clone());
});
return newArray;
};
/**
* Copies nodes to a new tree instance.
*
* @category TreeNodes
* @param {boolean} hierarchy Include necessary ancestors to match hierarchy.
* @return {void}
*/
TreeNodes.prototype.copy = function(hierarchy) {
var nodes = this;
return {
/**
* Sets a destination.
*
* @category CopyNode
* @param {object} dest Destination Inspire Tree.
* @return {array} Array of new nodes.
*/
to: function(dest) {
if (!isFunction(dest.addNodes)) {
throw new Error('Destination must be an Inspire Tree instance.');
}
var newNodes = new TreeNodes();
each((nodes || model), function(node) {
newNodes.push(node.copy(hierarchy).to(dest));
});
return newNodes;
}
};
};
/**
* Concat nodes like an Array would.
*
* @category TreeNodes
* @param {TreeNodes} nodes Array of nodes.
* @return {TreeNodes} Resulting node array.
*/
TreeNodes.prototype.concat = function(nodes) {
var newNodes = new TreeNodes();
var pusher = function(node) {
newNodes.push(node);
};
each(this, pusher);
each(nodes, pusher);
return newNodes;
};
/**
* Clones an array of node objects and removes any
* itree instance information/state.
*
* @category TreeNodes
* @return {TreeNodes} Cloned/modified node objects.
*/
TreeNodes.prototype.export = function() {
var nodeClones = this.clone();
tree.recurseDown(nodeClones, function(node) {
node.itree = null;
return node;
});
return nodeClones;
};
/**
* Flattens a hierarchy, returning only node(s) with the
* expected state, for operations which must exclude parents.
*
* @category TreeNodes
* @param {string} flag Which state flag to filter by.
* @return {TreeNodes} Flat array of matching nodes.
*/
TreeNodes.prototype.flatten = function(flag) {
var nodes = this;
var flat = new TreeNodes();
flag = flag || 'selected';
if (isArrayLike(nodes) && !isEmpty(nodes)) {
each(nodes, function(node) {
if (node.itree.state[flag]) {
flat.push(node);
}
if (node.hasChildren()) {
flat = flat.concat(node.children.flatten(flag));
}
});
}
return flat;
};
/**
* Returns a new TreeNodes array of available nodes.
*
* See README.md for terminology.
*
* @category TreeNodes
* @return {TreeNodes} Array of node objects.
*/
TreeNodes.prototype.getAvailableNodes = function() {
return this.reduce(function(node) {
return node.available();
});
};
/**
* Returns a new TreeNodes array of all available nodes
* at the deepest level (having no children).
*
* See README.md for terminology.
*
* @category TreeNodes
* @return {TreeNodes} Array of node objects.
*/
TreeNodes.prototype.getDeepestAvailableNodes = function() {
return this.reduceDeep(function(node) {
return (!node.hasChildren() && node.available());
});
};
/**
* Iterate down all nodes and any children.
*
* @category TreeNodes
* @param {function} iteratee Iteratee function.
* @return {TreeNodes} Resulting nodes.
*/
TreeNodes.prototype.recurseDown = function(iteratee) {
return tree.recurseDown(this, iteratee);
};
/**
* Get a subset of nodes based on how they match the predicate function.
*
* @category TreeNodes
* @param {function} predicate Predicate function.
* @return {TreeNodes} Array of matching node objects.
*/
TreeNodes.prototype.reduce = function(predicate) {
var reduced = new TreeNodes();
each(this, function(node) {
if (predicate(node)) {
reduced.push(node);
}
});
return reduced;
};
/**
* Get a subset of all descendant nodes based on how they match the predicate function.
*
* @category TreeNodes
* @param {function} predicate Predicate function.
* @return {TreeNodes} Array of matching node objects.
*/
TreeNodes.prototype.reduceDeep = function(predicate) {
var reduced = new TreeNodes();
this.recurseDown(function(node) {
if (predicate(node)) {
reduced.push(node);
}
return node;
});
return reduced;
};
/**
* Sorts all TreeNode objects in this collection.
*
* If no custom sorter given, the configured "sort" value will be used.
*
* @category TreeNodes
* @param {string|function} sorter Sort function or property name.
* @return {TreeNodes} Array of node obejcts.
*/
TreeNodes.prototype.sort = function(sorter) {
var nodes = this;
if (tree.config.sort && !sorter) {
sorter = tree.config.sort;
}
var sorted = sortBy(nodes, sorter);
nodes.length = 0;
each(sorted, function(node) {
nodes.push(node);
});
return nodes;
};
/**
* Map shallow to each TreeNode
*
* @private
* @param {string} method Method name.
* @return {void}
*/
function mapToEach(method) {
TreeNodes.prototype[method] = function() {
dom.batch();
each(this, function(node) {
node[method]();
});
dom.end();
return this;
};
}
/**
* Map deeply to all TreeNodes and children
*
* @private
* @param {string} method Method name.
* @return {void}
*/
function mapToEachDeeply(method) {
TreeNodes.prototype[method + 'Deep'] = function() {
dom.batch();
tree.recurseDown(this, function(node) {
node[method]();
return node;
});
dom.end();
return this;
};
}
// Methods can we map to each/deeply TreeNode
var mapped = ['blur', 'collapse', 'deselect', 'expand', 'hide', 'restore', 'show', 'softRemove'];
each(mapped, function(method) {
mapToEach(method);
mapToEachDeeply(method);
});
// Methods can we map to each TreeNode
each(['expandParents'], mapToEach);
/**
* Stores repetitive state change logic for most state methods.
*
* @private
* @param {string} prop State property name.
* @param {boolean} value New state value.
* @param {string} verb Verb used for events.
* @param {TreeNode} node Node object.
* @return {TreeNode} Node object.
*/
function baseStateChange(prop, value, verb, node) {
if (node.itree.state[prop] !== value) {
node.itree.state[prop] = value;
tree.emit('node.' + verb, node);
node.markDirty();
dom.applyChanges();
}
return node;
}
/**
* Parses a raw collection of objects into a model used
* within a tree. Adds state and other internal properties.
*
* @private
* @param {array|object} array Array of nodes
* @param {object} parent Pointer to parent object
* @return {array|object} Object model.
*/
function collectionToModel(array, parent) {
var collection = new TreeNodes();
// Sort
if (tree.config.sort) {
array = sortBy(array, tree.config.sort);
}
each(array, function(node) {
collection.push(objectToModel(node, parent));
});
return collection;
};
/**
* Merge a node into an existing context - a model
* or another node's children. If the ID exists
* the node is skipped and we try its children.
*
* @private
* @param {array} context Array of node objects.
* @param {object} node Node object.
* @return {array} Array of new nodes.
*/
var mergeNode = function(context, node) {
var newNodes = new TreeNodes();
if (node.id) {
// Does node already exist
var existing = tree.getNode(node.id);
if (existing) {
existing.restore();
existing.show();
// Ensure existing accepts children
if (!isArrayLike(existing.children)) {
existing.children = new TreeNodes();
}
each(node.children, function(child) {
newNodes.concat(mergeNode(existing, child));
});
}
else {
if (context instanceof TreeNode) {
node.itree.parent = context;
context.children.push(node);
}
else {
context.push(node);
}
node.markDirty();
newNodes.push(node);
}
}
return newNodes;
};
/**
* Parse a raw object into a model used within a tree.
*
* Note: Uses native js over lodash where performance
* benefits most, since this handles every node.
*
* @private
* @param {object} object Source object
* @param {object} parent Pointer to parent object.
* @return {object} Final object
*/
function objectToModel(object, parent) {
// Create or type-ensure ID
object.id = object.id || cuid();
if (typeof object.id !== 'string') {
object.id = object.id.toString();
}
// High-performance default assignments
var itree = object.itree = object.itree || {};
itree.icon = itree.icon || false;
var li = itree.li = itree.li || {};
li.attributes = li.attributes || {};
var state = itree.state = itree.state || {};
// Enabled by default
state.collapsed = typeof state.collapsed === 'boolean' ? state.collapsed : true;
state.selectable = typeof state.selectable === 'boolean' ? state.selectable : true;
// Disabled by default
state.focused = state.focused || false;
state.hidden = state.hidden || false;
state.loading = state.loading || false;
state.removed = state.removed || false;
state.selected = state.selected || false;
// Save parent, if any.
object.itree.parent = parent;
// Wrap
object = assign(new TreeNode(), object);
if (object.hasChildren()) {
object.children = collectionToModel(object.children, object);
}
return object;
};
var data = this;
var model = new TreeNodes();
/**
* Add a node.
*
* @category Tree
* @param {object} node Node object.
* @return {object} Node object.
*/
tree.addNode = function(node) {
node = objectToModel(node);
var newNodes = mergeNode(model, node);
if (newNodes.length) {
tree.emit('node.added', node);
}
node.markDirty();
dom.applyChanges();
return node;
};
/**
* Add nodes.
*
* @category Tree
* @param {array} nodes Array of node objects.
* @return {TreeNodes} Added node objects.
*/
tree.addNodes = function(nodes) {
dom.batch();
var newNodes = new TreeNodes();
each(nodes, function(node) {
newNodes.push(tree.addNode(node));
});
dom.end();
return newNodes;
};
/**
* Shows all nodes and collapses parents.
*
* @category Tree
* @return {void}
*/
tree.clearSearch = function() {
tree.getNodes().showDeep();
tree.getNodes().collapseDeep();
};
/**
* Get all available nodes.
*
* @category Tree
* @return {TreeNodes} Array of node objects.
*/
tree.getAvailableNodes = function() {
return model.getAvailableNodes();
};
/**
* Get all deepest available nodes.
*
* @category Tree
* @return {TreeNodes} Array of node objects.
*/
tree.getDeepestAvailableNodes = function() {
return model.getDeepestAvailableNodes();
};
/**
* Get a node.
*
* @category Tree
* @param {string|number} id ID of node.
* @param {TreeNodes} nodes Base collection to search in.
* @return {TreeNode} Node object.
*/
tree.getNode = function(id, nodes) {
var node;
if (!isString(id)) {
id = id.toString();
}
each((nodes || model), function(item) {
if (item.id === id) {
node = item;
}
if (!node && item.hasChildren()) {
node = tree.getNode(id, item.children);
}
if (node) {
return false;
}
});
return node;
};
/**
* Get all nodes in a tree, or nodes for an array of IDs.
*
* @category Tree
* @param {array} refs Array of ID references.
* @return {TreeNodes} Array of node objects.
* @example
*
* var all = tree.getNodes()
* var some = tree.getNodes([1, 2, 3])
*/
tree.getNodes = function(refs) {
var nodes = model;
if (isArray(refs)) {
var found = new TreeNodes();
each(refs, function(ref) {
var node = tree.getNode(ref);
if (node) {
found.push(node);
}
});
nodes = found;
}
return nodes;
};
/**
* Get the currently focused node, if any.
*
* @category Tree
* @return {TreeNode} Node object.
*/
tree.getFocusedNode = function() {
var node;
var focused = model.flatten('focused');
if (!isEmpty(focused)) {
node = focused[0];
}
return node;
};
/**
* Returns a flat array of selected nodes.
*
* @category Tree
* @param {TreeNodes} nodes Array of node objects to search within.
* @return {TreeNodes} Selected nodes.
*/
tree.getSelectedNodes = function(nodes) {
return (nodes || model).flatten('selected');
};
/**
* Loads tree. Accepts an array or a promise.
*
* @category Tree
* @param {array|function} loader Array of nodes, or promise resolving an array of nodes.
* @return {void}
* @example
*
* tree.load($.getJSON('nodes.json'));
*/
tree.load = function(loader) {
var resolve = function(nodes) {
// Emit raw data
tree.emit('data.loaded', nodes);
// Clear and call rendering on existing data
if (model.length > 0) {
tree.removeAll();
}
model = collectionToModel(nodes);
tree.emit('model.loaded', model);
dom.applyChanges();
};
var reject = function(err) {
tree.emit('data.loaderror', err);
throw err;
};
// Data given already as an array
if (isArrayLike(loader)) {
resolve(loader);
}
// Data loader requires a caller/callback
else if (isFunction(loader)) {
loader(null, resolve, reject);
}
// Data loader is likely a promise
else if (isObject(loader)) {
// Promise
if (isFunction(loader.then)) {
loader.then(resolve);
}
// jQuery promises use "error".
if (isFunction(loader.error)) {
loader.error(reject);
}
else if (isFunction(loader.catch)) {
loader.catch(reject);
}
}
else {
throw new Error('Invalid data loader.');
}
};
/**
* Iterate down node/children recursively.
*
* @category Tree
* @param {TreeNodes|TreeNode} collection Array of nodes or node object.
* @param {function} iteratee Iteratee function.
* @return {TreeNodes} Resulting node array.
*/
tree.recurseDown = function(collection, iteratee) {
// Recurse each element in this array
if (isArrayLike(collection)) {
each(collection, function(element, i) {
collection[i] = tree.recurseDown(element, iteratee);
});
}
else if (isObject(collection)) {
collection = iteratee(collection);
if (!collection) {
throw new Error('Iteratee returned invalid object. Did you forget "return"?');
}
// Recurse children
if (isArrayLike(collection.children) && !isEmpty(collection.children)) {
collection.children = tree.recurseDown(collection.children, iteratee);
}
}
return collection;
};
/**
* Removes all nodes.
*
* @category Tree
* @return {void}
*/
tree.removeAll = function() {
model = new TreeNodes();
dom.applyChanges();
};
/**
* Search nodes, showing only those that match and the necessary hierarchy.
*
* @category Tree
* @param {*} query Search string, RegExp, or function.
* @return {TreeNodes} Array of matching node objects.
*/
tree.search = function(query) {
var matches = new TreeNodes();
var custom = tree.config.search;
if (isFunction(custom)) {
return custom(
query,
function resolver(nodes) {
dom.batch();
tree.getNodes().hideDeep();
each(nodes, function(node) {
mergeNode(model, node);
});
dom.end();
},
function rejecter(err) {
tree.emit('tree.loaderror', err);
}
);
}
// Don't search if query empty
if (isString(query) && isEmpty(query)) {
return tree.clearSearch();
}
if (isString(query)) {
query = new RegExp(query, 'i');
}
var predicate;
if (isRegExp(query)) {
predicate = function(node) {
return query.test(node.text);
};
}
else {
predicate = query;
}
if (!isFunction(predicate)) {
throw new TypeError('Search predicate must be a string, RegExp, or function.');
}
dom.batch();
tree.recurseDown(model, function(node) {
var match = predicate(node);
var wasHidden = node.hidden();
node.itree.state.hidden = !match;
// If hidden state will change
if (wasHidden !== node.hidden()) {
node.markDirty();
}
if (match) {
matches.push(node);
node.expandParents();
}
return node;
});
dom.end();
return matches;
};
/**
* Select the first visible node at the root level.
*
* @category Tree
* @return {TreeNode} Selected node object.
*/
tree.selectFirstVisibleNode = function() {
var select;
each(model, function(node) {
if (!node.hidden()) {
node.select();
select = node;
return false;
}
});
return select;
};
/**
* Shows all nodes.
*
* @category Tree
* @return {void}
*/
tree.showAll = function() {
dom.batch();
tree.recurseDown(tree.getNodes(), function(node) {
return node.show();
});
dom.end();
};
// Connect to our target DOM element
dom.attach(tree.config.target);
// Load initial user data
data.load(tree.config.data);
return tree;
};
// Mixin EventEmitter
InspireTree.prototype = Object.create(EventEmitter.prototype);
module.exports = InspireTree;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.2.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseAssign = __webpack_require__(2),
createAssigner = __webpack_require__(8),
keys = __webpack_require__(4);
/**
* A specialized version of `_.assign` for customizing assigned values without
* support for argument juggling, multiple sources, and `this` binding `customizer`
* functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
*/
function assignWith(object, source, customizer) {
var index = -1,
props = keys(source),
length = props.length;
while (++index < length) {
var key = props[index],
value = object[key],
result = customizer(value, source[key], key, object, source);
if ((result === result ? (result !== value) : (value === value)) ||
(value === undefined && !(key in object))) {
object[key] = result;
}
}
return object;
}
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources overwrite property assignments of previous sources.
* If `customizer` is provided it is invoked to produce the assigned values.
* The `customizer` is bound to `thisArg` and invoked with five arguments:
* (objectValue, sourceValue, key, object, source).
*
* **Note:** This method mutates `object` and is based on
* [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign).
*
* @static
* @memberOf _
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
* // => { 'user': 'fred', 'age': 40 }
*
* // using a customizer callback
* var defaults = _.partialRight(_.assign, function(value, other) {
* return _.isUndefined(value) ? other : value;
* });
*
* defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
var assign = createAssigner(function(object, source, customizer) {
return customizer
? assignWith(object, source, customizer)
: baseAssign(object, source);
});
module.exports = assign;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.2.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCopy = __webpack_require__(3),
keys = __webpack_require__(4);
/**
* The base implementation of `_.assign` without support for argument juggling,
* multiple sources, and `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return source == null
? object
: baseCopy(source, keys(source), object);
}
module.exports = baseAssign;
/***/ },
/* 3 */
/***/ function(module, exports) {
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.1.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var getNative = __webpack_require__(5),
isArguments = __webpack_require__(6),
isArray = __webpack_require__(7);
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? undefined : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object != 'function' && isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = keys;
/***/ },
/* 5 */
/***/ function(module, exports) {
/**
* lodash 3.9.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
module.exports = getNative;
/***/ },
/* 6 */
/***/ function(module, exports) {
/**
* lodash 3.0.4 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return isObjectLike(value) && isArrayLike(value) &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
}
module.exports = isArguments;
/***/ },
/* 7 */
/***/ function(module, exports) {
/**
* lodash 3.0.4 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var arrayTag = '[object Array]',
funcTag = '[object Function]';
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
module.exports = isArray;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.1.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var bindCallback = __webpack_require__(9),
isIterateeCall = __webpack_require__(10),
restParam = __webpack_require__(11);
/**
* Creates a function that assigns properties of source object(s) to a given
* destination object.
*
* **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return restParam(function(object, sources) {
var index = -1,
length = object == null ? 0 : sources.length,
customizer = length > 2 ? sources[length - 2] : undefined,
guard = length > 2 ? sources[2] : undefined,
thisArg = length > 1 ? sources[length - 1] : undefined;
if (typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = typeof thisArg == 'function' ? thisArg : undefined;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
/***/ },
/* 9 */
/***/ function(module, exports) {
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (thisArg === undefined) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = bindCallback;
/***/ },
/* 10 */
/***/ function(module, exports) {
/**
* lodash 3.0.9 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isIterateeCall;
/***/ },
/* 11 */
/***/ function(module, exports) {
/**
* lodash 3.6.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseClone = __webpack_require__(13),
bindCallback = __webpack_require__(9);
/**
* Creates a deep clone of `value`. If `customizer` is provided it's invoked
* to produce the cloned values. If `customizer` returns `undefined` cloning
* is handled by the method instead. The `customizer` is bound to `thisArg`
* and invoked with up to three argument; (value [, index|key, object]).
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
* The enumerable properties of `arguments` objects and objects created by
* constructors other than `Object` are cloned to plain `Object` objects. An
* empty object is returned for uncloneable values such as functions, DOM nodes,
* Maps, Sets, and WeakMaps.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {*} Returns the deep cloned value.
* @example
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* var deep = _.cloneDeep(users);
* deep[0] === users[0];
* // => false
*
* // using a customizer callback
* var el = _.cloneDeep(document.body, function(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* });
*
* el === document.body
* // => false
* el.nodeName
* // => BODY
* el.childNodes.length;
* // => 20
*/
function cloneDeep(value, customizer, thisArg) {
return typeof customizer == 'function'
? baseClone(value, true, bindCallback(customizer, thisArg, 3))
: baseClone(value, true);
}
module.exports = cloneDeep;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* lodash 3.3.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var arrayCopy = __webpack_require__(14),
arrayEach = __webpack_require__(15),
baseAssign = __webpack_require__(2),
baseFor = __webpack_require__(16),
isArray = __webpack_require__(7),
keys = __webpack_require__(4);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
cloneableTags[dateTag] = cloneableTags[float32Tag] =
cloneableTags[float64Tag] = cloneableTags[int8Tag] =
cloneableTags[int16Tag] = cloneableTags[int32Tag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[stringTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[mapTag] = cloneableTags[setTag] =
cloneableTags[weakMapTag] = false;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Native method references. */
var ArrayBuffer = global.ArrayBuffer,
Uint8Array = global.Uint8Array;
/**
* The base implementation of `_.clone` without support for argument juggling
* and `this` binding `customizer` functions.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The object `value` belongs to.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates clones with source counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
var result;
if (customizer) {
result = object ? customizer(value, key, object) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return arrayCopy(value, result);
}
} else {
var tag = objToString.call(value),
isFunc = tag == funcTag;
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = initCloneObject(isFunc ? {} : value);
if (!isDeep) {
return baseAssign(result, value);
}
} else {
return cloneableTags[tag]
? initCloneByTag(value, tag, isDeep)
: (object ? value : {});
}
}
// Check for circular references and return its corresponding clone.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
// Add the source value to the stack of traversed objects and associate it with its clone.
stackA.push(value);
stackB.push(result);
// Recursively populate clone (susceptible to call stack limits).
(isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
});
return result;
}
/**
* The base implementation of `_.forOwn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return baseFor(object, iteratee, keys);
}
/**
* Creates a clone of the given array buffer.
*
* @private
* @param {ArrayBuffer} buffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function bufferClone(buffer) {
var result = new ArrayBuffer(buffer.byteLength),
view = new Uint8Array(result);
view.set(new Uint8Array(buffer));
return result;
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add array properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
var Ctor = object.constructor;
if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
Ctor = Object;
}
return new Ctor;
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return bufferClone(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
var buffer = object.buffer;
return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
var result = new Ctor(object.source, reFlags.exec(object));
result.lastIndex = object.lastIndex;
}
return result;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = baseClone;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 14 */
/***/ function(module, exports) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = arrayCopy;
/***/ },
/* 15 */
/***/ function(module, exports) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ },
/* 16 */
/***/ function(module, exports) {
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iteratee functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = baseFor;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/**
* cuid.js
* Collision-resistant UID generator for browsers and node.
* Sequential for fast db lookups and recency sorting.
* Safe for element IDs and server-side lookups.
*
* Extracted from CLCTR
*
* Copyright (c) Eric Elliott 2012
* MIT License
*/
/*global window, navigator, document, require, process, module */
(function (app) {
'use strict';
var namespace = 'cuid',
c = 0,
blockSize = 4,
base = 36,
discreteValues = Math.pow(base, blockSize),
pad = function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
},
randomBlock = function randomBlock() {
return pad((Math.random() *
discreteValues << 0)
.toString(base), blockSize);
},
safeCounter = function () {
c = (c < discreteValues) ? c : 0;
c++; // this is not subliminal
return c - 1;
},
api = function cuid() {
// Starting with a lowercase letter makes
// it HTML element ID friendly.
var letter = 'c', // hard-coded allows for sequential access
// timestamp
// warning: this exposes the exact date and time
// that the uid was created.
timestamp = (new Date().getTime()).toString(base),
// Prevent same-machine collisions.
counter,
// A few chars to generate distinct ids for different
// clients (so different computers are far less
// likely to generate the same id)
fingerprint = api.fingerprint(),
// Grab some more chars from Math.random()
random = randomBlock() + randomBlock();
counter = pad(safeCounter().toString(base), blockSize);
return (letter + timestamp + counter + fingerprint + random);
};
api.slug = function slug() {
var date = new Date().getTime().toString(36),
counter,
print = api.fingerprint().slice(0,1) +
api.fingerprint().slice(-1),
random = randomBlock().slice(-2);
counter = safeCounter().toString(36).slice(-4);
return date.slice(-2) +
counter + print + random;
};
api.globalCount = function globalCount() {
// We want to cache the results of this
var cache = (function calc() {
var i,
count = 0;
for (i in window) {
count++;
}
return count;
}());
api.globalCount = function () { return cache; };
return cache;
};
api.fingerprint = function browserPrint() {
return pad((navigator.mimeTypes.length +
navigator.userAgent.length).toString(36) +
api.globalCount().toString(36), 4);
};
// don't change anything from here down.
if (app.register) {
app.register(namespace, api);
} else if (true) {
module.exports = api;
} else {
app[namespace] = api;
}
}(this.applitude || this));
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.10.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var merge = __webpack_require__(19),
restParam = __webpack_require__(11);
/**
* Creates a `_.defaults` or `_.defaultsDeep` function.
*
* @private
* @param {Function} assigner The function to assign values.
* @param {Function} customizer The function to customize assigned values.
* @returns {Function} Returns the new defaults function.
*/
function createDefaults(assigner, customizer) {
return restParam(function(args) {
var object = args[0];
if (object == null) {
return object;
}
args.push(customizer);
return assigner.apply(undefined, args);
});
}
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use.
*
* @private
* @param {*} objectValue The destination object property value.
* @param {*} sourceValue The source object property value.
* @returns {*} Returns the value to assign to the destination object.
*/
function mergeDefaults(objectValue, sourceValue) {
return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
}
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
* // => { 'user': { 'name': 'barney', 'age': 36 } }
*
*/
var defaultsDeep = createDefaults(merge, mergeDefaults);
module.exports = defaultsDeep;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.3.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var arrayCopy = __webpack_require__(14),
arrayEach = __webpack_require__(15),
createAssigner = __webpack_require__(8),
isArguments = __webpack_require__(6),
isArray = __webpack_require__(7),
isPlainObject = __webpack_require__(20),
isTypedArray = __webpack_require__(22),
keys = __webpack_require__(4),
toPlainObject = __webpack_require__(23);
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.merge` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns `object`.
*/
function baseMerge(object, source, customizer, stackA, stackB) {
if (!isObject(object)) {
return object;
}
var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
props = isSrcArr ? undefined : keys(source);
arrayEach(props || source, function(srcValue, key) {
if (props) {
key = srcValue;
srcValue = source[key];
}
if (isObjectLike(srcValue)) {
stackA || (stackA = []);
stackB || (stackB = []);
baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
}
else {
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
}
if ((result !== undefined || (isSrcArr && !(key in object))) &&
(isCommon || (result === result ? (result !== value) : (value === value)))) {
object[key] = result;
}
}
});
return object;
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
var length = stackA.length,
srcValue = source[key];
while (length--) {
if (stackA[length] == srcValue) {
object[key] = stackB[length];
return;
}
}
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
result = isArray(value)
? value
: (isArrayLike(value) ? arrayCopy(value) : []);
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
result = isArguments(value)
? toPlainObject(value)
: (isPlainObject(value) ? value : {});
}
else {
isCommon = false;
}
}
// Add the source value to the stack of traversed objects and associate
// it with its merged value.
stackA.push(srcValue);
stackB.push(result);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
} else if (result === result ? (result !== value) : (value === value)) {
object[key] = result;
}
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* overwrite property assignments of previous sources. If `customizer` is
* provided it is invoked to produce the merged values of the destination and
* source properties. If `customizer` returns `undefined` merging is handled
* by the method instead. The `customizer` is bound to `thisArg` and invoked
* with five arguments: (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*
* // using a customizer callback
* var object = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var other = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(object, other, function(a, b) {
* if (_.isArray(a)) {
* return a.concat(b);
* }
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
*/
var merge = createAssigner(baseMerge);
module.exports = merge;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.2.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseFor = __webpack_require__(16),
isArguments = __webpack_require__(6),
keysIn = __webpack_require__(21);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* The base implementation of `_.forIn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
return baseFor(object, iteratee, keysIn);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* **Note:** This method assumes objects created by the `Object` constructor
* have no inherited enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
var Ctor;
// Exit early for non `Object` objects.
if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
(!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
var result;
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
baseForIn(value, function(subValue, key) {
result = key;
});
return result === undefined || hasOwnProperty.call(value, result);
}
module.exports = isPlainObject;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.8 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var isArguments = __webpack_require__(6),
isArray = __webpack_require__(7);
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = keysIn;
/***/ },
/* 22 */
/***/ function(module, exports) {
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
module.exports = isTypedArray;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCopy = __webpack_require__(3),
keysIn = __webpack_require__(21);
/**
* Converts `value` to a plain object flattening inherited enumerable
* properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return baseCopy(value, keysIn(value));
}
module.exports = toPlainObject;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var arrayEach = __webpack_require__(15),
baseEach = __webpack_require__(25),
bindCallback = __webpack_require__(9),
isArray = __webpack_require__(7);
/**
* Creates a function for `_.forEach` or `_.forEachRight`.
*
* @private
* @param {Function} arrayFunc The function to iterate over an array.
* @param {Function} eachFunc The function to iterate over a collection.
* @returns {Function} Returns the new each function.
*/
function createForEach(arrayFunc, eachFunc) {
return function(collection, iteratee, thisArg) {
return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
? arrayFunc(collection, iteratee)
: eachFunc(collection, bindCallback(iteratee, thisArg, 3));
};
}
/**
* Iterates over elements of `collection` invoking `iteratee` for each element.
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection). Iteratee functions may exit iteration early
* by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length" property
* are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
* may be used for object iteration.
*
* @static
* @memberOf _
* @alias each
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2]).forEach(function(n) {
* console.log(n);
* }).value();
* // => logs each value from left to right and returns the array
*
* _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
* console.log(n, key);
* });
* // => logs each value-key pair and returns the object (iteration order is not guaranteed)
*/
var forEach = createForEach(arrayEach, baseEach);
module.exports = forEach;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.4 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var keys = __webpack_require__(4);
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.forEach` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iteratee functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* The base implementation of `_.forOwn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
var length = collection ? getLength(collection) : 0;
if (!isLength(length)) {
return eachFunc(collection, iteratee);
}
var index = fromRight ? length : -1,
iterable = toObject(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = baseEach;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
* EventEmitter2
* https://github.com/hij1nx/EventEmitter2
*
* Copyright (c) 2013 hij1nx
* Licensed under the MIT license.
*/
;!function(undefined) {
var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
var defaultMaxListeners = 10;
function init() {
this._events = {};
if (this._conf) {
configure.call(this, this._conf);
}
}
function configure(conf) {
if (conf) {
this._conf = conf;
conf.delimiter && (this.delimiter = conf.delimiter);
conf.maxListeners && (this._events.maxListeners = conf.maxListeners);
conf.wildcard && (this.wildcard = conf.wildcard);
conf.newListener && (this.newListener = conf.newListener);
if (this.wildcard) {
this.listenerTree = {};
}
}
}
function EventEmitter(conf) {
this._events = {};
this.newListener = false;
configure.call(this, conf);
}
//
// Attention, function return type now is array, always !
// It has zero elements if no any matches found and one or more
// elements (leafs) if there are matches
//
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
typeLength = type.length, currentType = type[i], nextType = type[i+1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
handlers && handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
handlers && handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
}
}
return listeners;
} else if(currentType === '**') {
endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
if(endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if(branch === '*' || branch === '**') {
if(tree[branch]._listeners && !endReached) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
} else if(branch === nextType) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i+1);
}
xxTree = tree['**'];
if(xxTree) {
if(i < typeLength) {
if(xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for(branch in xxTree) {
if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if(branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i+2);
} else if(branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i+1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
}
}
}
} else if(xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if(xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
function growListenerTree(type, listener) {
type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
//
// Looks for two consecutive '**', if so, don't add the event at all.
//
for(var i = 0, len = type.length; i+1 < len; i++) {
if(type[i] === '**' && type[i+1] === '**') {
return;
}
}
var tree = this.listenerTree;
var name = type.shift();
while (name) {
if (!tree[name]) {
tree[name] = {};
}
tree = tree[name];
if (type.length === 0) {
if (!tree._listeners) {
tree._listeners = listener;
}
else if(typeof tree._listeners === 'function') {
tree._listeners = [tree._listeners, listener];
}
else if (isArray(tree._listeners)) {
tree._listeners.push(listener);
if (!tree._listeners.warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && tree._listeners.length > m) {
tree._listeners.warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
tree._listeners.length);
console.trace();
}
}
}
return true;
}
name = type.shift();
}
return true;
}
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.delimiter = '.';
EventEmitter.prototype.setMaxListeners = function(n) {
this._events || init.call(this);
this._events.maxListeners = n;
if (!this._conf) this._conf = {};
this._conf.maxListeners = n;
};
EventEmitter.prototype.event = '';
EventEmitter.prototype.once = function(event, fn) {
this.many(event, 1, fn);
return this;
};
EventEmitter.prototype.many = function(event, ttl, fn) {
var self = this;
if (typeof fn !== 'function') {
throw new Error('many only accepts instances of Function');
}
function listener() {
if (--ttl === 0) {
self.off(event, listener);
}
fn.apply(this, arguments);
}
listener._origin = fn;
this.on(event, listener);
return self;
};
EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if (type === 'newListener' && !this.newListener) {
if (!this._events.newListener) { return false; }
}
// Loop through the *_all* functions and invoke them.
if (this._all) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
for (i = 0, l = this._all.length; i < l; i++) {
this.event = type;
this._all[i].apply(this, args);
}
}
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._all &&
!this._events.error &&
!(this.wildcard && this.listenerTree.error)) {
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
var handler;
if(this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
}
else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
if (arguments.length === 1) {
handler.call(this);
}
else if (arguments.length > 1)
switch (arguments.length) {
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
handler.apply(this, args);
}
return true;
}
else if (handler) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
this.event = type;
listeners[i].apply(this, args);
}
return (listeners.length > 0) || !!this._all;
}
else {
return !!this._all;
}
};
EventEmitter.prototype.on = function(type, listener) {
if (typeof type === 'function') {
this.onAny(type);
return this;
}
if (typeof listener !== 'function') {
throw new Error('on only accepts instances of Function');
}
this._events || init.call(this);
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if(this.wildcard) {
growListenerTree.call(this, type, listener);
return this;
}
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
}
else if(typeof this._events[type] === 'function') {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
else if (isArray(this._events[type])) {
// If we've already got an array, just append.
this._events[type].push(listener);
// Check for listener leak
if (!this._events[type].warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.onAny = function(fn) {
if (typeof fn !== 'function') {
throw new Error('onAny only accepts instances of Function');
}
if(!this._all) {
this._all = [];
}
// Add the function to the event listener collection.
this._all.push(fn);
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function(type, listener) {
if (typeof listener !== 'function') {
throw new Error('removeListener only takes instances of Function');
}
var handlers,leafs=[];
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
}
else {
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events[type]) return this;
handlers = this._events[type];
leafs.push({_listeners:handlers});
}
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
handlers = leaf._listeners;
if (isArray(handlers)) {
var position = -1;
for (var i = 0, length = handlers.length; i < length; i++) {
if (handlers[i] === listener ||
(handlers[i].listener && handlers[i].listener === listener) ||
(handlers[i]._origin && handlers[i]._origin === listener)) {
position = i;
break;
}
}
if (position < 0) {
continue;
}
if(this.wildcard) {
leaf._listeners.splice(position, 1);
}
else {
this._events[type].splice(position, 1);
}
if (handlers.length === 0) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
return this;
}
else if (handlers === listener ||
(handlers.listener && handlers.listener === listener) ||
(handlers._origin && handlers._origin === listener)) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
return this;
};
EventEmitter.prototype.offAny = function(fn) {
var i = 0, l = 0, fns;
if (fn && this._all && this._all.length > 0) {
fns = this._all;
for(i = 0, l = fns.length; i < l; i++) {
if(fn === fns[i]) {
fns.splice(i, 1);
return this;
}
}
} else {
this._all = [];
}
return this;
};
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
!this._events || init.call(this);
return this;
}
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
leaf._listeners = null;
}
}
else {
if (!this._events[type]) return this;
this._events[type] = null;
}
return this;
};
EventEmitter.prototype.listeners = function(type) {
if(this.wildcard) {
var handlers = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
return handlers;
}
this._events || init.call(this);
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
EventEmitter.prototype.listenersAny = function() {
if(this._all) {
return this._all;
}
else {
return [];
}
};
if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
return EventEmitter;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports === 'object') {
// CommonJS
exports.EventEmitter2 = EventEmitter;
}
else {
// Browser global.
window.EventEmitter2 = EventEmitter;
}
}();
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.2.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCallback = __webpack_require__(28),
baseEach = __webpack_require__(25),
baseFind = __webpack_require__(31),
baseFindIndex = __webpack_require__(32),
isArray = __webpack_require__(7);
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new find function.
*/
function createFind(eachFunc, fromRight) {
return function(collection, predicate, thisArg) {
predicate = baseCallback(predicate, thisArg, 3);
if (isArray(collection)) {
var index = baseFindIndex(collection, predicate, fromRight);
return index > -1 ? collection[index] : undefined;
}
return baseFind(collection, predicate, eachFunc);
};
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
* invoked with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias detect
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.result(_.find(users, function(chr) {
* return chr.age < 40;
* }), 'user');
* // => 'barney'
*
* // using the `_.matches` callback shorthand
* _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
* // => 'pebbles'
*
* // using the `_.matchesProperty` callback shorthand
* _.result(_.find(users, 'active', false), 'user');
* // => 'fred'
*
* // using the `_.property` callback shorthand
* _.result(_.find(users, 'active'), 'user');
* // => 'barney'
*/
var find = createFind(baseEach);
module.exports = find;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.3.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseIsEqual = __webpack_require__(29),
bindCallback = __webpack_require__(9),
isArray = __webpack_require__(7),
pairs = __webpack_require__(30);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `value` to a string if it's not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
return value == null ? '' : (value + '');
}
/**
* The base implementation of `_.callback` which supports specifying the
* number of arguments to provide to `func`.
*
* @private
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function baseCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function') {
return thisArg === undefined
? func
: bindCallback(func, thisArg, argCount);
}
if (func == null) {
return identity;
}
if (type == 'object') {
return baseMatches(func);
}
return thisArg === undefined
? property(func)
: baseMatchesProperty(func, thisArg);
}
/**
* The base implementation of `get` without support for string paths
* and default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path of the property to get.
* @param {string} [pathKey] The key representation of path.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path, pathKey) {
if (object == null) {
return;
}
if (pathKey !== undefined && pathKey in toObject(object)) {
path = [pathKey];
}
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[path[index++]];
}
return (index && index == length) ? object : undefined;
}
/**
* The base implementation of `_.isMatch` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} matchData The propery names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparing objects.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = toObject(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var result = customizer ? customizer(objValue, srcValue, key) : undefined;
if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
return false;
}
}
}
return true;
}
/**
* The base implementation of `_.matches` which does not clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
var key = matchData[0][0],
value = matchData[0][1];
return function(object) {
if (object == null) {
return false;
}
return object[key] === value && (value !== undefined || (key in toObject(object)));
};
}
return function(object) {
return baseIsMatch(object, matchData);
};
}
/**
* The base implementation of `_.matchesProperty` which does not clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to compare.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(path, srcValue) {
var isArr = isArray(path),
isCommon = isKey(path) && isStrictComparable(srcValue),
pathKey = (path + '');
path = toPath(path);
return function(object) {
if (object == null) {
return false;
}
var key = pathKey;
object = toObject(object);
if ((isArr || !isCommon) && !(key in object)) {
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
if (object == null) {
return false;
}
key = last(path);
object = toObject(object);
}
return object[key] === srcValue
? (srcValue !== undefined || (key in object))
: baseIsEqual(srcValue, object[key], undefined, true);
};
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
*/
function basePropertyDeep(path) {
var pathKey = (path + '');
path = toPath(path);
return function(object) {
return baseGet(object, path, pathKey);
};
}
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : (+end || 0);
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* Gets the propery names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = pairs(object),
length = result.length;
while (length--) {
result[length][2] = isStrictComparable(result[length][1]);
}
return result;
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
var type = typeof value;
if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
return true;
}
if (isArray(value)) {
return false;
}
var result = !reIsDeepProp.test(value);
return result || (object != null && value in toObject(object));
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/**
* Converts `value` to property path array if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Array} Returns the property path array.
*/
function toPath(value) {
if (isArray(value)) {
return value;
}
var result = [];
baseToString(value).replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array ? array.length : 0;
return length ? array[length - 1] : undefined;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function that returns the property value at `path` on a
* given object.
*
* @static
* @memberOf _
* @category Utility
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
* @example
*
* var objects = [
* { 'a': { 'b': { 'c': 2 } } },
* { 'a': { 'b': { 'c': 1 } } }
* ];
*
* _.map(objects, _.property('a.b.c'));
* // => [2, 1]
*
* _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
}
module.exports = baseCallback;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.7 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var isArray = __webpack_require__(7),
isTypedArray = __webpack_require__(22),
keys = __webpack_require__(4);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* A specialized version of `_.some` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* The base implementation of `_.isEqual` without support for `this` binding
* `customizer` functions.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing objects.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `value` objects.
* @param {Array} [stackB=[]] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = objToString.call(object);
if (objTag == argsTag) {
objTag = objectTag;
} else if (objTag != objectTag) {
objIsArr = isTypedArray(object);
}
}
if (!othIsArr) {
othTag = objToString.call(other);
if (othTag == argsTag) {
othTag = objectTag;
} else if (othTag != objectTag) {
othIsArr = isTypedArray(other);
}
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
return equalByTag(object, other, objTag);
}
if (!isLoose) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
}
}
if (!isSameTag) {
return false;
}
// Assume cyclic values are equal.
// For more information on detecting circular references see https://es5.github.io/#JO.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == object) {
return stackB[length] == other;
}
}
// Add `object` and `other` to the stack of traversed objects.
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing arrays.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
var index = -1,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
return false;
}
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index],
result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
if (result !== undefined) {
if (result) {
continue;
}
return false;
}
// Recursively compare arrays (susceptible to call stack limits).
if (isLoose) {
if (!arraySome(other, function(othValue) {
return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
})) {
return false;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
return false;
}
}
return true;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} value The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
// Coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
return +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object)
? other != +other
: object == +other;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings primitives and string
// objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
return object == (other + '');
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
var objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isLoose) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
var skipCtor = isLoose;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key],
result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
// Recursively compare objects (susceptible to call stack limits).
if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
return false;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (!skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
return false;
}
}
return true;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = baseIsEqual;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var keys = __webpack_require__(4);
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Creates a two dimensional array of the key-value pairs for `object`,
* e.g. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the new array of key-value pairs.
* @example
*
* _.pairs({ 'barney': 36, 'fred': 40 });
* // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
*/
function pairs(object) {
object = toObject(object);
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
var key = props[index];
result[index] = [key, object[key]];
}
return result;
}
module.exports = pairs;
/***/ },
/* 31 */
/***/ function(module, exports) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
* without support for callback shorthands and `this` binding, which iterates
* over `collection` using the provided `eachFunc`.
*
* @private
* @param {Array|Object|string} collection The collection to search.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @param {boolean} [retKey] Specify returning the key of the found element
* instead of the element itself.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFind(collection, predicate, eachFunc, retKey) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = retKey ? key : value;
return false;
}
});
return result;
}
module.exports = baseFind;
/***/ },
/* 32 */
/***/ function(module, exports) {
/**
* lodash 3.6.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to search.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.2.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCallback = __webpack_require__(28),
baseFindIndex = __webpack_require__(32);
/**
* Creates a `_.findIndex` or `_.findLastIndex` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new find function.
*/
function createFindIndex(fromRight) {
return function(array, predicate, thisArg) {
if (!(array && array.length)) {
return -1;
}
predicate = baseCallback(predicate, thisArg, 3);
return baseFindIndex(array, predicate, fromRight);
};
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(chr) {
* return chr.user == 'barney';
* });
* // => 0
*
* // using the `_.matches` callback shorthand
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // using the `_.matchesProperty` callback shorthand
* _.findIndex(users, 'active', false);
* // => 0
*
* // using the `_.property` callback shorthand
* _.findIndex(users, 'active');
* // => 2
*/
var findIndex = createFindIndex();
module.exports = findIndex;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.2.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCallback = __webpack_require__(28),
baseEachRight = __webpack_require__(35),
baseFind = __webpack_require__(31),
baseFindIndex = __webpack_require__(32),
isArray = __webpack_require__(7);
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new find function.
*/
function createFind(eachFunc, fromRight) {
return function(collection, predicate, thisArg) {
predicate = baseCallback(predicate, thisArg, 3);
if (isArray(collection)) {
var index = baseFindIndex(collection, predicate, fromRight);
return index > -1 ? collection[index] : undefined;
}
return baseFind(collection, predicate, eachFunc);
};
}
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(baseEachRight, true);
module.exports = findLast;
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseForRight = __webpack_require__(36),
keys = __webpack_require__(4);
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.forEachRight` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEachRight = createBaseEach(baseForOwnRight, true);
/**
* The base implementation of `_.forOwnRight` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
var length = collection ? getLength(collection) : 0;
if (!isLength(length)) {
return eachFunc(collection, iteratee);
}
var index = fromRight ? length : -1,
iterable = toObject(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = baseEachRight;
/***/ },
/* 36 */
/***/ function(module, exports) {
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseForRight = createBaseFor(true);
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = baseForRight;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isArray = __webpack_require__(7);
module.exports = function isArrayLike(array) {
return Boolean(isArray(array) || (
array &&
typeof array !== 'function' &&
typeof array !== 'string' &&
typeof array.length === 'number'));
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.4 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var isArguments = __webpack_require__(6),
isArray = __webpack_require__(7),
isFunction = __webpack_require__(39),
isString = __webpack_require__(40),
keys = __webpack_require__(4);
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is empty. A value is considered empty unless it is an
* `arguments` object, array, string, or jQuery-like collection with a length
* greater than `0` or an object with own enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
(isObjectLike(value) && isFunction(value.splice)))) {
return !value.length;
}
return !keys(value).length;
}
module.exports = isEmpty;
/***/ },
/* 39 */
/***/ function(module, exports) {
/**
* lodash 3.0.6 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isFunction;
/***/ },
/* 40 */
/***/ function(module, exports) {
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
}
module.exports = isString;
/***/ },
/* 41 */
/***/ function(module, exports) {
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ },
/* 42 */
/***/ function(module, exports) {
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var regexpTag = '[object RegExp]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
function isRegExp(value) {
return isObject(value) && objToString.call(value) == regexpTag;
}
module.exports = isRegExp;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.1.4 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var arrayMap = __webpack_require__(44),
baseCallback = __webpack_require__(28),
baseEach = __webpack_require__(25),
isArray = __webpack_require__(7);
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.map` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Creates an array of values by running each element in `collection` through
* `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
* arguments: (value, index|key, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
* `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
* `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
* `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
* `sum`, `uniq`, and `words`
*
* @static
* @memberOf _
* @alias collect
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new mapped array.
* @example
*
* function timesThree(n) {
* return n * 3;
* }
*
* _.map([1, 2], timesThree);
* // => [3, 6]
*
* _.map({ 'a': 1, 'b': 2 }, timesThree);
* // => [3, 6] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // using the `_.property` callback shorthand
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee, thisArg) {
var func = isArray(collection) ? arrayMap : baseMap;
iteratee = baseCallback(iteratee, thisArg, 3);
return func(collection, iteratee);
}
module.exports = map;
/***/ },
/* 44 */
/***/ function(module, exports) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* A specialized version of `_.map` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.1.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCallback = __webpack_require__(28),
basePullAt = __webpack_require__(46);
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is bound to
* `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** Unlike `_.filter`, this method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate, thisArg) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = baseCallback(predicate, thisArg, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
module.exports = remove;
/***/ },
/* 46 */
/***/ function(module, exports) {
/**
* lodash 3.8.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/** Used for native method references. */
var arrayProto = Array.prototype;
/** Native method references. */
var splice = arrayProto.splice;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.pullAt` without support for individual
* index arguments and capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/
function basePullAt(array, indexes) {
var length = array ? indexes.length : 0;
while (length--) {
var index = indexes[length];
if (index != previous && isIndex(index)) {
var previous = index;
splice.call(array, index, 1);
}
}
return array;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = basePullAt;
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseSlice = __webpack_require__(48),
isIterateeCall = __webpack_require__(10);
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This function is used instead of `Array#slice` to support node
* lists in IE < 9 and to ensure dense arrays are returned.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function slice(array, start, end) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
return baseSlice(array, start, end);
}
module.exports = slice;
/***/ },
/* 48 */
/***/ function(module, exports) {
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : (+end || 0);
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 3.1.5 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCallback = __webpack_require__(28),
baseCompareAscending = __webpack_require__(50),
baseEach = __webpack_require__(25),
baseSortBy = __webpack_require__(51),
isIterateeCall = __webpack_require__(10);
/**
* Used by `_.sortBy` to compare transformed elements of a collection and stable
* sort them in ascending order.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareAscending(object, other) {
return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
}
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.map` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection through `iteratee`. This method performs
* a stable sort, that is, it preserves the original sort order of equal elements.
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new sorted array.
* @example
*
* _.sortBy([1, 2, 3], function(n) {
* return Math.sin(n);
* });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(n) {
* return this.sin(n);
* }, Math);
* // => [3, 1, 2]
*
* var users = [
* { 'user': 'fred' },
* { 'user': 'pebbles' },
* { 'user': 'barney' }
* ];
*
* // using the `_.property` callback shorthand
* _.pluck(_.sortBy(users, 'user'), 'user');
* // => ['barney', 'fred', 'pebbles']
*/
function sortBy(collection, iteratee, thisArg) {
if (collection == null) {
return [];
}
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = undefined;
}
var index = -1;
iteratee = baseCallback(iteratee, thisArg, 3);
var result = baseMap(collection, function(value, key, collection) {
return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
});
return baseSortBy(result, compareAscending);
}
module.exports = sortBy;
/***/ },
/* 50 */
/***/ function(module, exports) {
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `compareAscending` which compares values and
* sorts them in ascending order without guaranteeing a stable sort.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function baseCompareAscending(value, other) {
if (value !== other) {
var valIsNull = value === null,
valIsUndef = value === undefined,
valIsReflexive = value === value;
var othIsNull = other === null,
othIsUndef = other === undefined,
othIsReflexive = other === other;
if ((value > other && !othIsNull) || !valIsReflexive ||
(valIsNull && !othIsUndef && othIsReflexive) ||
(valIsUndef && othIsReflexive)) {
return 1;
}
if ((value < other && !valIsNull) || !othIsReflexive ||
(othIsNull && !valIsUndef && valIsReflexive) ||
(othIsUndef && valIsReflexive)) {
return -1;
}
}
return 0;
}
module.exports = baseCompareAscending;
/***/ },
/* 51 */
/***/ function(module, exports) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.sortBy` and `_.sortByAll` which uses `comparer`
* to define the sort order of `array` and replaces criteria objects with their
* corresponding values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
module.exports = baseSortBy;
/***/ },
/* 52 */
/***/ function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }
/******/ ])
});
; |
/*!
* Microbe JavaScript Library v0.4.13
* http://m.icro.be
*
* Copyright 2014-2015 Sociomantic Labs and other contributors
* Released under the MIT license
* http://m.icro.be/license
*
* Date: Sat Nov 28 2015
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.µ=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* ## Microbe
*
* Builds the Microbe object
*
* @author Mouse Braun <mouse@knoblau.ch>
* @author Nicolas Brugneaux <nicolas.brugneaux@gmail.com>
*
* @package Microbe
*/
/*jshint globalstrict: true*/
'use strict';
var _type = '[object Microbe]';
var _version = '0.4.13-selectorEngine';
var Microbe = function( selector, scope, elements )
{
return new Microbe.core.__init__( selector, scope, elements );
};
require( './selectorEngine/init' )( Microbe, _type );
Microbe.version = Microbe.core.__init__.prototype.version = _version;
module.exports = Microbe.core.constructor = Microbe;
},{"./selectorEngine/init":4}],2:[function(require,module,exports){
/**
* array.js
*
* methods based on the array prototype
*
* @author Mouse Braun <mouse@knoblau.ch>
* @author Nicolas Brugneaux <nicolas.brugneaux@gmail.com>
*
* @package Microbe
*/
/*jshint globalstrict: true*/
'use strict';
module.exports = function( Microbe )
{
Microbe.core.every = Array.prototype.every;
Microbe.core.findIndex = Array.prototype.findIndex;
Microbe.core.each = Array.prototype.forEach;
Microbe.core.forEach = Array.prototype.forEach;
Microbe.core.includes = Array.prototype.includes;
Microbe.core.indexOf = Array.prototype.indexOf;
Microbe.core.lastIndexOf = Array.prototype.lastIndexOf;
Microbe.core.map = Array.prototype.map;
Microbe.core.pop = Array.prototype.pop;
Microbe.core.push = Array.prototype.push;
Microbe.core.reverse = Array.prototype.reverse;
Microbe.core.shift = Array.prototype.shift;
Microbe.core.slice = Array.prototype.slice;
Microbe.core.some = Array.prototype.some;
Microbe.core.sort = Array.prototype.sort;
Microbe.core.unshift = Array.prototype.unshift;
/*
* needed to be modified slightly to output a microbe
*/
Microbe.core.splice = function( start, deleteCount )
{
return this.constructor( Array.prototype.splice.call( this, start, deleteCount ) );
};
};
},{}],3:[function(require,module,exports){
/**
* pseudo.js
*
* @author Mouse Braun <mouse@knoblau.ch>
* @author Nicolas Brugneaux <nicolas.brugneaux@gmail.com>
*
* @package Microbe
*/
var _cleanArray = function( _r ){ return !!( _r ); };
module.exports = function( Microbe )
{
'use strict';
/**
* ## children
*
* Gets a microbe of all the given element's children
*
* @param {String} selector css selector string filter
*
* @example µ( '.example' ).children();
* @example µ( '.example' ).children( 'div' );
*
* @return _Array_ array of microbes (value)
*/
Microbe.core.children = function( selector )
{
var _constructor = this.constructor;
var _children = function( _el )
{
_el = _constructor( _el.children );
if ( typeof selector === 'string' )
{
return _el.filter( selector );
}
return _el;
};
return this.map( _children );
};
/**
* ## childrenFlat
*
* Gets an microbe of all children of all element's given
*
* @param {String} selector css selector string filter
*
* @example µ( '.example' ).childrenFlat();
* @example µ( '.example' ).childrenFlat( 'div' );
*
* @return _Microbe_ value array of combined children
*/
Microbe.core.childrenFlat = function( selector )
{
var i = 0, childrenArray = [];
var _childrenFlat = function( _el )
{
var arr = _el.children;
var arrLength = arr.length;
for ( var j = 0; j < arrLength; j++ )
{
childrenArray[ i ] = arr[ j ];
i++;
}
};
this.each( _childrenFlat );
var _el = this.constructor( childrenArray );
if ( typeof selector === 'string' )
{
return _el.filter( selector );
}
return _el;
};
/**
* ## filter
*
* Filters the microbe by the given given selector or function. In the case
* of a function, the element is passed as this. The inclusion on an element
* into the set is based on the return of the function
*
* @param {Mixed} selector selector or function to filter by
*
* @example µ( '.example' ).filter( 'div' );
* @example µ( '.example' ).filter( function( _el ){ return _el.tagName === 'div'; } );
*
* @return _Microbe_ new microbe containing only the filtered values
*/
Microbe.core.filter = function( filter )
{
var pseudo, filters, self = this, _el, method;
if ( this.length === 0 )
{
return this;
}
if ( typeof filter === 'function' )
{
var res = [];
for ( var i = 0, lenI = this.length; i < lenI; i++ )
{
res[ i ] = filter.call( this[ i ], i ) ? this[ i ] : null;
}
res = res.filter( _cleanArray );
return this.constructor( res );
}
else
{
var _filter = function( _f, _self, i )
{
if ( Microbe.pseudo[ _f[ 0 ] ] )
{
return Microbe.pseudo[ _f[ 0 ] ]( _self, _f[ 1 ] );
}
else
{
var resArray = [], _selector;
_selector = i === 0 ? _f[ 0 ] : ':' + _f[ 0 ];
if ( _selector !== '' )
{
if ( _f[ 1 ] !== '' )
{
_selector += '(' + _f[ 1 ] + ')';
}
for ( var j = 0, lenJ = _self.length; j < lenJ; j++ )
{
_el = _self[ j ];
resArray[ j ] = Microbe.matches( _el, _selector ) === true ? _el : null;
}
resArray = resArray.filter( _cleanArray );
}
return new Microbe( resArray );
}
};
if ( filter && filter.indexOf( ':' ) !== -1 )
{
pseudo = filter.split( ':' );
filters = [ [ pseudo.splice( 0, 1 ).toString(), '' ] ];
var _p, pseudoArray;
for ( var h = 0, lenH = pseudo.length; h < lenH; h++ )
{
_p = pseudo[ h ];
if ( _p.indexOf( '(' ) !== - 1 )
{
_p = _p.split( '(' );
_p[ 1 ] = _p[ 1 ].replace( ')', '' );
}
else
{
_p = [ _p, '' ];
}
filters.push( _p );
}
}
else if ( filter )
{
filters = [ [ filter, '' ] ];
}
else
{
return this;
}
for ( var k = 0, lenK = filters.length; k < lenK; k++ )
{
if ( self.length !== 0 )
{
if ( filters[ k ][ 0 ] !== '' )
{
self = _filter( filters[ k ], self, k );
}
}
else
{
return self;
}
}
return self;
}
};
/**
* ## find
*
* Finds a child element with the given selector inside the scope of the current microbe
*
* @param {String} selector selector to search for
*
* @example µ( '.example' ).find( 'div' );
*
* @return _Microbe_ new microbe containing only the found children values
*/
Microbe.core.find = function( _selector )
{
var _s = _selector[ 0 ];
if ( _s === ' ' )
{
_selector = _selector.trim();
_s = _selector[ 0 ];
}
if ( _s === '>' )
{
_selector = _selector.slice( 1 ).trim();
return this.childrenFlat().filter( _selector );
}
else if ( _s === '~' )
{
_selector = _selector.slice( 1 ).trim();
return this.siblingsFlat().filter( _selector );
}
else if ( _s === '!' )
{
return this.parent();
}
else if ( _s === '+' )
{
_selector = _selector.slice( 1 ).trim();
var resArray = [],
_el, els = this.children();
for ( var i = 0, lenI = els.length; i < lenI; i++ )
{
_el = els[ i ][ 0 ];
resArray[ i ] = _el ? _el : null;
}
resArray.filter( _cleanArray );
return new Microbe( resArray ).filter( _selector );
}
else if ( _selector.indexOf( ':' ) !== -1 )
{
return this.constructor( _selector, this );
}
var _children = new Microbe( _selector ), res = [], r = 0;
for ( var j = 0, lenJ = this.length; j < lenJ; j++ )
{
for ( var k = 0, lenK = _children.length; k < lenK; k++ )
{
if ( Microbe.contains( _children[ k ], this[ j ] ) )
{
res[ r ] = _children[ k ];
r++;
}
}
}
return this.constructor( res );
};
/**
* ## first
*
* gets the first Element and wraps it in Microbe.
*
* @example µ( '.example' ).first();
*
* @return _Microbe_ new Microbe containing only the first value
*/
Microbe.core.first = function()
{
if ( this.length !== 0 )
{
return this.constructor( this[ 0 ] );
}
return this.constructor( [] );
};
/**
* ## last
*
* Gets the last Element and wraps it in Microbe.
*
* @example µ( '.example' ).last();
*
* @return _Microbe_ new microbe containing only the last value
*/
Microbe.core.last = function()
{
var len = this.length;
if ( len === 1 )
{
return this;
}
else if ( len !== 0 )
{
return this.constructor( this[ len - 1 ] );
}
return this.constructor( [] );
};
/**
* ## parent
*
* gets all elements in a microbe's parent nodes
*
* @example µ( '.example' ).parent();
*
* @return _Microbe_ new microbe containing parent elements (index-preserved)
*/
Microbe.core.parent = function()
{
var _parent = function( _el )
{
return _el.parentNode;
};
var i, len, parentArray = new Array( this.length );
for ( i = 0, len = this.length; i < len; i++ )
{
parentArray[ i ] = _parent( this[ i ] );
}
return this.constructor( parentArray );
};
/**
* ## siblings
*
* Gets an microbe of all of each given element's siblings
*
* @param {String} selector css selector string filter
*
* @example µ( '.example' ).siblings();;
* @example µ( '.example' ).siblings( 'div' );
*
* @return _Array_ array of microbes (value)
*/
Microbe.core.siblings = function( selector )
{
var _constructor = this.constructor;
var _siblings = function( _el )
{
var res = [], r = 0;
var sibling = _el.parentNode.firstElementChild;
for ( ; sibling; )
{
if ( sibling !== _el )
{
res[ r ] = sibling;
r++;
}
sibling = sibling.nextElementSibling;
if ( !sibling )
{
res = _constructor( res );
if ( typeof selector === 'string' )
{
return res.filter( selector );
}
return res;
}
}
};
return this.map( _siblings );
};
/**
* ## siblingsFlat
*
* Gets an microbe of all siblings of all element's given. 'next' and 'prev'
* passed as direction return only the next or previous siblings of each element
*
* @param {String} direction direction modifier (optional)
*
* @example µ( '.example' ).siblingsFlat();
* @example µ( '.example' ).siblingsFlat( 'div' );
*
* @return _Microbe_ value array of combined siblings
*/
Microbe.core.siblingsFlat = function( selector )
{
var i = 0, siblingsArray = [];
var isSiblingConnector = ( selector === '+' || selector === '~' );
var _siblingsFlat = function( _el )
{
var sibling = _el;
if ( !isSiblingConnector )
{
sibling = _el.parentNode.firstElementChild;
}
else
{
sibling = _el.nextElementSibling;
}
for ( ; sibling; )
{
if ( sibling !== _el && siblingsArray.indexOf( sibling ) === -1 )
{
siblingsArray[ i ] = sibling;
i++;
}
sibling = sibling.nextElementSibling;
if ( !sibling || selector === '+' )
{
break;
}
}
};
this.each( _siblingsFlat );
var _el = this.constructor( siblingsArray );
if ( typeof selector === 'string' && !isSiblingConnector )
{
return _el.filter( selector );
}
return _el;
};
/**
* ## toString
*
* Methods returns the type of Microbe.
*
* @example µ( '.example' ).toString();
*
* @return _String_
*/
Microbe.core.toString = function()
{
return this.type;
};
};
},{}],4:[function(require,module,exports){
/**
* Microbe.js
*
* @author Mouse Braun <mouse@knoblau.ch>
* @author Nicolas Brugneaux <nicolas.brugneaux@gmail.com>
*
* @package Microbe
*/
var slice = Array.prototype.slice;
module.exports = function( Microbe, _type )
{
'use strict';
Microbe.core = {};
var trigger, _shortSelector;
var selectorRegex = Microbe.prototype.__selectorRegex = /(?:[\s]*\.([\w-_\.]+)|#([\w-_]+)|([^#\.:<][\w-_]*)|(<[\w-_#\.]+>)|:([^#\.<][\w-()_]*))/g;
// TODO: Check if we hit the duck
/**
* ## _build
*
* Builds and returns the final Microbe
*
* @param {Array} _elements array of elements
* @param {String} _selector selector
*
* @return _Microbe_ Microbe wrapped elements
*/
function _build( _elements, self )
{
var i = 0, lenI = _elements.length;
for ( ; i < lenI; i++ )
{
self[ i ] = _elements[ i ];
}
self.length = i;
return self;
}
/**
* ## _create
*
* Method creates Microbe from a passed string, and returns it
*
* @param {String} _el element to create
* @param {Object} this reference to pass on to _build
*
* @return _Microbe_
*/
function _create( _el, self )
{
var resultsRegex = _el.match( selectorRegex ),
_id = '', _tag = '', _class = '';
var i = 0, lenI = resultsRegex.length;
for ( ; i < lenI; i++ )
{
var trigger = resultsRegex[ i ][ 0 ];
switch ( trigger )
{
case '#':
_id += resultsRegex[ i ];
break;
case '.':
_class += resultsRegex[ i ];
break;
default:
_tag += resultsRegex[ i ];
break;
}
}
if ( typeof _tag === 'string' )
{
_el = document.createElement( _tag );
if ( _id )
{
_el.id = _id.slice( 1 );
}
if ( _class )
{
_class = _class.split( '.' );
for ( i = 1, lenI = _class.length; i < lenI; i++ )
{
_el.classList.add( _class[ i ] );
}
}
}
return _build( [ _el ], self );
}
/**
* ## _createHtml
*
* Method creates a Microbe from an html string, and returns it
*
* @param {String} _el element to create
* @param {Object} this reference to pass on to _build
*
* @return _Microbe_
*/
function _createHtml( _el, self )
{
var _ghost = document.createElement( 'div' );
_ghost.innerHTML = _el;
_el = slice.call( _ghost.children );
for ( var i = 0, lenI = _el.length; i < lenI; i++ )
{
_ghost.removeChild( _el[ i ] );
}
return _build( _el, self );
}
/**
* ## _css4StringReplace
*
* translates css4 strings
*
* @param {String} _string pre substitution string
*
* @return _String_ post substitution string
*/
function _css4StringReplace( _string )
{
if ( _string.indexOf( '>>' ) !== -1 )
{
_string = _string.replace( />>/g, ' ' );
}
if ( _string.indexOf( '!' ) !== -1 )
{
_string = _string.replace( /!/g, ':parent' );
}
return _string;
}
/**
* ## _noScopeSimple
*
* if ther is no scope and there is only a simple selector
*
* @param {String} _s selector string
* @param {Object} self this empty Microbe
*
* @return _Microbe_
*/
function _noScopeSimple( _s, self )
{
if ( typeof _s === 'string' && _s.indexOf( ':' ) === -1 &&
_s.indexOf( '!' ) === -1 && _s.indexOf( ' ' ) === -1 )
{
switch ( _s[0] )
{
case '#':
if ( _s.indexOf( '.' ) === -1 )
{
var id = document.getElementById( _s.slice( 1 ) );
return id === null ? _build( [], self ) : _build( [ id ], self );
}
break;
case '.':
if ( _s.indexOf( '#' ) === -1 )
{
var clss = _s.slice( 1 );
if ( clss.indexOf( '.' ) === -1 )
{
return _build( document.getElementsByClassName( clss ), self );
}
else
{
clss = clss.split( '.' );
var res, _r, _el = document.getElementsByClassName( clss[ 0 ] );
for ( var c = 1, lenC = clss.length; c < lenC; c++ )
{
res = slice.call( document.getElementsByClassName( clss[ c ] ) );
for ( var r = 0, lenR = _el.length; r < lenR; r++ )
{
_r = _el[ r ];
if ( res.indexOf( _r ) === -1 )
{
_el[ r ] = null;
}
}
}
return _build( _el, self ).filter( function( _e ){ return _e !== null; } );
}
}
break;
default:
if ( _s && _s.indexOf( '[' ) === -1 && _s.indexOf( '<' ) === -1 &&
_s.indexOf( '#' ) === -1 && _s.indexOf( '.' ) === -1 )
{
return _build( document.getElementsByTagName( _s ), self );
}
break;
}
}
else if ( typeof _s === 'function' && Microbe && typeof Microbe.ready === 'function' )
{
Microbe.ready( _s );
}
return false;
}
/**
* ## \_\_init\_\_
*
* Constructor.
*
* Either selects or creates an HTML element and wraps it into a Microbe instance.
*
* @param {Mixed} _selector HTML selector (Element String Array)
* @param {Mixed} _scope scope to look inside (Element String Microbe)
* @param {Mixed} _elements elements to fill Microbe with (optional) (Element or Array)
*
* @example µ() ---> empty
* @example µ( '' ) ---> empty
* @example µ( [] ) ---> empty
* @example µ( 'div#test' ) ---> selection
* @example µ( elDiv ) ---> selection
* @example µ( [ elDiv1, elDiv2, elDiv3 ] ) ---> selection
* @example µ( '<div#test>' ) ---> creation
* @example µ( '<div id="test"></div>' ) ---> creation
*
* @return _Microbe_
*/
var Init = Microbe.core.__init__ = function( _selector, _scope, _elements )
{
var res;
if ( !_scope )
{
res = _noScopeSimple( _selector, this );
if ( res )
{
return res;
}
}
if ( typeof _selector === 'string' )
{
_selector = _css4StringReplace( _selector );
}
if ( typeof _scope === 'string' )
{
_scope = _css4StringReplace( _scope );
}
_selector = _selector || '';
if ( _scope && _scope.type === _type )
{
res = _build( [], this );
var next;
for ( var n = 0, lenN = _scope.length; n < lenN; n++ )
{
next = new Init( _selector, _scope[ n ] );
for ( var i = 0, lenI = next.length; i < lenI; i++ )
{
if ( Array.prototype.indexOf.call( res, next[ i ] ) === -1 )
{
res[ res.length ] = next[ i ];
res.length++;
}
}
}
return res;
}
/*
* fast tracks element based queries
*/
var isArr, isHTMLCollection;
if ( _selector.nodeType === 1 || ( isArr = Array.isArray( _selector ) ) ||
_selector === window || _selector === document ||
( isHTMLCollection = _selector.toString() === '[object HTMLCollection]' ) )
{
if ( !isArr && !isHTMLCollection )
{
_selector = [ _selector ];
}
return _build( _selector, this );
}
_scope = _scope === undefined ? document : _scope;
if ( _scope !== document )
{
if ( typeof _scope === 'string' && typeof _selector === 'string' )
{
return this.constructor( _scope ).find( _selector );
}
}
var scopeNodeType = _scope.nodeType;
if ( ( !_selector || typeof _selector !== 'string' ) ||
( scopeNodeType !== 1 && scopeNodeType !== 9 ) )
{
return _build( [], this );
}
var resultsRegex = _selector.match( selectorRegex );
if ( resultsRegex && resultsRegex.length === 1 && resultsRegex[ 0 ][ 0 ] !== ':' )
{
trigger = resultsRegex[0][0];
_shortSelector = _selector.slice( 1 );
switch( trigger )
{
case '.': // non-document scoped classname search
var _classesCount = ( _selector || '' ).slice( 1 ).split( '.' ).length;
if ( _classesCount === 1 )
{
return _build( _scope.getElementsByClassName( _shortSelector ), this );
}
break;
case '#': // non-document scoped id search
var _id = document.getElementById( _shortSelector );
if ( _scope.ownerDocument && this.contains( _id, _scope ) )
{
return _build( [ _id ], this );
}
else
{
return _build( [], this );
}
break;
case '<': // element creation
return _create( _selector.substring( 1, _selector.length - 1 ), this );
default:
return _build( _scope.getElementsByTagName( _selector ), this );
}
}
if ( !( this instanceof Init ) )
{
return new Init( _selector, _scope, _elements );
}
if ( _selector.indexOf( ':' ) !== -1 && _pseudo )
{
return _pseudo( this, _selector, _scope, _build );
}
// html creation string
if ( _selector.indexOf( '/' ) !== -1 )
{
return _createHtml( _selector, this );
}
return _build( _scope.querySelectorAll( _selector ), this );
};
Microbe.core.type = _type;
Microbe.core.__init__.prototype = Microbe.core;
require( './core' )( Microbe );
require( './root' )( Microbe );
require( './pseudo' )( Microbe );
require( './array' )( Microbe );
var _pseudo = Microbe.constructor.pseudo;
};
},{"./array":2,"./core":3,"./pseudo":5,"./root":6}],5:[function(require,module,exports){
/**
* pseudo.js
*
* @author Mouse Braun <mouse@knoblau.ch>
* @author Nicolas Brugneaux <nicolas.brugneaux@gmail.com>
*
* @package Microbe
*/
module.exports = function( Microbe )
{
'use strict';
/**
* ## _parseNth
*
* when supplied with a Microbe and a css style n selector (2n1), filters
* and returns the result
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var number string
* @param {Boolean} _last counting from the font or back
*
* @return _Microbe_
*/
var _parseNth = function( _el, _var, _last )
{
if ( _var === 'odd' )
{
_var = '2n';
}
else if ( _var === 'even' )
{
_var = '2n1';
}
if ( _var.indexOf( 'n' ) === -1 )
{
switch ( _last )
{
case true:
case 'last':
return new Microbe( _el[ _el.length - parseInt( _var ) ] );
}
return new Microbe( _el[ parseInt( _var ) - 1 ] );
}
else
{
_var = _var.split( 'n' );
var increment = parseInt( _var[0] ) || 1;
var offset = parseInt( _var[1] );
var top;
if ( _last === true || _last === 'last' )
{
top = _el.length - parseInt( _var[1] );
offset = top % increment;
}
var _e, resArray = [];
for ( var i = offset || 0, lenI = top || _el.length; i < lenI; )
{
_e = _el[ i ];
if ( _e )
{
resArray.push( _e );
}
i += increment;
}
return new Microbe( resArray );
}
};
/**
* ## pseudo
*
* an extension to core.__init_ to handle custom pseusoselectors
*
* @param {Microbe} self half built Microbe
* @param {String} selector pseudo-selector string
* @param {Object} _scope scope element
* @param {Function} _build build function from core
*
* @return _Microbe_
*/
var pseudo = function( self, selector, _scope, _build )
{
/**
* ## _breakUpSelector
*
* pushes each selector through the pseudo-selector engine
*
* @param {Array} _selectors split selectors
*
* @return _Microbe_
*/
function _breakUpSelector( _selectors )
{
var next, resArray = [];
for ( var i = 0, lenI = _selectors.length; i < lenI; i++ )
{
if ( i === 0 )
{
resArray = pseudo( self, _selectors[ i ], _scope, _build );
}
else
{
next = pseudo( self, _selectors[ i ], _scope, _build );
for ( var j = 0, lenJ = next.length; j < lenJ; j++ )
{
if ( Array.prototype.indexOf.call( resArray, next[ j ] ) === -1 )
{
resArray[ resArray.length ] = next[ j ];
resArray.length++;
}
}
}
}
return resArray;
}
/**
* ## _buildObject
*
* builds the Microbe ready for return
*
* @return _Microbe_
*/
function _buildObject()
{
var _pseudo = _parsePseudo( _selector );
var obj = _build( _scope.querySelectorAll( _pseudo[0] ), self );
_pseudo = _pseudo[ 1 ];
var _sel, _var;
for ( var h = 0, lenH = _pseudo.length; h < lenH; h++ )
{
_sel = _pseudo[ h ].split( '(' );
_var = _sel[ 1 ];
if ( _var )
{
_var = _var.slice( 0, _var.length - 1 );
}
_sel = _sel[ 0 ];
if ( Microbe.constructor.pseudo[ _sel ] )
{
obj = Microbe.constructor.pseudo[ _sel ]( obj, _var, selector );
}
}
return obj;
}
/**
* ## _cycleFilters
*
* filters multiple pseudo-selector selectors
*
* @param {Array} res array of results to be filtered
*
* @return _Microbe_
*/
function _cycleFilters( res )
{
var obj = Microbe.constructor.pseudo( self, res[ 0 ], _scope, _build );
var filter, connect = false;
for ( var i = 1, lenI = res.length; i < lenI; i++ )
{
filter = res[ i ].trim();
if ( filter[ 0 ] === '~' )
{
obj = obj.siblingsFlat( '~' );
connect = true;
}
else if ( filter[ 0 ] === '+' )
{
obj = obj.siblingsFlat( '+' );
connect = true;
}
else if ( connect )
{
obj = obj.filter( filter );
connect = false;
}
else
{
obj = obj.find( filter );
connect = false;
}
if ( obj.length === 0 )
{
return obj;
}
}
return obj;
}
/**
* ## _parsePseudo
*
* checks all pseudo-selectors to see if they're custom and
* otherwise it reattaches it
*
* @param {String} _sel selector string
*
* @return _String_ modified selector
*/
function _parsePseudo( _sel )
{
var _pseudoArray;
var _pseudo = _sel.split( ':' );
_sel = _pseudo[ 0 ];
_pseudo.splice( 0, 1 );
for ( var k = 0, lenK = _pseudo.length; k < lenK; k++ )
{
_pseudoArray = _pseudo[ k ].split( '(' );
if ( !Microbe.constructor.pseudo[ _pseudoArray[ 0 ] ] )
{
_sel += ':' + _pseudo[ k ];
_pseudo.splice( k, 1 );
}
}
return [ _sel, _pseudo ];
}
if ( selector.indexOf( ',' ) !== -1 )
{
selector = selector.split( /,(?![a-zA-Z0-9-#.,\s]+\))/g );
if ( selector.length > 1 )
{
return _breakUpSelector( selector );
}
else
{
selector = selector[ 0 ];
}
}
var _selector = selector;
if ( _selector[ 0 ] === ':' )
{
_selector = '*' + _selector;
}
if ( _selector.trim().indexOf( ' ' ) !== -1 )
{
var filterFunction = function( e ){ return e === ' ' ? false : e; };
var res = _selector.split( /((?:[A-Za-z0-9.#*\-_]+)?(?:\:[A-Za-z\-]+(?:\([\s\S]+\))?)?)?( )?/ );
res = res.filter( filterFunction );
if ( res.length > 1 )
{
return _cycleFilters( res );
}
else
{
_selector = res[ 0 ];
}
}
return _buildObject();
};
/**
* ## _filteredIteration
*
* special iterator that dumps all results ito one array
*
* @param {Microbe} _el elements to cycle through
* @param {Function} _cb callback
*
* @return _Microbe_ filtered microbe
*/
function _filteredIteration( _el, _cb, _recursive )
{
var _r, resArray = [], _f = 0;
for ( var i = 0, lenI = _el.length; i < lenI; i++ )
{
_r = _cb( _el[ i ], resArray, i );
if ( _r )
{
resArray[ _f ] = _r;
_f++;
}
}
if ( _recursive )
{
return resArray;
}
return _el.constructor( resArray );
}
/**
* ## any-link
*
* match elements that act as the source anchors of hyperlinks
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:any-link' );
*
* @return _Microbe_
*/
pseudo[ 'any-link' ] = function( _el )
{
return _el.filter( 'a' );
};
/**
* ## blank
*
* matches elements that only contain content which consists of whitespace
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:blank' );
*
* @return _Microbe_
*/
pseudo.blank = function( _el )
{
var _blank = function( _e, resArray )
{
var _t = document.all ? _e.innerText : _e.textContent;
if ( resArray.indexOf( _e ) === -1 )
{
if ( /^\s*$/.test( _t || _e.value ) )
{
return _e;
}
}
};
return _filteredIteration( _el, _blank );
};
/**
* ## column
*
* filters for columns with a suplied selector
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var string to search for
*
* @example µ( '.example:column' );
*
* @return _Microbe_
*/
pseudo.column = function( _el, _var )
{
return _el.filter( 'col' ).filter( _var );
};
/**
* ## contains
*
* Returns only elements that contain the given text. The supplied text
* is compared ignoring case
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var string to search for
*
* @example µ( '.example:contains(moon)' );
*
* @return _Microbe_
*/
pseudo.contains = function( _el, _var )
{
_var = _var.toLowerCase();
var _contains = function( _e )
{
var _getText = function( _el )
{
return document.all ? _el.innerText : _el.textContent; // ff
};
var _elText = _getText( _e );
if ( _elText.toLowerCase().indexOf( _var ) !== -1 )
{
return _e;
}
};
return _filteredIteration( _el, _contains );
};
/**
* ## default
*
* selects all inputs and select boxes that are checked by dafeult
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:default' );
*
* @return _Microbe_
*/
pseudo.default = function( _el )
{
_el = _el.filter( 'input, option' );
var _default = function( _e )
{
if ( _e.defaultChecked === true )
{
return _e;
}
};
return _filteredIteration( _el, _default );
};
/**
* ## dir
*
* match elements by its directionality based on the document language
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var string to search for
*
* @example µ( '.example:dir(ltr)' );
*
* @return _Microbe_
*/
pseudo.dir = function( _el, _var )
{
var _dir = function( _e )
{
if ( getComputedStyle( _e ).direction === _var )
{
return _e;
}
};
return _filteredIteration( _el, _dir );
};
/**
* ## drop
*
* returns all elements that are drop targets. HTML has a dropzone
* attribute which specifies that an element is a drop target.
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var trigger string
*
* @example µ( '.example:drop' );
*
* @return _Microbe_
*/
pseudo.drop = function( _el, _var )
{
_el = _el.filter( '[dropzone]' );
if ( !_var )
{
return _el;
}
else
{
switch ( _var )
{
case 'active':
return _el.filter( ':active' );
case 'invalid':
return _el.filter();
case 'valid':
return _el.filter();
}
}
};
/**
* ## even
*
* Returns the even indexed elements of a Microbe (starting at 0)
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:even' );
*
* @return _Microbe_
*/
pseudo.even = function( _el )
{
var _even = function( _e, resArray, i )
{
if ( ( i + 1 ) % 2 === 0 )
{
return _e;
}
};
return _filteredIteration( _el, _even );
};
/**
* ## first
*
* returns the first element of a Microbe
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:first' );
*
* @return _Microbe_
*/
pseudo.first = function( _el )
{
return _el.first();
};
/**
* ## gt
*
* returns the last {_var} element
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var number of elements to return
*
* @example µ( '.example:gt(4)' );
*
* @return _Microbe_
*/
pseudo.gt = function( _el, _var )
{
return _el.splice( _var, _el.length );
};
/**
* ## has
*
* returns elements that have the passed selector as a child
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var selector string
*
* @example µ( '.example:has(span)' );
*
* @return _Microbe_
*/
pseudo.has = function( _el, _var )
{
var _has = function( _e )
{
if ( _e.querySelector( _var ) )
{
return _e;
}
};
return _filteredIteration( _el, _has );
};
/**
* ## in-range
*
* select the elements with a value inside the specified range
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:in-range' );
*
* @return _Microbe_
*/
pseudo[ 'in-range' ] = function( _el )
{
_el = _el.filter( '[max],[min]' );
var _inRange = function( _e )
{
var min = _e.getAttribute( 'min' );
var max = _e.getAttribute( 'max' );
var _v = parseInt( _e.value );
if ( _v )
{
if ( min && max )
{
if ( _v > min && _v < max )
{
return _e;
}
}
else if ( min && _v > min || max && _v < max )
{
return _e;
}
}
};
return _filteredIteration( _el, _inRange );
};
/**
* ## lang
*
* match the elements based on the document language
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var specified language (accepts wildcards as *)
*
* @example µ( '.example:lang(gb-en)' );
* @example µ( '.example:lang(*-en)' );
*
* @return _Microbe_
*/
pseudo.lang = function( _el, _var )
{
if ( _var )
{
if ( _var.indexOf( '*' ) !== -1 )
{
_el = _el.filter( '[lang]' );
_var = _var.replace( '*', '' );
var _lang = function( _e )
{
if ( _e.getAttribute( 'lang' ).indexOf( _var ) !== -1 )
{
return _e;
}
};
return _filteredIteration( _el, _lang );
}
var res = document.querySelectorAll( ':lang(' + _var + ')' );
return _el.constructor( Array.prototype.slice.call( res ) );
}
else
{
return _el.constructor( [] );
}
};
/**
* ## last
*
* returns the last element of a Microbe
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:last' );
*
* @return _Microbe_
*/
pseudo.last = function( _el )
{
return _el.last();
};
/**
* ## local-link
*
* returns all link tags that go to local links. If specified a depth
* filter can be added
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var specified depth
*
* @example µ( '.example:local-link' );
* @example µ( '.example:local-link(2)' );
*
* @return _Microbe_
*/
pseudo[ 'local-link' ] = function( _el, _var )
{
_el = _el.filter( 'a' );
var here = document.location;
var _localLink = function( _e )
{
var url = _e.href;
var urlShort = url.replace( here.origin, '' ).replace( here.host, '' );
urlShort = urlShort[ 0 ] === '/' ? urlShort.slice( 1 ) : urlShort;
var depth = urlShort.split( '/' ).length - 1;
if ( !_var || parseInt( _var ) === depth )
{
return _e;
}
};
return _filteredIteration( _el, _localLink );
};
/**
* ## lt
*
* returns the first [_var] elements
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var number of elements to return
*
* @example µ( '.example:lt(2)' );
*
* @return _Microbe_
*/
pseudo.lt = function( _el, _var )
{
return _el.splice( 0, _var );
};
/**
* ## matches
*
* returns elements that match either selector
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var selector filter
* @param {String} _selector full original selector
*
* @example µ( '.example:matches(div)' );
*
* @return _Microbe_
*/
pseudo.matches = function( _el, _var, _selector )
{
var _constructor = _el.constructor;
var text = ':matches(' + _var + ')';
_var = _var.split( ',' );
_selector = _selector.replace( text, '' );
_selector = _selector === '*' ? '' : _selector;
var res = _constructor( _selector + _var[ 0 ].trim() );
for ( var i = 1, lenI = _var.length; i < lenI; i++ )
{
res.merge( _constructor( _selector + _var[ i ].trim() ), true );
}
return res;
};
/**
* ## not
*
* returns all elements that do not match the given selector. As per
* CSS4 spec, this accepts complex selectors seperated with a comma
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var null selector
* @param {String} _recursive an indicator that it is calling itself. defines output
*
* @example µ( '.example:not(div)' );
* @example µ( '.example:not(div,#an--id)' );
*
* @return _Microbe_
*/
pseudo.not = function( _el, _var, _selector, _recursive )
{
if ( _var.indexOf( ',' ) !== -1 )
{
var _constructor = _el.constructor;
_var = _var.split( ',' );
for ( var i = 0, lenI = _var.length; i < lenI; i++ )
{
_el = this.not( _el, _var[ i ].trim(), _selector, true );
}
return _constructor( _el );
}
else
{
var _not = function( _e )
{
if ( ! Microbe.matches( _e, _var ) )
{
return _e;
}
};
return _filteredIteration( _el, _not, _recursive );
}
};
/**
* ## nth-column
*
* returns the nth column of the current Microbe
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var column number(s) return
*
* @example µ( '.example:nth-column(1)' );
* @example µ( '.example:nth-column(2n1)' );
* @example µ( '.example:nth-column(even)' );
* @example µ( '.example:nth-column(odd)' );
*
* @return _Microbe_
*/
pseudo[ 'nth-column' ] = function( _el, _var )
{
_el = _el.filter( 'col' );
return _parseNth( _el, _var );
};
/**
* ## nth-last-column
*
* returns the nth column of the current Microbe starting from the back
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var column number(s) return
*
* @example µ( '.example:nth-last-column(1)' );
* @example µ( '.example:nth-last-column(2n1)' );
* @example µ( '.example:nth-last-column(even)' );
* @example µ( '.example:nth-last-column(odd)' );
*
* @return _Microbe_
*/
pseudo[ 'nth-last-column' ] = function( _el, _var )
{
_el = _el.filter( 'col' );
return _parseNth( _el, _var, true );
};
/**
* ## nth-last-match
*
* returns the nth match(es) of the current Microbe starting from the back
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var match number(s) return
*
* @example µ( '.example:nth-last-match(1)' );
* @example µ( '.example:nth-last-match(2n1)' );
* @example µ( '.example:nth-last-match(even)' );
* @example µ( '.example:nth-last-match(odd)' );
*
* @return _Microbe_
*/
pseudo[ 'nth-last-match' ] = function( _el, _var )
{
return _parseNth( _el, _var, true );
};
/**
* ## nth-match
*
* returns the nth match(es) of the current Microbe
*
* @param {Microbe} _el Microbe to be filtered
* @param {String} _var match number(s) return
*
* @example µ( '.example:nth-match(1)' );
* @example µ( '.example:nth-match(2n1)' );
* @example µ( '.example:nth-match(even)' );
* @example µ( '.example:nth-match(odd)' );
*
* @return _Microbe_
*/
pseudo[ 'nth-match' ] = function( _el, _var )
{
return _parseNth( _el, _var );
};
/**
* ## odd
*
* returns the odd indexed elements of a Microbe
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:odd' );
*
* @return _Microbe_
*/
pseudo.odd = function( _el )
{
var _odd = function( _e, resArray, i )
{
if ( ( i + 1 ) % 2 !== 0 )
{
return _e;
}
};
return _filteredIteration( _el, _odd );
};
/**
* ## optional
*
* returns all optional elements
*
* @param {Microbe} _el base elements set
*
* @example µ( '.example:optional' );
*
* @return _Microbe_
*/
pseudo.optional = function( _el )
{
return _el.filter( 'input:not([required=required]), textfield:not([required=required]), [required=optional], [optional]' );
};
/**
* ## out-of-range
*
* select the elements with a value inside the specified range
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:out-of-range' );
*
* @return _Microbe_
*/
pseudo[ 'out-of-range' ] = function( _el )
{
_el = _el.filter( '[max],[min]' );
var _outOfRange = function( _e )
{
var min = _e.getAttribute( 'min' );
var max = _e.getAttribute( 'max' );
var _v = parseInt( _e.value );
if ( _v )
{
if ( min && max )
{
if ( _v < min || _v > max )
{
return _e;
}
}
else if ( min && _v < min || max && _v > max )
{
return _e;
}
}
};
return _filteredIteration( _el, _outOfRange );
};
/**
* ## parent
*
* returns the parents of an _el match.
* normally triggered using the ! selector
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example!' );
* @example µ( '.example:parent' );
*
* @return _Microbe_
*/
pseudo.parent = function( _el )
{
_el = _el.parent();
var _parent = function( _e, resArray, i )
{
if ( resArray.indexOf( _e ) === -1 )
{
return _e;
}
};
return _filteredIteration( _el, _parent );
};
/**
* ## read-only
*
* user-non-alterable content
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:read-only' );
*
* @return _Microbe_
*/
pseudo[ 'read-only' ] = function( _el )
{
return _el.filter( ':not(input,textfield,[contenteditable=false])' );
};
/**
* ## read-write
*
* input elements which are user-alterable or contenteditable
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:read-write' );
*
* @return _Microbe_
*/
pseudo[ 'read-write' ] = function( _el )
{
return _el.filter( 'input,textfield,[contenteditable=true]' );
};
/**
* ## required
*
* returns all required elements
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:required' );
*
* @return _Microbe_
*/
pseudo.required = function( _el )
{
return _el.filter( '[required=required]' );
};
/**
* ## root
*
* returns the root elements of the document
*
* @param {Microbe} _el Microbe to be filtered
*
* @example µ( '.example:root );
*
* @return _Microbe_
*/
pseudo.root = function( _el )
{
return _el.constructor( document.body.parentNode );
};
Microbe.constructor.prototype.pseudo = pseudo;
};
},{}],6:[function(require,module,exports){
/**
* rootUtils.js
*
* @author Mouse Braun <mouse@knoblau.ch>
* @author Nicolas Brugneaux <nicolas.brugneaux@gmail.com>
*
* @package Microbe
*/
module.exports = function( Microbe )
{
'use strict';
/**
* ## contains
*
* Checks if a given element is a child of _scope
*
* @param {Element} _el element to check
* @param {Element} _scope scope
*
* @example µ.contains( _el, _parentEl );
*
* @return _Boolean_ whether _el is contained in the scope
*/
Microbe.contains = function( _el, _scope )
{
var parent = _el.parentNode;
while ( parent !== document && parent !== _scope )
{
parent = parent.parentNode || _scope.parentNode;
}
if ( parent === document )
{
return false;
}
return true;
};
/**
* ## matches
*
* checks element an to see if they match a given css selector
* unsure if we actually need the webkitMatchSelector and mozMatchSelector
* http://caniuse.com/#feat=matchesselector
*
* @param {Mixed} el element, microbe, or array of elements to match
*
* @example µ.matches( _el, 'div.example' );
*
* @return _Booblean_ matches or not
*/
Microbe.matches = function( el, selector )
{
var method = this.matches.__matchesMethod;
var notForm = ( typeof el !== 'string' && !!( el.length ) &&
el.toString() !== '[object HTMLFormElement]' );
var isArray = Array.isArray( el ) || notForm ? true : false;
if ( !isArray && !notForm )
{
el = [ el ];
}
if ( !method && el[ 0 ] )
{
if ( el[ 0 ].matches )
{
method = this.matches.__matchesMethod = 'matches';
}
else if ( el[ 0 ].msMatchesSelector )
{
method = this.matches.__matchesMethod = 'msMatchesSelector';
}
else if ( el[ 0 ].mozMatchesSelector )
{
method = this.matches.__matchesMethod = 'mozMatchesSelector';
}
else if ( el[ 0 ].webkitMatchesSelector )
{
method = this.matches.__matchesMethod = 'webkitMatchesSelector';
}
}
var resArray = [];
for ( var i = 0, lenI = el.length; i < lenI; i++ )
{
resArray.push( el[ i ][ method ]( selector ) );
}
return isArray ? resArray : resArray[ 0 ];
};
};
},{}]},{},[1])(1)
}); |
/*!
* inferno-mobx v1.0.0-beta21
* (c) 2016 Ryan Megidov
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component'), require('./inferno'), require('./inferno-create-class'), require('./inferno-create-element')) :
typeof define === 'function' && define.amd ? define(['inferno-component', 'inferno', 'inferno-create-class', 'inferno-create-element'], factory) :
(global.Inferno = global.Inferno || {}, global.Inferno.Mobx = factory(global.Inferno.Component,global.Inferno,global.Inferno.createClass,global.Inferno.createElement));
}(this, (function (Component,Inferno,createClass,createElement) { 'use strict';
Component = 'default' in Component ? Component['default'] : Component;
Inferno = 'default' in Inferno ? Inferno['default'] : Inferno;
createClass = 'default' in createClass ? createClass['default'] : createClass;
createElement = 'default' in createElement ? createElement['default'] : createElement;
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
// this is MUCH faster than .constructor === Array and instanceof Array
// in Node 7 and the later versions of V8, slower in older versions though
function throwError(message) {
if (!message) {
message = ERROR_MSG;
}
throw new Error(("Inferno Error: " + message));
}
function warning(condition, message) {
if (!condition) {
console.error(message);
}
}
var specialKeys = {
children: true,
key: true,
ref: true
};
var Provider = (function (Component$$1) {
function Provider(props, context) {
Component$$1.call(this, props, context);
this.contextTypes = { mobxStores: function mobxStores() { } };
this.childContextTypes = { mobxStores: function mobxStores$1() { } };
this.store = props.store;
}
if ( Component$$1 ) Provider.__proto__ = Component$$1;
Provider.prototype = Object.create( Component$$1 && Component$$1.prototype );
Provider.prototype.constructor = Provider;
Provider.prototype.render = function render () {
return this.props.children;
};
Provider.prototype.getChildContext = function getChildContext () {
var this$1 = this;
var stores = {};
// inherit stores
var baseStores = this.context.mobxStores;
if (baseStores) {
for (var key in baseStores) {
stores[key] = baseStores[key];
}
}
// add own stores
for (var key$1 in this.props) {
if (!specialKeys[key$1]) {
stores[key$1] = this$1.props[key$1];
}
}
return {
mobxStores: stores
};
};
return Provider;
}(Component));
if (process.env.NODE_ENV !== 'production') {
Provider.prototype.componentWillReceiveProps = function (nextProps) {
var this$1 = this;
// Maybe this warning is to aggressive?
warning(Object.keys(nextProps).length === Object.keys(this.props).length, 'MobX Provider: The set of provided stores has changed. ' +
'Please avoid changing stores as the change might not propagate to all children');
for (var key in nextProps) {
warning(specialKeys[key] || this$1.props[key] === nextProps[key], "MobX Provider: Provided store '" + key + "' has changed. " +
"Please avoid replacing stores as the change might not propagate to all children");
}
};
}
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var mobx = createCommonjsModule(function (module, exports) {
"use strict";
var __extends = (commonjsGlobal && commonjsGlobal.__extends) || function (d, b) {
for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } }
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
registerGlobals();
exports.extras = {
allowStateChanges: allowStateChanges,
getAtom: getAtom,
getDebugName: getDebugName,
getDependencyTree: getDependencyTree,
getObserverTree: getObserverTree,
isComputingDerivation: isComputingDerivation,
isSpyEnabled: isSpyEnabled,
resetGlobalState: resetGlobalState,
spyReport: spyReport,
spyReportEnd: spyReportEnd,
spyReportStart: spyReportStart,
trackTransitions: trackTransitions,
setReactionScheduler: setReactionScheduler
};
exports._ = {
getAdministration: getAdministration,
resetGlobalState: resetGlobalState
};
if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === 'object') {
__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx(module.exports);
}
var actionFieldDecorator = createClassPropertyDecorator(function (target, key, value, args, originalDescriptor) {
var actionName = (args && args.length === 1) ? args[0] : (value.name || key || "<unnamed action>");
var wrappedAction = action(actionName, value);
addHiddenProp(target, key, wrappedAction);
}, function (key) {
return this[key];
}, function () {
invariant(false, "It is not allowed to assign new values to @action fields");
}, false, true);
function action(arg1, arg2, arg3, arg4) {
if (arguments.length === 1 && typeof arg1 === "function")
{ return createAction(arg1.name || "<unnamed action>", arg1); }
if (arguments.length === 2 && typeof arg2 === "function")
{ return createAction(arg1, arg2); }
if (arguments.length === 1 && typeof arg1 === "string")
{ return namedActionDecorator(arg1); }
return namedActionDecorator(arg2).apply(null, arguments);
}
exports.action = action;
function namedActionDecorator(name) {
return function (target, prop, descriptor) {
if (descriptor && typeof descriptor.value === "function") {
descriptor.value = createAction(name, descriptor.value);
descriptor.enumerable = false;
descriptor.configurable = true;
return descriptor;
}
return actionFieldDecorator(name).apply(this, arguments);
};
}
function runInAction(arg1, arg2, arg3) {
var actionName = typeof arg1 === "string" ? arg1 : arg1.name || "<unnamed action>";
var fn = typeof arg1 === "function" ? arg1 : arg2;
var scope = typeof arg1 === "function" ? arg2 : arg3;
invariant(typeof fn === "function", "`runInAction` expects a function");
invariant(fn.length === 0, "`runInAction` expects a function without arguments");
invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'");
return executeAction(actionName, fn, scope, undefined);
}
exports.runInAction = runInAction;
function isAction(thing) {
return typeof thing === "function" && thing.isMobxAction === true;
}
exports.isAction = isAction;
function autorun(arg1, arg2, arg3) {
var name, view, scope;
if (typeof arg1 === "string") {
name = arg1;
view = arg2;
scope = arg3;
}
else if (typeof arg1 === "function") {
name = arg1.name || ("Autorun@" + getNextId());
view = arg1;
scope = arg2;
}
assertUnwrapped(view, "autorun methods cannot have modifiers");
invariant(typeof view === "function", "autorun expects a function");
invariant(isAction(view) === false, "Warning: attempted to pass an action to autorun. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action.");
if (scope)
{ view = view.bind(scope); }
var reaction = new Reaction(name, function () {
this.track(reactionRunner);
});
function reactionRunner() {
view(reaction);
}
reaction.schedule();
return reaction.getDisposer();
}
exports.autorun = autorun;
function when(arg1, arg2, arg3, arg4) {
var name, predicate, effect, scope;
if (typeof arg1 === "string") {
name = arg1;
predicate = arg2;
effect = arg3;
scope = arg4;
}
else if (typeof arg1 === "function") {
name = ("When@" + getNextId());
predicate = arg1;
effect = arg2;
scope = arg3;
}
var disposer = autorun(name, function (r) {
if (predicate.call(scope)) {
r.dispose();
var prevUntracked = untrackedStart();
effect.call(scope);
untrackedEnd(prevUntracked);
}
});
return disposer;
}
exports.when = when;
function autorunUntil(predicate, effect, scope) {
deprecated("`autorunUntil` is deprecated, please use `when`.");
return when.apply(null, arguments);
}
exports.autorunUntil = autorunUntil;
function autorunAsync(arg1, arg2, arg3, arg4) {
var name, func, delay, scope;
if (typeof arg1 === "string") {
name = arg1;
func = arg2;
delay = arg3;
scope = arg4;
}
else if (typeof arg1 === "function") {
name = arg1.name || ("AutorunAsync@" + getNextId());
func = arg1;
delay = arg2;
scope = arg3;
}
invariant(isAction(func) === false, "Warning: attempted to pass an action to autorunAsync. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action.");
if (delay === void 0)
{ delay = 1; }
if (scope)
{ func = func.bind(scope); }
var isScheduled = false;
var r = new Reaction(name, function () {
if (!isScheduled) {
isScheduled = true;
setTimeout(function () {
isScheduled = false;
if (!r.isDisposed)
{ r.track(reactionRunner); }
}, delay);
}
});
function reactionRunner() { func(r); }
r.schedule();
return r.getDisposer();
}
exports.autorunAsync = autorunAsync;
function reaction(arg1, arg2, arg3, arg4, arg5, arg6) {
var name, expression, effect, fireImmediately, delay, scope;
if (typeof arg1 === "string") {
name = arg1;
expression = arg2;
effect = arg3;
fireImmediately = arg4;
delay = arg5;
scope = arg6;
}
else {
name = arg1.name || arg2.name || ("Reaction@" + getNextId());
expression = arg1;
effect = arg2;
fireImmediately = arg3;
delay = arg4;
scope = arg5;
}
if (fireImmediately === void 0)
{ fireImmediately = false; }
if (delay === void 0)
{ delay = 0; }
var _a = getValueModeFromValue(expression, ValueMode.Reference), valueMode = _a[0], unwrappedExpression = _a[1];
var compareStructural = valueMode === ValueMode.Structure;
if (scope) {
unwrappedExpression = unwrappedExpression.bind(scope);
effect = action(name, effect.bind(scope));
}
var firstTime = true;
var isScheduled = false;
var nextValue = undefined;
var r = new Reaction(name, function () {
if (delay < 1) {
reactionRunner();
}
else if (!isScheduled) {
isScheduled = true;
setTimeout(function () {
isScheduled = false;
reactionRunner();
}, delay);
}
});
function reactionRunner() {
if (r.isDisposed)
{ return; }
var changed = false;
r.track(function () {
var v = unwrappedExpression(r);
changed = valueDidChange(compareStructural, nextValue, v);
nextValue = v;
});
if (firstTime && fireImmediately)
{ effect(nextValue, r); }
if (!firstTime && changed === true)
{ effect(nextValue, r); }
if (firstTime)
{ firstTime = false; }
}
r.schedule();
return r.getDisposer();
}
exports.reaction = reaction;
var computedDecorator = createClassPropertyDecorator(function (target, name, _, decoratorArgs, originalDescriptor) {
invariant(typeof originalDescriptor !== "undefined", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'. It looks like it was used on a property.");
var baseValue = originalDescriptor.get;
var setter = originalDescriptor.set;
invariant(typeof baseValue === "function", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'");
var compareStructural = false;
if (decoratorArgs && decoratorArgs.length === 1 && decoratorArgs[0].asStructure === true)
{ compareStructural = true; }
var adm = asObservableObject(target, undefined, ValueMode.Recursive);
defineObservableProperty(adm, name, compareStructural ? asStructure(baseValue) : baseValue, false, setter);
}, function (name) {
var observable = this.$mobx.values[name];
if (observable === undefined)
{ return undefined; }
return observable.get();
}, function (name, value) {
this.$mobx.values[name].set(value);
}, false, true);
function computed(targetOrExpr, keyOrScopeOrSetter, baseDescriptor, options) {
if (typeof targetOrExpr === "function" && arguments.length < 3) {
if (typeof keyOrScopeOrSetter === "function")
{ return computedExpr(targetOrExpr, keyOrScopeOrSetter, undefined); }
else
{ return computedExpr(targetOrExpr, undefined, keyOrScopeOrSetter); }
}
return computedDecorator.apply(null, arguments);
}
exports.computed = computed;
function computedExpr(expr, setter, scope) {
var _a = getValueModeFromValue(expr, ValueMode.Recursive), mode = _a[0], value = _a[1];
return new ComputedValue(value, scope, mode === ValueMode.Structure, value.name, setter);
}
function createTransformer(transformer, onCleanup) {
invariant(typeof transformer === "function" && transformer.length === 1, "createTransformer expects a function that accepts one argument");
var objectCache = {};
var resetId = globalState.resetId;
var Transformer = (function (_super) {
__extends(Transformer, _super);
function Transformer(sourceIdentifier, sourceObject) {
_super.call(this, function () { return transformer(sourceObject); }, null, false, "Transformer-" + transformer.name + "-" + sourceIdentifier, undefined);
this.sourceIdentifier = sourceIdentifier;
this.sourceObject = sourceObject;
}
Transformer.prototype.onBecomeUnobserved = function () {
var lastValue = this.value;
_super.prototype.onBecomeUnobserved.call(this);
delete objectCache[this.sourceIdentifier];
if (onCleanup)
{ onCleanup(lastValue, this.sourceObject); }
};
return Transformer;
}(ComputedValue));
return function (object) {
if (resetId !== globalState.resetId) {
objectCache = {};
resetId = globalState.resetId;
}
var identifier = getMemoizationId(object);
var reactiveTransformer = objectCache[identifier];
if (reactiveTransformer)
{ return reactiveTransformer.get(); }
reactiveTransformer = objectCache[identifier] = new Transformer(identifier, object);
return reactiveTransformer.get();
};
}
exports.createTransformer = createTransformer;
function getMemoizationId(object) {
if (object === null || typeof object !== "object")
{ throw new Error("[mobx] transform expected some kind of object, got: " + object); }
var tid = object.$transformId;
if (tid === undefined) {
tid = getNextId();
addHiddenProp(object, "$transformId", tid);
}
return tid;
}
function expr(expr, scope) {
if (!isComputingDerivation())
{ console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."); }
return computed(expr, scope).get();
}
exports.expr = expr;
function extendObservable(target) {
var arguments$1 = arguments;
var properties = [];
for (var _i = 1; _i < arguments.length; _i++) {
properties[_i - 1] = arguments$1[_i];
}
invariant(arguments.length >= 2, "extendObservable expected 2 or more arguments");
invariant(typeof target === "object", "extendObservable expects an object as first argument");
invariant(!(isObservableMap(target)), "extendObservable should not be used on maps, use map.merge instead");
properties.forEach(function (propSet) {
invariant(typeof propSet === "object", "all arguments of extendObservable should be objects");
invariant(!isObservable(propSet), "extending an object with another observable (object) is not supported. Please construct an explicit propertymap, using `toJS` if need. See issue #540");
extendObservableHelper(target, propSet, ValueMode.Recursive, null);
});
return target;
}
exports.extendObservable = extendObservable;
function extendObservableHelper(target, properties, mode, name) {
var adm = asObservableObject(target, name, mode);
for (var key in properties)
{ if (hasOwnProperty(properties, key)) {
if (target === properties && !isPropertyConfigurable(target, key))
{ continue; }
var descriptor = Object.getOwnPropertyDescriptor(properties, key);
setObservableObjectInstanceProperty(adm, key, descriptor);
} }
return target;
}
function getDependencyTree(thing, property) {
return nodeToDependencyTree(getAtom(thing, property));
}
function nodeToDependencyTree(node) {
var result = {
name: node.name
};
if (node.observing && node.observing.length > 0)
{ result.dependencies = unique(node.observing).map(nodeToDependencyTree); }
return result;
}
function getObserverTree(thing, property) {
return nodeToObserverTree(getAtom(thing, property));
}
function nodeToObserverTree(node) {
var result = {
name: node.name
};
if (hasObservers(node))
{ result.observers = getObservers(node).map(nodeToObserverTree); }
return result;
}
function intercept(thing, propOrHandler, handler) {
if (typeof handler === "function")
{ return interceptProperty(thing, propOrHandler, handler); }
else
{ return interceptInterceptable(thing, propOrHandler); }
}
exports.intercept = intercept;
function interceptInterceptable(thing, handler) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
return getAdministration(observable(thing)).intercept(handler);
}
return getAdministration(thing).intercept(handler);
}
function interceptProperty(thing, property, handler) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
extendObservable(thing, {
property: thing[property]
});
return interceptProperty(thing, property, handler);
}
return getAdministration(thing, property).intercept(handler);
}
function isComputed(value, property) {
if (value === null || value === undefined)
{ return false; }
if (property !== undefined) {
if (isObservableObject(value) === false)
{ return false; }
var atom = getAtom(value, property);
return isComputedValue(atom);
}
return isComputedValue(value);
}
exports.isComputed = isComputed;
function isObservable(value, property) {
if (value === null || value === undefined)
{ return false; }
if (property !== undefined) {
if (isObservableArray(value) || isObservableMap(value))
{ throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead."); }
else if (isObservableObject(value)) {
var o = value.$mobx;
return o.values && !!o.values[property];
}
return false;
}
return !!value.$mobx || isAtom(value) || isReaction(value) || isComputedValue(value);
}
exports.isObservable = isObservable;
var decoratorImpl = createClassPropertyDecorator(function (target, name, baseValue) {
var prevA = allowStateChangesStart(true);
if (typeof baseValue === "function")
{ baseValue = asReference(baseValue); }
var adm = asObservableObject(target, undefined, ValueMode.Recursive);
defineObservableProperty(adm, name, baseValue, true, undefined);
allowStateChangesEnd(prevA);
}, function (name) {
var observable = this.$mobx.values[name];
if (observable === undefined)
{ return undefined; }
return observable.get();
}, function (name, value) {
setPropertyValue(this, name, value);
}, true, false);
function observableDecorator(target, key, baseDescriptor) {
invariant(arguments.length >= 2 && arguments.length <= 3, "Illegal decorator config", key);
assertPropertyConfigurable(target, key);
invariant(!baseDescriptor || !baseDescriptor.get, "@observable can not be used on getters, use @computed instead");
return decoratorImpl.apply(null, arguments);
}
function observable(v, keyOrScope) {
if (v === void 0) { v = undefined; }
if (typeof arguments[1] === "string")
{ return observableDecorator.apply(null, arguments); }
invariant(arguments.length < 3, "observable expects zero, one or two arguments");
if (isObservable(v))
{ return v; }
var _a = getValueModeFromValue(v, ValueMode.Recursive), mode = _a[0], value = _a[1];
var sourceType = mode === ValueMode.Reference ? ValueType.Reference : getTypeOfValue(value);
switch (sourceType) {
case ValueType.Array:
case ValueType.PlainObject:
return makeChildObservable(value, mode);
case ValueType.Reference:
case ValueType.ComplexObject:
return new ObservableValue(value, mode);
case ValueType.ComplexFunction:
throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");
case ValueType.ViewFunction:
deprecated("Use `computed(expr)` instead of `observable(expr)`");
return computed(v, keyOrScope);
}
invariant(false, "Illegal State");
}
exports.observable = observable;
var ValueType;
(function (ValueType) {
ValueType[ValueType["Reference"] = 0] = "Reference";
ValueType[ValueType["PlainObject"] = 1] = "PlainObject";
ValueType[ValueType["ComplexObject"] = 2] = "ComplexObject";
ValueType[ValueType["Array"] = 3] = "Array";
ValueType[ValueType["ViewFunction"] = 4] = "ViewFunction";
ValueType[ValueType["ComplexFunction"] = 5] = "ComplexFunction";
})(ValueType || (ValueType = {}));
function getTypeOfValue(value) {
if (value === null || value === undefined)
{ return ValueType.Reference; }
if (typeof value === "function")
{ return value.length ? ValueType.ComplexFunction : ValueType.ViewFunction; }
if (isArrayLike(value))
{ return ValueType.Array; }
if (typeof value === "object")
{ return isPlainObject(value) ? ValueType.PlainObject : ValueType.ComplexObject; }
return ValueType.Reference;
}
function observe(thing, propOrCb, cbOrFire, fireImmediately) {
if (typeof cbOrFire === "function")
{ return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately); }
else
{ return observeObservable(thing, propOrCb, cbOrFire); }
}
exports.observe = observe;
function observeObservable(thing, listener, fireImmediately) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
return getAdministration(observable(thing)).observe(listener, fireImmediately);
}
return getAdministration(thing).observe(listener, fireImmediately);
}
function observeObservableProperty(thing, property, listener, fireImmediately) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
extendObservable(thing, {
property: thing[property]
});
return observeObservableProperty(thing, property, listener, fireImmediately);
}
return getAdministration(thing, property).observe(listener, fireImmediately);
}
function toJS(source, detectCycles, __alreadySeen) {
if (detectCycles === void 0) { detectCycles = true; }
if (__alreadySeen === void 0) { __alreadySeen = null; }
function cache(value) {
if (detectCycles)
{ __alreadySeen.push([source, value]); }
return value;
}
if (isObservable(source)) {
if (detectCycles && __alreadySeen === null)
{ __alreadySeen = []; }
if (detectCycles && source !== null && typeof source === "object") {
for (var i = 0, l = __alreadySeen.length; i < l; i++)
{ if (__alreadySeen[i][0] === source)
{ return __alreadySeen[i][1]; } }
}
if (isObservableArray(source)) {
var res = cache([]);
var toAdd = source.map(function (value) { return toJS(value, detectCycles, __alreadySeen); });
res.length = toAdd.length;
for (var i = 0, l = toAdd.length; i < l; i++)
{ res[i] = toAdd[i]; }
return res;
}
if (isObservableObject(source)) {
var res = cache({});
for (var key in source)
{ res[key] = toJS(source[key], detectCycles, __alreadySeen); }
return res;
}
if (isObservableMap(source)) {
var res_1 = cache({});
source.forEach(function (value, key) { return res_1[key] = toJS(value, detectCycles, __alreadySeen); });
return res_1;
}
if (isObservableValue(source))
{ return toJS(source.get(), detectCycles, __alreadySeen); }
}
return source;
}
exports.toJS = toJS;
function toJSlegacy(source, detectCycles, __alreadySeen) {
if (detectCycles === void 0) { detectCycles = true; }
if (__alreadySeen === void 0) { __alreadySeen = null; }
deprecated("toJSlegacy is deprecated and will be removed in the next major. Use `toJS` instead. See #566");
function cache(value) {
if (detectCycles)
{ __alreadySeen.push([source, value]); }
return value;
}
if (source instanceof Date || source instanceof RegExp)
{ return source; }
if (detectCycles && __alreadySeen === null)
{ __alreadySeen = []; }
if (detectCycles && source !== null && typeof source === "object") {
for (var i = 0, l = __alreadySeen.length; i < l; i++)
{ if (__alreadySeen[i][0] === source)
{ return __alreadySeen[i][1]; } }
}
if (!source)
{ return source; }
if (isArrayLike(source)) {
var res = cache([]);
var toAdd = source.map(function (value) { return toJSlegacy(value, detectCycles, __alreadySeen); });
res.length = toAdd.length;
for (var i = 0, l = toAdd.length; i < l; i++)
{ res[i] = toAdd[i]; }
return res;
}
if (isObservableMap(source)) {
var res_2 = cache({});
source.forEach(function (value, key) { return res_2[key] = toJSlegacy(value, detectCycles, __alreadySeen); });
return res_2;
}
if (isObservableValue(source))
{ return toJSlegacy(source.get(), detectCycles, __alreadySeen); }
if (typeof source === "object") {
var res = cache({});
for (var key in source)
{ res[key] = toJSlegacy(source[key], detectCycles, __alreadySeen); }
return res;
}
return source;
}
exports.toJSlegacy = toJSlegacy;
function toJSON(source, detectCycles, __alreadySeen) {
if (detectCycles === void 0) { detectCycles = true; }
if (__alreadySeen === void 0) { __alreadySeen = null; }
deprecated("toJSON is deprecated. Use toJS instead");
return toJSlegacy.apply(null, arguments);
}
exports.toJSON = toJSON;
function log(msg) {
console.log(msg);
return msg;
}
function whyRun(thing, prop) {
switch (arguments.length) {
case 0:
thing = globalState.trackingDerivation;
if (!thing)
{ return log("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value."); }
break;
case 2:
thing = getAtom(thing, prop);
break;
}
thing = getAtom(thing);
if (isComputedValue(thing))
{ return log(thing.whyRun()); }
else if (isReaction(thing))
{ return log(thing.whyRun()); }
else
{ invariant(false, "whyRun can only be used on reactions and computed values"); }
}
exports.whyRun = whyRun;
function createAction(actionName, fn) {
invariant(typeof fn === "function", "`action` can only be invoked on functions");
invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'");
var res = function () {
return executeAction(actionName, fn, this, arguments);
};
res.isMobxAction = true;
return res;
}
function executeAction(actionName, fn, scope, args) {
invariant(!isComputedValue(globalState.trackingDerivation), "Computed values or transformers should not invoke actions or trigger other side effects");
var notifySpy = isSpyEnabled();
var startTime;
if (notifySpy) {
startTime = Date.now();
var l = (args && args.length) || 0;
var flattendArgs = new Array(l);
if (l > 0)
{ for (var i = 0; i < l; i++)
{ flattendArgs[i] = args[i]; } }
spyReportStart({
type: "action",
name: actionName,
fn: fn,
target: scope,
arguments: flattendArgs
});
}
var prevUntracked = untrackedStart();
transactionStart(actionName, scope, false);
var prevAllowStateChanges = allowStateChangesStart(true);
try {
return fn.apply(scope, args);
}
finally {
allowStateChangesEnd(prevAllowStateChanges);
transactionEnd(false);
untrackedEnd(prevUntracked);
if (notifySpy)
{ spyReportEnd({ time: Date.now() - startTime }); }
}
}
function useStrict(strict) {
if (arguments.length === 0) {
deprecated("`useStrict` without arguments is deprecated, use `isStrictModeEnabled()` instead");
return globalState.strictMode;
}
else {
invariant(globalState.trackingDerivation === null, "It is not allowed to set `useStrict` when a derivation is running");
globalState.strictMode = strict;
globalState.allowStateChanges = !strict;
}
}
exports.useStrict = useStrict;
function isStrictModeEnabled() {
return globalState.strictMode;
}
exports.isStrictModeEnabled = isStrictModeEnabled;
function allowStateChanges(allowStateChanges, func) {
var prev = allowStateChangesStart(allowStateChanges);
var res = func();
allowStateChangesEnd(prev);
return res;
}
function allowStateChangesStart(allowStateChanges) {
var prev = globalState.allowStateChanges;
globalState.allowStateChanges = allowStateChanges;
return prev;
}
function allowStateChangesEnd(prev) {
globalState.allowStateChanges = prev;
}
var BaseAtom = (function () {
function BaseAtom(name) {
if (name === void 0) { name = "Atom@" + getNextId(); }
this.name = name;
this.isPendingUnobservation = true;
this.observers = [];
this.observersIndexes = {};
this.diffValue = 0;
this.lastAccessedBy = 0;
this.lowestObserverState = IDerivationState.NOT_TRACKING;
}
BaseAtom.prototype.onBecomeUnobserved = function () {
};
BaseAtom.prototype.reportObserved = function () {
reportObserved(this);
};
BaseAtom.prototype.reportChanged = function () {
transactionStart("propagatingAtomChange", null, false);
propagateChanged(this);
transactionEnd(false);
};
BaseAtom.prototype.toString = function () {
return this.name;
};
return BaseAtom;
}());
exports.BaseAtom = BaseAtom;
var Atom = (function (_super) {
__extends(Atom, _super);
function Atom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {
if (name === void 0) { name = "Atom@" + getNextId(); }
if (onBecomeObservedHandler === void 0) { onBecomeObservedHandler = noop; }
if (onBecomeUnobservedHandler === void 0) { onBecomeUnobservedHandler = noop; }
_super.call(this, name);
this.name = name;
this.onBecomeObservedHandler = onBecomeObservedHandler;
this.onBecomeUnobservedHandler = onBecomeUnobservedHandler;
this.isPendingUnobservation = false;
this.isBeingTracked = false;
}
Atom.prototype.reportObserved = function () {
startBatch();
_super.prototype.reportObserved.call(this);
if (!this.isBeingTracked) {
this.isBeingTracked = true;
this.onBecomeObservedHandler();
}
endBatch();
return !!globalState.trackingDerivation;
};
Atom.prototype.onBecomeUnobserved = function () {
this.isBeingTracked = false;
this.onBecomeUnobservedHandler();
};
return Atom;
}(BaseAtom));
exports.Atom = Atom;
var isAtom = createInstanceofPredicate("Atom", BaseAtom);
var ComputedValue = (function () {
function ComputedValue(derivation, scope, compareStructural, name, setter) {
this.derivation = derivation;
this.scope = scope;
this.compareStructural = compareStructural;
this.dependenciesState = IDerivationState.NOT_TRACKING;
this.observing = [];
this.newObserving = null;
this.isPendingUnobservation = false;
this.observers = [];
this.observersIndexes = {};
this.diffValue = 0;
this.runId = 0;
this.lastAccessedBy = 0;
this.lowestObserverState = IDerivationState.UP_TO_DATE;
this.unboundDepsCount = 0;
this.__mapid = "#" + getNextId();
this.value = undefined;
this.isComputing = false;
this.isRunningSetter = false;
this.name = name || "ComputedValue@" + getNextId();
if (setter)
{ this.setter = createAction(name + "-setter", setter); }
}
ComputedValue.prototype.peek = function () {
this.isComputing = true;
var prevAllowStateChanges = allowStateChangesStart(false);
var res = this.derivation.call(this.scope);
allowStateChangesEnd(prevAllowStateChanges);
this.isComputing = false;
return res;
};
ComputedValue.prototype.peekUntracked = function () {
var hasError = true;
try {
var res = this.peek();
hasError = false;
return res;
}
finally {
if (hasError)
{ handleExceptionInDerivation(this); }
}
};
ComputedValue.prototype.onBecomeStale = function () {
propagateMaybeChanged(this);
};
ComputedValue.prototype.onBecomeUnobserved = function () {
invariant(this.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR only onBecomeUnobserved shouldn't be called twice in a row");
clearObserving(this);
this.value = undefined;
};
ComputedValue.prototype.get = function () {
invariant(!this.isComputing, "Cycle detected in computation " + this.name, this.derivation);
startBatch();
if (globalState.inBatch === 1) {
if (shouldCompute(this))
{ this.value = this.peekUntracked(); }
}
else {
reportObserved(this);
if (shouldCompute(this))
{ if (this.trackAndCompute())
{ propagateChangeConfirmed(this); } }
}
var result = this.value;
endBatch();
return result;
};
ComputedValue.prototype.recoverFromError = function () {
this.isComputing = false;
};
ComputedValue.prototype.set = function (value) {
if (this.setter) {
invariant(!this.isRunningSetter, "The setter of computed value '" + this.name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?");
this.isRunningSetter = true;
try {
this.setter.call(this.scope, value);
}
finally {
this.isRunningSetter = false;
}
}
else
{ invariant(false, "[ComputedValue '" + this.name + "'] It is not possible to assign a new value to a computed value."); }
};
ComputedValue.prototype.trackAndCompute = function () {
if (isSpyEnabled()) {
spyReport({
object: this,
type: "compute",
fn: this.derivation,
target: this.scope
});
}
var oldValue = this.value;
var newValue = this.value = trackDerivedFunction(this, this.peek);
return valueDidChange(this.compareStructural, newValue, oldValue);
};
ComputedValue.prototype.observe = function (listener, fireImmediately) {
var _this = this;
var firstTime = true;
var prevValue = undefined;
return autorun(function () {
var newValue = _this.get();
if (!firstTime || fireImmediately) {
var prevU = untrackedStart();
listener(newValue, prevValue);
untrackedEnd(prevU);
}
firstTime = false;
prevValue = newValue;
});
};
ComputedValue.prototype.toJSON = function () {
return this.get();
};
ComputedValue.prototype.toString = function () {
return this.name + "[" + this.derivation.toString() + "]";
};
ComputedValue.prototype.whyRun = function () {
var isTracking = Boolean(globalState.trackingDerivation);
var observing = unique(this.isComputing ? this.newObserving : this.observing).map(function (dep) { return dep.name; });
var observers = unique(getObservers(this).map(function (dep) { return dep.name; }));
return (("\nWhyRun? computation '" + this.name + "':\n * Running because: " + (isTracking ? "[active] the value of this computation is needed by a reaction" : this.isComputing ? "[get] The value of this computed was requested outside a reaction" : "[idle] not running at the moment") + "\n") +
(this.dependenciesState === IDerivationState.NOT_TRACKING
?
" * This computation is suspended (not in use by any reaction) and won't run automatically.\n\tDidn't expect this computation to be suspended at this point?\n\t 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n\t 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n"
:
" * This computation will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this.isComputing && isTracking) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n " + joinStrings(observers) + "\n"));
};
return ComputedValue;
}());
var isComputedValue = createInstanceofPredicate("ComputedValue", ComputedValue);
var IDerivationState;
(function (IDerivationState) {
IDerivationState[IDerivationState["NOT_TRACKING"] = -1] = "NOT_TRACKING";
IDerivationState[IDerivationState["UP_TO_DATE"] = 0] = "UP_TO_DATE";
IDerivationState[IDerivationState["POSSIBLY_STALE"] = 1] = "POSSIBLY_STALE";
IDerivationState[IDerivationState["STALE"] = 2] = "STALE";
})(IDerivationState || (IDerivationState = {}));
exports.IDerivationState = IDerivationState;
function shouldCompute(derivation) {
switch (derivation.dependenciesState) {
case IDerivationState.UP_TO_DATE: return false;
case IDerivationState.NOT_TRACKING:
case IDerivationState.STALE: return true;
case IDerivationState.POSSIBLY_STALE: {
var hasError = true;
var prevUntracked = untrackedStart();
try {
var obs = derivation.observing, l = obs.length;
for (var i = 0; i < l; i++) {
var obj = obs[i];
if (isComputedValue(obj)) {
obj.get();
if (derivation.dependenciesState === IDerivationState.STALE) {
hasError = false;
untrackedEnd(prevUntracked);
return true;
}
}
}
hasError = false;
changeDependenciesStateTo0(derivation);
untrackedEnd(prevUntracked);
return false;
}
finally {
if (hasError) {
changeDependenciesStateTo0(derivation);
}
}
}
}
}
function isComputingDerivation() {
return globalState.trackingDerivation !== null;
}
function checkIfStateModificationsAreAllowed() {
if (!globalState.allowStateChanges) {
invariant(false, globalState.strictMode
? "It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended"
: "It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects.");
}
}
function trackDerivedFunction(derivation, f) {
changeDependenciesStateTo0(derivation);
derivation.newObserving = new Array(derivation.observing.length + 100);
derivation.unboundDepsCount = 0;
derivation.runId = ++globalState.runId;
var prevTracking = globalState.trackingDerivation;
globalState.trackingDerivation = derivation;
var hasException = true;
var result;
try {
result = f.call(derivation);
hasException = false;
}
finally {
if (hasException) {
handleExceptionInDerivation(derivation);
}
else {
globalState.trackingDerivation = prevTracking;
bindDependencies(derivation);
}
}
return result;
}
function handleExceptionInDerivation(derivation) {
var message = ("[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. " +
"These functions should never throw exceptions as MobX will not always be able to recover from them. " +
("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '" + derivation.name + "'. ") +
"For more details see https://github.com/mobxjs/mobx/issues/462");
if (isSpyEnabled()) {
spyReport({
type: "error",
message: message
});
}
console.warn(message);
changeDependenciesStateTo0(derivation);
derivation.newObserving = null;
derivation.unboundDepsCount = 0;
derivation.recoverFromError();
endBatch();
resetGlobalState();
}
function bindDependencies(derivation) {
var prevObserving = derivation.observing;
var observing = derivation.observing = derivation.newObserving;
derivation.newObserving = null;
var i0 = 0, l = derivation.unboundDepsCount;
for (var i = 0; i < l; i++) {
var dep = observing[i];
if (dep.diffValue === 0) {
dep.diffValue = 1;
if (i0 !== i)
{ observing[i0] = dep; }
i0++;
}
}
observing.length = i0;
l = prevObserving.length;
while (l--) {
var dep = prevObserving[l];
if (dep.diffValue === 0) {
removeObserver(dep, derivation);
}
dep.diffValue = 0;
}
while (i0--) {
var dep = observing[i0];
if (dep.diffValue === 1) {
dep.diffValue = 0;
addObserver(dep, derivation);
}
}
}
function clearObserving(derivation) {
var obs = derivation.observing;
var i = obs.length;
while (i--)
{ removeObserver(obs[i], derivation); }
derivation.dependenciesState = IDerivationState.NOT_TRACKING;
obs.length = 0;
}
function untracked(action) {
var prev = untrackedStart();
var res = action();
untrackedEnd(prev);
return res;
}
exports.untracked = untracked;
function untrackedStart() {
var prev = globalState.trackingDerivation;
globalState.trackingDerivation = null;
return prev;
}
function untrackedEnd(prev) {
globalState.trackingDerivation = prev;
}
function changeDependenciesStateTo0(derivation) {
if (derivation.dependenciesState === IDerivationState.UP_TO_DATE)
{ return; }
derivation.dependenciesState = IDerivationState.UP_TO_DATE;
var obs = derivation.observing;
var i = obs.length;
while (i--)
{ obs[i].lowestObserverState = IDerivationState.UP_TO_DATE; }
}
var persistentKeys = ["mobxGuid", "resetId", "spyListeners", "strictMode", "runId"];
var MobXGlobals = (function () {
function MobXGlobals() {
this.version = 4;
this.trackingDerivation = null;
this.runId = 0;
this.mobxGuid = 0;
this.inTransaction = 0;
this.isRunningReactions = false;
this.inBatch = 0;
this.pendingUnobservations = [];
this.pendingReactions = [];
this.allowStateChanges = true;
this.strictMode = false;
this.resetId = 0;
this.spyListeners = [];
}
return MobXGlobals;
}());
var globalState = (function () {
var res = new MobXGlobals();
if (commonjsGlobal.__mobservableTrackingStack || commonjsGlobal.__mobservableViewStack)
{ throw new Error("[mobx] An incompatible version of mobservable is already loaded."); }
if (commonjsGlobal.__mobxGlobal && commonjsGlobal.__mobxGlobal.version !== res.version)
{ throw new Error("[mobx] An incompatible version of mobx is already loaded."); }
if (commonjsGlobal.__mobxGlobal)
{ return commonjsGlobal.__mobxGlobal; }
return commonjsGlobal.__mobxGlobal = res;
})();
function registerGlobals() {
}
function resetGlobalState() {
globalState.resetId++;
var defaultGlobals = new MobXGlobals();
for (var key in defaultGlobals)
{ if (persistentKeys.indexOf(key) === -1)
{ globalState[key] = defaultGlobals[key]; } }
globalState.allowStateChanges = !globalState.strictMode;
}
function hasObservers(observable) {
return observable.observers && observable.observers.length > 0;
}
function getObservers(observable) {
return observable.observers;
}
function invariantObservers(observable) {
var list = observable.observers;
var map = observable.observersIndexes;
var l = list.length;
for (var i = 0; i < l; i++) {
var id = list[i].__mapid;
if (i) {
invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list");
}
else {
invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldnt be held in map.");
}
}
invariant(list.length === 0 || Object.keys(map).length === list.length - 1, "INTERNAL ERROR there is no junk in map");
}
function addObserver(observable, node) {
var l = observable.observers.length;
if (l) {
observable.observersIndexes[node.__mapid] = l;
}
observable.observers[l] = node;
if (observable.lowestObserverState > node.dependenciesState)
{ observable.lowestObserverState = node.dependenciesState; }
}
function removeObserver(observable, node) {
if (observable.observers.length === 1) {
observable.observers.length = 0;
queueForUnobservation(observable);
}
else {
var list = observable.observers;
var map_1 = observable.observersIndexes;
var filler = list.pop();
if (filler !== node) {
var index = map_1[node.__mapid] || 0;
if (index) {
map_1[filler.__mapid] = index;
}
else {
delete map_1[filler.__mapid];
}
list[index] = filler;
}
delete map_1[node.__mapid];
}
}
function queueForUnobservation(observable) {
if (!observable.isPendingUnobservation) {
observable.isPendingUnobservation = true;
globalState.pendingUnobservations.push(observable);
}
}
function startBatch() {
globalState.inBatch++;
}
function endBatch() {
if (globalState.inBatch === 1) {
var list = globalState.pendingUnobservations;
for (var i = 0; i < list.length; i++) {
var observable_1 = list[i];
observable_1.isPendingUnobservation = false;
if (observable_1.observers.length === 0) {
observable_1.onBecomeUnobserved();
}
}
globalState.pendingUnobservations = [];
}
globalState.inBatch--;
}
function reportObserved(observable) {
var derivation = globalState.trackingDerivation;
if (derivation !== null) {
if (derivation.runId !== observable.lastAccessedBy) {
observable.lastAccessedBy = derivation.runId;
derivation.newObserving[derivation.unboundDepsCount++] = observable;
}
}
else if (observable.observers.length === 0) {
queueForUnobservation(observable);
}
}
function invariantLOS(observable, msg) {
var min = getObservers(observable).reduce(function (a, b) { return Math.min(a, b.dependenciesState); }, 2);
if (min >= observable.lowestObserverState)
{ return; }
throw new Error("lowestObserverState is wrong for " + msg + " because " + min + " < " + observable.lowestObserverState);
}
function propagateChanged(observable) {
if (observable.lowestObserverState === IDerivationState.STALE)
{ return; }
observable.lowestObserverState = IDerivationState.STALE;
var observers = observable.observers;
var i = observers.length;
while (i--) {
var d = observers[i];
if (d.dependenciesState === IDerivationState.UP_TO_DATE)
{ d.onBecomeStale(); }
d.dependenciesState = IDerivationState.STALE;
}
}
function propagateChangeConfirmed(observable) {
if (observable.lowestObserverState === IDerivationState.STALE)
{ return; }
observable.lowestObserverState = IDerivationState.STALE;
var observers = observable.observers;
var i = observers.length;
while (i--) {
var d = observers[i];
if (d.dependenciesState === IDerivationState.POSSIBLY_STALE)
{ d.dependenciesState = IDerivationState.STALE; }
else if (d.dependenciesState === IDerivationState.UP_TO_DATE)
{ observable.lowestObserverState = IDerivationState.UP_TO_DATE; }
}
}
function propagateMaybeChanged(observable) {
if (observable.lowestObserverState !== IDerivationState.UP_TO_DATE)
{ return; }
observable.lowestObserverState = IDerivationState.POSSIBLY_STALE;
var observers = observable.observers;
var i = observers.length;
while (i--) {
var d = observers[i];
if (d.dependenciesState === IDerivationState.UP_TO_DATE) {
d.dependenciesState = IDerivationState.POSSIBLY_STALE;
d.onBecomeStale();
}
}
}
var Reaction = (function () {
function Reaction(name, onInvalidate) {
if (name === void 0) { name = "Reaction@" + getNextId(); }
this.name = name;
this.onInvalidate = onInvalidate;
this.observing = [];
this.newObserving = [];
this.dependenciesState = IDerivationState.NOT_TRACKING;
this.diffValue = 0;
this.runId = 0;
this.unboundDepsCount = 0;
this.__mapid = "#" + getNextId();
this.isDisposed = false;
this._isScheduled = false;
this._isTrackPending = false;
this._isRunning = false;
}
Reaction.prototype.onBecomeStale = function () {
this.schedule();
};
Reaction.prototype.schedule = function () {
if (!this._isScheduled) {
this._isScheduled = true;
globalState.pendingReactions.push(this);
startBatch();
runReactions();
endBatch();
}
};
Reaction.prototype.isScheduled = function () {
return this._isScheduled;
};
Reaction.prototype.runReaction = function () {
if (!this.isDisposed) {
this._isScheduled = false;
if (shouldCompute(this)) {
this._isTrackPending = true;
this.onInvalidate();
if (this._isTrackPending && isSpyEnabled()) {
spyReport({
object: this,
type: "scheduled-reaction"
});
}
}
}
};
Reaction.prototype.track = function (fn) {
startBatch();
var notify = isSpyEnabled();
var startTime;
if (notify) {
startTime = Date.now();
spyReportStart({
object: this,
type: "reaction",
fn: fn
});
}
this._isRunning = true;
trackDerivedFunction(this, fn);
this._isRunning = false;
this._isTrackPending = false;
if (this.isDisposed) {
clearObserving(this);
}
if (notify) {
spyReportEnd({
time: Date.now() - startTime
});
}
endBatch();
};
Reaction.prototype.recoverFromError = function () {
this._isRunning = false;
this._isTrackPending = false;
};
Reaction.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
if (!this._isRunning) {
startBatch();
clearObserving(this);
endBatch();
}
}
};
Reaction.prototype.getDisposer = function () {
var r = this.dispose.bind(this);
r.$mobx = this;
return r;
};
Reaction.prototype.toString = function () {
return "Reaction[" + this.name + "]";
};
Reaction.prototype.whyRun = function () {
var observing = unique(this._isRunning ? this.newObserving : this.observing).map(function (dep) { return dep.name; });
return ("\nWhyRun? reaction '" + this.name + "':\n * Status: [" + (this.isDisposed ? "stopped" : this._isRunning ? "running" : this.isScheduled() ? "scheduled" : "idle") + "]\n * This reaction will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this._isRunning) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n");
};
return Reaction;
}());
exports.Reaction = Reaction;
var MAX_REACTION_ITERATIONS = 100;
var reactionScheduler = function (f) { return f(); };
function runReactions() {
if (globalState.isRunningReactions === true || globalState.inTransaction > 0)
{ return; }
reactionScheduler(runReactionsHelper);
}
function runReactionsHelper() {
globalState.isRunningReactions = true;
var allReactions = globalState.pendingReactions;
var iterations = 0;
while (allReactions.length > 0) {
if (++iterations === MAX_REACTION_ITERATIONS) {
resetGlobalState();
throw new Error(("Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations.")
+ (" Probably there is a cycle in the reactive function: " + allReactions[0]));
}
var remainingReactions = allReactions.splice(0);
for (var i = 0, l = remainingReactions.length; i < l; i++)
{ remainingReactions[i].runReaction(); }
}
globalState.isRunningReactions = false;
}
var isReaction = createInstanceofPredicate("Reaction", Reaction);
function setReactionScheduler(fn) {
var baseScheduler = reactionScheduler;
reactionScheduler = function (f) { return fn(function () { return baseScheduler(f); }); };
}
function isSpyEnabled() {
return !!globalState.spyListeners.length;
}
function spyReport(event) {
if (!globalState.spyListeners.length)
{ return false; }
var listeners = globalState.spyListeners;
for (var i = 0, l = listeners.length; i < l; i++)
{ listeners[i](event); }
}
function spyReportStart(event) {
var change = objectAssign({}, event, { spyReportStart: true });
spyReport(change);
}
var END_EVENT = { spyReportEnd: true };
function spyReportEnd(change) {
if (change)
{ spyReport(objectAssign({}, change, END_EVENT)); }
else
{ spyReport(END_EVENT); }
}
function spy(listener) {
globalState.spyListeners.push(listener);
return once(function () {
var idx = globalState.spyListeners.indexOf(listener);
if (idx !== -1)
{ globalState.spyListeners.splice(idx, 1); }
});
}
exports.spy = spy;
function trackTransitions(onReport) {
deprecated("trackTransitions is deprecated. Use mobx.spy instead");
if (typeof onReport === "boolean") {
deprecated("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first");
onReport = arguments[1];
}
if (!onReport) {
deprecated("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first");
return function () { };
}
return spy(onReport);
}
function transaction(action, thisArg, report) {
if (thisArg === void 0) { thisArg = undefined; }
if (report === void 0) { report = true; }
transactionStart((action.name) || "anonymous transaction", thisArg, report);
try {
return action.call(thisArg);
}
finally {
transactionEnd(report);
}
}
exports.transaction = transaction;
function transactionStart(name, thisArg, report) {
if (thisArg === void 0) { thisArg = undefined; }
if (report === void 0) { report = true; }
startBatch();
globalState.inTransaction += 1;
if (report && isSpyEnabled()) {
spyReportStart({
type: "transaction",
target: thisArg,
name: name
});
}
}
function transactionEnd(report) {
if (report === void 0) { report = true; }
if (--globalState.inTransaction === 0) {
runReactions();
}
if (report && isSpyEnabled())
{ spyReportEnd(); }
endBatch();
}
function hasInterceptors(interceptable) {
return (interceptable.interceptors && interceptable.interceptors.length > 0);
}
function registerInterceptor(interceptable, handler) {
var interceptors = interceptable.interceptors || (interceptable.interceptors = []);
interceptors.push(handler);
return once(function () {
var idx = interceptors.indexOf(handler);
if (idx !== -1)
{ interceptors.splice(idx, 1); }
});
}
function interceptChange(interceptable, change) {
var prevU = untrackedStart();
var interceptors = interceptable.interceptors;
for (var i = 0, l = interceptors.length; i < l; i++) {
change = interceptors[i](change);
invariant(!change || change.type, "Intercept handlers should return nothing or a change object");
if (!change)
{ return null; }
}
untrackedEnd(prevU);
return change;
}
function hasListeners(listenable) {
return listenable.changeListeners && listenable.changeListeners.length > 0;
}
function registerListener(listenable, handler) {
var listeners = listenable.changeListeners || (listenable.changeListeners = []);
listeners.push(handler);
return once(function () {
var idx = listeners.indexOf(handler);
if (idx !== -1)
{ listeners.splice(idx, 1); }
});
}
function notifyListeners(listenable, change) {
var prevU = untrackedStart();
var listeners = listenable.changeListeners;
if (!listeners)
{ return; }
listeners = listeners.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
if (Array.isArray(change)) {
listeners[i].apply(null, change);
}
else {
listeners[i](change);
}
}
untrackedEnd(prevU);
}
var ValueMode;
(function (ValueMode) {
ValueMode[ValueMode["Recursive"] = 0] = "Recursive";
ValueMode[ValueMode["Reference"] = 1] = "Reference";
ValueMode[ValueMode["Structure"] = 2] = "Structure";
ValueMode[ValueMode["Flat"] = 3] = "Flat";
})(ValueMode || (ValueMode = {}));
function withModifier(modifier, value) {
assertUnwrapped(value, "Modifiers are not allowed to be nested");
return {
mobxModifier: modifier,
value: value
};
}
function getModifier(value) {
if (value) {
return value.mobxModifier || null;
}
return null;
}
function asReference(value) {
return withModifier(ValueMode.Reference, value);
}
exports.asReference = asReference;
asReference.mobxModifier = ValueMode.Reference;
function asStructure(value) {
return withModifier(ValueMode.Structure, value);
}
exports.asStructure = asStructure;
asStructure.mobxModifier = ValueMode.Structure;
function asFlat(value) {
return withModifier(ValueMode.Flat, value);
}
exports.asFlat = asFlat;
asFlat.mobxModifier = ValueMode.Flat;
function asMap(data, modifierFunc) {
return map(data, modifierFunc);
}
exports.asMap = asMap;
function getValueModeFromValue(value, defaultMode) {
var mode = getModifier(value);
if (mode)
{ return [mode, value.value]; }
return [defaultMode, value];
}
function getValueModeFromModifierFunc(func) {
if (func === undefined)
{ return ValueMode.Recursive; }
var mod = getModifier(func);
invariant(mod !== null, "Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: " + func);
return mod;
}
function makeChildObservable(value, parentMode, name) {
var childMode;
if (isObservable(value))
{ return value; }
switch (parentMode) {
case ValueMode.Reference:
return value;
case ValueMode.Flat:
assertUnwrapped(value, "Items inside 'asFlat' cannot have modifiers");
childMode = ValueMode.Reference;
break;
case ValueMode.Structure:
assertUnwrapped(value, "Items inside 'asStructure' cannot have modifiers");
childMode = ValueMode.Structure;
break;
case ValueMode.Recursive:
_a = getValueModeFromValue(value, ValueMode.Recursive), childMode = _a[0], value = _a[1];
break;
default:
invariant(false, "Illegal State");
}
if (Array.isArray(value))
{ return createObservableArray(value, childMode, name); }
if (isPlainObject(value) && Object.isExtensible(value))
{ return extendObservableHelper(value, value, childMode, name); }
return value;
var _a;
}
function assertUnwrapped(value, message) {
if (getModifier(value) !== null)
{ throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. " + message); }
}
var safariPrototypeSetterInheritanceBug = (function () {
var v = false;
var p = {};
Object.defineProperty(p, "0", { set: function () { v = true; } });
Object.create(p)["0"] = 1;
return v === false;
})();
var OBSERVABLE_ARRAY_BUFFER_SIZE = 0;
var StubArray = (function () {
function StubArray() {
}
return StubArray;
}());
StubArray.prototype = [];
var ObservableArrayAdministration = (function () {
function ObservableArrayAdministration(name, mode, array, owned) {
this.mode = mode;
this.array = array;
this.owned = owned;
this.lastKnownLength = 0;
this.interceptors = null;
this.changeListeners = null;
this.atom = new BaseAtom(name || ("ObservableArray@" + getNextId()));
}
ObservableArrayAdministration.prototype.makeReactiveArrayItem = function (value) {
assertUnwrapped(value, "Array values cannot have modifiers");
if (this.mode === ValueMode.Flat || this.mode === ValueMode.Reference)
{ return value; }
return makeChildObservable(value, this.mode, this.atom.name + "[..]");
};
ObservableArrayAdministration.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
ObservableArrayAdministration.prototype.observe = function (listener, fireImmediately) {
if (fireImmediately === void 0) { fireImmediately = false; }
if (fireImmediately) {
listener({
object: this.array,
type: "splice",
index: 0,
added: this.values.slice(),
addedCount: this.values.length,
removed: [],
removedCount: 0
});
}
return registerListener(this, listener);
};
ObservableArrayAdministration.prototype.getArrayLength = function () {
this.atom.reportObserved();
return this.values.length;
};
ObservableArrayAdministration.prototype.setArrayLength = function (newLength) {
if (typeof newLength !== "number" || newLength < 0)
{ throw new Error("[mobx.array] Out of range: " + newLength); }
var currentLength = this.values.length;
if (newLength === currentLength)
{ return; }
else if (newLength > currentLength)
{ this.spliceWithArray(currentLength, 0, new Array(newLength - currentLength)); }
else
{ this.spliceWithArray(newLength, currentLength - newLength); }
};
ObservableArrayAdministration.prototype.updateArrayLength = function (oldLength, delta) {
if (oldLength !== this.lastKnownLength)
{ throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?"); }
this.lastKnownLength += delta;
if (delta > 0 && oldLength + delta + 1 > OBSERVABLE_ARRAY_BUFFER_SIZE)
{ reserveArrayBuffer(oldLength + delta + 1); }
};
ObservableArrayAdministration.prototype.spliceWithArray = function (index, deleteCount, newItems) {
checkIfStateModificationsAreAllowed();
var length = this.values.length;
if (index === undefined)
{ index = 0; }
else if (index > length)
{ index = length; }
else if (index < 0)
{ index = Math.max(0, length + index); }
if (arguments.length === 1)
{ deleteCount = length - index; }
else if (deleteCount === undefined || deleteCount === null)
{ deleteCount = 0; }
else
{ deleteCount = Math.max(0, Math.min(deleteCount, length - index)); }
if (newItems === undefined)
{ newItems = []; }
if (hasInterceptors(this)) {
var change = interceptChange(this, {
object: this.array,
type: "splice",
index: index,
removedCount: deleteCount,
added: newItems
});
if (!change)
{ return EMPTY_ARRAY; }
deleteCount = change.removedCount;
newItems = change.added;
}
newItems = newItems.map(this.makeReactiveArrayItem, this);
var lengthDelta = newItems.length - deleteCount;
this.updateArrayLength(length, lengthDelta);
var res = (_a = this.values).splice.apply(_a, [index, deleteCount].concat(newItems));
if (deleteCount !== 0 || newItems.length !== 0)
{ this.notifyArraySplice(index, newItems, res); }
return res;
var _a;
};
ObservableArrayAdministration.prototype.notifyArrayChildUpdate = function (index, newValue, oldValue) {
var notifySpy = !this.owned && isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
object: this.array,
type: "update",
index: index, newValue: newValue, oldValue: oldValue
} : null;
if (notifySpy)
{ spyReportStart(change); }
this.atom.reportChanged();
if (notify)
{ notifyListeners(this, change); }
if (notifySpy)
{ spyReportEnd(); }
};
ObservableArrayAdministration.prototype.notifyArraySplice = function (index, added, removed) {
var notifySpy = !this.owned && isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
object: this.array,
type: "splice",
index: index, removed: removed, added: added,
removedCount: removed.length,
addedCount: added.length
} : null;
if (notifySpy)
{ spyReportStart(change); }
this.atom.reportChanged();
if (notify)
{ notifyListeners(this, change); }
if (notifySpy)
{ spyReportEnd(); }
};
return ObservableArrayAdministration;
}());
var ObservableArray = (function (_super) {
__extends(ObservableArray, _super);
function ObservableArray(initialValues, mode, name, owned) {
if (owned === void 0) { owned = false; }
_super.call(this);
var adm = new ObservableArrayAdministration(name, mode, this, owned);
addHiddenFinalProp(this, "$mobx", adm);
if (initialValues && initialValues.length) {
adm.updateArrayLength(0, initialValues.length);
adm.values = initialValues.map(adm.makeReactiveArrayItem, adm);
adm.notifyArraySplice(0, adm.values.slice(), EMPTY_ARRAY);
}
else {
adm.values = [];
}
if (safariPrototypeSetterInheritanceBug) {
Object.defineProperty(adm.array, "0", ENTRY_0);
}
}
ObservableArray.prototype.intercept = function (handler) {
return this.$mobx.intercept(handler);
};
ObservableArray.prototype.observe = function (listener, fireImmediately) {
if (fireImmediately === void 0) { fireImmediately = false; }
return this.$mobx.observe(listener, fireImmediately);
};
ObservableArray.prototype.clear = function () {
return this.splice(0);
};
ObservableArray.prototype.concat = function () {
var arguments$1 = arguments;
var arrays = [];
for (var _i = 0; _i < arguments.length; _i++) {
arrays[_i - 0] = arguments$1[_i];
}
this.$mobx.atom.reportObserved();
return Array.prototype.concat.apply(this.slice(), arrays.map(function (a) { return isObservableArray(a) ? a.slice() : a; }));
};
ObservableArray.prototype.replace = function (newItems) {
return this.$mobx.spliceWithArray(0, this.$mobx.values.length, newItems);
};
ObservableArray.prototype.toJS = function () {
return this.slice();
};
ObservableArray.prototype.toJSON = function () {
return this.toJS();
};
ObservableArray.prototype.peek = function () {
return this.$mobx.values;
};
ObservableArray.prototype.find = function (predicate, thisArg, fromIndex) {
var this$1 = this;
if (fromIndex === void 0) { fromIndex = 0; }
this.$mobx.atom.reportObserved();
var items = this.$mobx.values, l = items.length;
for (var i = fromIndex; i < l; i++)
{ if (predicate.call(thisArg, items[i], i, this$1))
{ return items[i]; } }
return undefined;
};
ObservableArray.prototype.splice = function (index, deleteCount) {
var arguments$1 = arguments;
var newItems = [];
for (var _i = 2; _i < arguments.length; _i++) {
newItems[_i - 2] = arguments$1[_i];
}
switch (arguments.length) {
case 0:
return [];
case 1:
return this.$mobx.spliceWithArray(index);
case 2:
return this.$mobx.spliceWithArray(index, deleteCount);
}
return this.$mobx.spliceWithArray(index, deleteCount, newItems);
};
ObservableArray.prototype.push = function () {
var arguments$1 = arguments;
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i - 0] = arguments$1[_i];
}
var adm = this.$mobx;
adm.spliceWithArray(adm.values.length, 0, items);
return adm.values.length;
};
ObservableArray.prototype.pop = function () {
return this.splice(Math.max(this.$mobx.values.length - 1, 0), 1)[0];
};
ObservableArray.prototype.shift = function () {
return this.splice(0, 1)[0];
};
ObservableArray.prototype.unshift = function () {
var arguments$1 = arguments;
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i - 0] = arguments$1[_i];
}
var adm = this.$mobx;
adm.spliceWithArray(0, 0, items);
return adm.values.length;
};
ObservableArray.prototype.reverse = function () {
this.$mobx.atom.reportObserved();
var clone = this.slice();
return clone.reverse.apply(clone, arguments);
};
ObservableArray.prototype.sort = function (compareFn) {
this.$mobx.atom.reportObserved();
var clone = this.slice();
return clone.sort.apply(clone, arguments);
};
ObservableArray.prototype.remove = function (value) {
var idx = this.$mobx.values.indexOf(value);
if (idx > -1) {
this.splice(idx, 1);
return true;
}
return false;
};
ObservableArray.prototype.toString = function () {
return "[mobx.array] " + Array.prototype.toString.apply(this.$mobx.values, arguments);
};
ObservableArray.prototype.toLocaleString = function () {
return "[mobx.array] " + Array.prototype.toLocaleString.apply(this.$mobx.values, arguments);
};
return ObservableArray;
}(StubArray));
declareIterator(ObservableArray.prototype, function () {
return arrayAsIterator(this.slice());
});
makeNonEnumerable(ObservableArray.prototype, [
"constructor",
"intercept",
"observe",
"clear",
"concat",
"replace",
"toJS",
"toJSON",
"peek",
"find",
"splice",
"push",
"pop",
"shift",
"unshift",
"reverse",
"sort",
"remove",
"toString",
"toLocaleString"
]);
Object.defineProperty(ObservableArray.prototype, "length", {
enumerable: false,
configurable: true,
get: function () {
return this.$mobx.getArrayLength();
},
set: function (newLength) {
this.$mobx.setArrayLength(newLength);
}
});
[
"every",
"filter",
"forEach",
"indexOf",
"join",
"lastIndexOf",
"map",
"reduce",
"reduceRight",
"slice",
"some"
].forEach(function (funcName) {
var baseFunc = Array.prototype[funcName];
invariant(typeof baseFunc === "function", "Base function not defined on Array prototype: '" + funcName + "'");
addHiddenProp(ObservableArray.prototype, funcName, function () {
this.$mobx.atom.reportObserved();
return baseFunc.apply(this.$mobx.values, arguments);
});
});
var ENTRY_0 = {
configurable: true,
enumerable: false,
set: createArraySetter(0),
get: createArrayGetter(0)
};
function createArrayBufferItem(index) {
var set = createArraySetter(index);
var get = createArrayGetter(index);
Object.defineProperty(ObservableArray.prototype, "" + index, {
enumerable: false,
configurable: true,
set: set, get: get
});
}
function createArraySetter(index) {
return function (newValue) {
var adm = this.$mobx;
var values = adm.values;
assertUnwrapped(newValue, "Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array)).");
if (index < values.length) {
checkIfStateModificationsAreAllowed();
var oldValue = values[index];
if (hasInterceptors(adm)) {
var change = interceptChange(adm, {
type: "update",
object: adm.array,
index: index, newValue: newValue
});
if (!change)
{ return; }
newValue = change.newValue;
}
newValue = adm.makeReactiveArrayItem(newValue);
var changed = (adm.mode === ValueMode.Structure) ? !deepEquals(oldValue, newValue) : oldValue !== newValue;
if (changed) {
values[index] = newValue;
adm.notifyArrayChildUpdate(index, newValue, oldValue);
}
}
else if (index === values.length) {
adm.spliceWithArray(index, 0, [newValue]);
}
else
{ throw new Error("[mobx.array] Index out of bounds, " + index + " is larger than " + values.length); }
};
}
function createArrayGetter(index) {
return function () {
var impl = this.$mobx;
if (impl && index < impl.values.length) {
impl.atom.reportObserved();
return impl.values[index];
}
console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + impl.values.length + "). Please check length first. Out of bound indices will not be tracked by MobX");
return undefined;
};
}
function reserveArrayBuffer(max) {
for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max; index++)
{ createArrayBufferItem(index); }
OBSERVABLE_ARRAY_BUFFER_SIZE = max;
}
reserveArrayBuffer(1000);
function createObservableArray(initialValues, mode, name) {
return new ObservableArray(initialValues, mode, name);
}
function fastArray(initialValues) {
deprecated("fastArray is deprecated. Please use `observable(asFlat([]))`");
return createObservableArray(initialValues, ValueMode.Flat, null);
}
exports.fastArray = fastArray;
var isObservableArrayAdministration = createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration);
function isObservableArray(thing) {
return isObject(thing) && isObservableArrayAdministration(thing.$mobx);
}
exports.isObservableArray = isObservableArray;
var ObservableMapMarker = {};
var ObservableMap = (function () {
function ObservableMap(initialData, valueModeFunc) {
var _this = this;
this.$mobx = ObservableMapMarker;
this._data = {};
this._hasMap = {};
this.name = "ObservableMap@" + getNextId();
this._keys = new ObservableArray(null, ValueMode.Reference, this.name + ".keys()", true);
this.interceptors = null;
this.changeListeners = null;
this._valueMode = getValueModeFromModifierFunc(valueModeFunc);
if (this._valueMode === ValueMode.Flat)
{ this._valueMode = ValueMode.Reference; }
allowStateChanges(true, function () {
if (isPlainObject(initialData))
{ _this.merge(initialData); }
else if (Array.isArray(initialData))
{ initialData.forEach(function (_a) {
var key = _a[0], value = _a[1];
return _this.set(key, value);
}); }
});
}
ObservableMap.prototype._has = function (key) {
return typeof this._data[key] !== "undefined";
};
ObservableMap.prototype.has = function (key) {
if (!this.isValidKey(key))
{ return false; }
key = "" + key;
if (this._hasMap[key])
{ return this._hasMap[key].get(); }
return this._updateHasMapEntry(key, false).get();
};
ObservableMap.prototype.set = function (key, value) {
this.assertValidKey(key);
key = "" + key;
var hasKey = this._has(key);
assertUnwrapped(value, "[mobx.map.set] Expected unwrapped value to be inserted to key '" + key + "'. If you need to use modifiers pass them as second argument to the constructor");
if (hasInterceptors(this)) {
var change = interceptChange(this, {
type: hasKey ? "update" : "add",
object: this,
newValue: value,
name: key
});
if (!change)
{ return; }
value = change.newValue;
}
if (hasKey) {
this._updateValue(key, value);
}
else {
this._addValue(key, value);
}
};
ObservableMap.prototype.delete = function (key) {
var _this = this;
this.assertValidKey(key);
key = "" + key;
if (hasInterceptors(this)) {
var change = interceptChange(this, {
type: "delete",
object: this,
name: key
});
if (!change)
{ return false; }
}
if (this._has(key)) {
var notifySpy = isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
type: "delete",
object: this,
oldValue: this._data[key].value,
name: key
} : null;
if (notifySpy)
{ spyReportStart(change); }
transaction(function () {
_this._keys.remove(key);
_this._updateHasMapEntry(key, false);
var observable = _this._data[key];
observable.setNewValue(undefined);
_this._data[key] = undefined;
}, undefined, false);
if (notify)
{ notifyListeners(this, change); }
if (notifySpy)
{ spyReportEnd(); }
return true;
}
return false;
};
ObservableMap.prototype._updateHasMapEntry = function (key, value) {
var entry = this._hasMap[key];
if (entry) {
entry.setNewValue(value);
}
else {
entry = this._hasMap[key] = new ObservableValue(value, ValueMode.Reference, this.name + "." + key + "?", false);
}
return entry;
};
ObservableMap.prototype._updateValue = function (name, newValue) {
var observable = this._data[name];
newValue = observable.prepareNewValue(newValue);
if (newValue !== UNCHANGED) {
var notifySpy = isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
type: "update",
object: this,
oldValue: observable.value,
name: name, newValue: newValue
} : null;
if (notifySpy)
{ spyReportStart(change); }
observable.setNewValue(newValue);
if (notify)
{ notifyListeners(this, change); }
if (notifySpy)
{ spyReportEnd(); }
}
};
ObservableMap.prototype._addValue = function (name, newValue) {
var _this = this;
transaction(function () {
var observable = _this._data[name] = new ObservableValue(newValue, _this._valueMode, _this.name + "." + name, false);
newValue = observable.value;
_this._updateHasMapEntry(name, true);
_this._keys.push(name);
}, undefined, false);
var notifySpy = isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
type: "add",
object: this,
name: name, newValue: newValue
} : null;
if (notifySpy)
{ spyReportStart(change); }
if (notify)
{ notifyListeners(this, change); }
if (notifySpy)
{ spyReportEnd(); }
};
ObservableMap.prototype.get = function (key) {
key = "" + key;
if (this.has(key))
{ return this._data[key].get(); }
return undefined;
};
ObservableMap.prototype.keys = function () {
return arrayAsIterator(this._keys.slice());
};
ObservableMap.prototype.values = function () {
return arrayAsIterator(this._keys.map(this.get, this));
};
ObservableMap.prototype.entries = function () {
var _this = this;
return arrayAsIterator(this._keys.map(function (key) { return [key, _this.get(key)]; }));
};
ObservableMap.prototype.forEach = function (callback, thisArg) {
var _this = this;
this.keys().forEach(function (key) { return callback.call(thisArg, _this.get(key), key); });
};
ObservableMap.prototype.merge = function (other) {
var _this = this;
transaction(function () {
if (isObservableMap(other))
{ other.keys().forEach(function (key) { return _this.set(key, other.get(key)); }); }
else
{ Object.keys(other).forEach(function (key) { return _this.set(key, other[key]); }); }
}, undefined, false);
return this;
};
ObservableMap.prototype.clear = function () {
var _this = this;
transaction(function () {
untracked(function () {
_this.keys().forEach(_this.delete, _this);
});
}, undefined, false);
};
Object.defineProperty(ObservableMap.prototype, "size", {
get: function () {
return this._keys.length;
},
enumerable: true,
configurable: true
});
ObservableMap.prototype.toJS = function () {
var _this = this;
var res = {};
this.keys().forEach(function (key) { return res[key] = _this.get(key); });
return res;
};
ObservableMap.prototype.toJs = function () {
deprecated("toJs is deprecated, use toJS instead");
return this.toJS();
};
ObservableMap.prototype.toJSON = function () {
return this.toJS();
};
ObservableMap.prototype.isValidKey = function (key) {
if (key === null || key === undefined)
{ return false; }
if (typeof key !== "string" && typeof key !== "number" && typeof key !== "boolean")
{ return false; }
return true;
};
ObservableMap.prototype.assertValidKey = function (key) {
if (!this.isValidKey(key))
{ throw new Error("[mobx.map] Invalid key: '" + key + "'"); }
};
ObservableMap.prototype.toString = function () {
var _this = this;
return this.name + "[{ " + this.keys().map(function (key) { return (key + ": " + ("" + _this.get(key))); }).join(", ") + " }]";
};
ObservableMap.prototype.observe = function (listener, fireImmediately) {
invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable maps.");
return registerListener(this, listener);
};
ObservableMap.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
return ObservableMap;
}());
exports.ObservableMap = ObservableMap;
declareIterator(ObservableMap.prototype, function () {
return this.entries();
});
function map(initialValues, valueModifier) {
return new ObservableMap(initialValues, valueModifier);
}
exports.map = map;
var isObservableMap = createInstanceofPredicate("ObservableMap", ObservableMap);
exports.isObservableMap = isObservableMap;
var ObservableObjectAdministration = (function () {
function ObservableObjectAdministration(target, name, mode) {
this.target = target;
this.name = name;
this.mode = mode;
this.values = {};
this.changeListeners = null;
this.interceptors = null;
}
ObservableObjectAdministration.prototype.observe = function (callback, fireImmediately) {
invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects.");
return registerListener(this, callback);
};
ObservableObjectAdministration.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
return ObservableObjectAdministration;
}());
function asObservableObject(target, name, mode) {
if (mode === void 0) { mode = ValueMode.Recursive; }
if (isObservableObject(target))
{ return target.$mobx; }
if (!isPlainObject(target))
{ name = target.constructor.name + "@" + getNextId(); }
if (!name)
{ name = "ObservableObject@" + getNextId(); }
var adm = new ObservableObjectAdministration(target, name, mode);
addHiddenFinalProp(target, "$mobx", adm);
return adm;
}
function setObservableObjectInstanceProperty(adm, propName, descriptor) {
if (adm.values[propName]) {
invariant("value" in descriptor, "cannot redefine property " + propName);
adm.target[propName] = descriptor.value;
}
else {
if ("value" in descriptor)
{ defineObservableProperty(adm, propName, descriptor.value, true, undefined); }
else
{ defineObservableProperty(adm, propName, descriptor.get, true, descriptor.set); }
}
}
function defineObservableProperty(adm, propName, newValue, asInstanceProperty, setter) {
if (asInstanceProperty)
{ assertPropertyConfigurable(adm.target, propName); }
var observable;
var name = adm.name + "." + propName;
var isComputed = true;
if (isComputedValue(newValue)) {
observable = newValue;
newValue.name = name;
if (!newValue.scope)
{ newValue.scope = adm.target; }
}
else if (typeof newValue === "function" && newValue.length === 0 && !isAction(newValue)) {
observable = new ComputedValue(newValue, adm.target, false, name, setter);
}
else if (getModifier(newValue) === ValueMode.Structure && typeof newValue.value === "function" && newValue.value.length === 0) {
observable = new ComputedValue(newValue.value, adm.target, true, name, setter);
}
else {
isComputed = false;
if (hasInterceptors(adm)) {
var change = interceptChange(adm, {
object: adm.target,
name: propName,
type: "add",
newValue: newValue
});
if (!change)
{ return; }
newValue = change.newValue;
}
observable = new ObservableValue(newValue, adm.mode, name, false);
newValue = observable.value;
}
adm.values[propName] = observable;
if (asInstanceProperty) {
Object.defineProperty(adm.target, propName, isComputed ? generateComputedPropConfig(propName) : generateObservablePropConfig(propName));
}
if (!isComputed)
{ notifyPropertyAddition(adm, adm.target, propName, newValue); }
}
var observablePropertyConfigs = {};
var computedPropertyConfigs = {};
function generateObservablePropConfig(propName) {
var config = observablePropertyConfigs[propName];
if (config)
{ return config; }
return observablePropertyConfigs[propName] = {
configurable: true,
enumerable: true,
get: function () {
return this.$mobx.values[propName].get();
},
set: function (v) {
setPropertyValue(this, propName, v);
}
};
}
function generateComputedPropConfig(propName) {
var config = computedPropertyConfigs[propName];
if (config)
{ return config; }
return computedPropertyConfigs[propName] = {
configurable: true,
enumerable: false,
get: function () {
return this.$mobx.values[propName].get();
},
set: function (v) {
return this.$mobx.values[propName].set(v);
}
};
}
function setPropertyValue(instance, name, newValue) {
var adm = instance.$mobx;
var observable = adm.values[name];
if (hasInterceptors(adm)) {
var change = interceptChange(adm, {
type: "update",
object: instance,
name: name, newValue: newValue
});
if (!change)
{ return; }
newValue = change.newValue;
}
newValue = observable.prepareNewValue(newValue);
if (newValue !== UNCHANGED) {
var notify = hasListeners(adm);
var notifySpy = isSpyEnabled();
var change = notify || notifySpy ? {
type: "update",
object: instance,
oldValue: observable.value,
name: name, newValue: newValue
} : null;
if (notifySpy)
{ spyReportStart(change); }
observable.setNewValue(newValue);
if (notify)
{ notifyListeners(adm, change); }
if (notifySpy)
{ spyReportEnd(); }
}
}
function notifyPropertyAddition(adm, object, name, newValue) {
var notify = hasListeners(adm);
var notifySpy = isSpyEnabled();
var change = notify || notifySpy ? {
type: "add",
object: object, name: name, newValue: newValue
} : null;
if (notifySpy)
{ spyReportStart(change); }
if (notify)
{ notifyListeners(adm, change); }
if (notifySpy)
{ spyReportEnd(); }
}
var isObservableObjectAdministration = createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration);
function isObservableObject(thing) {
if (isObject(thing)) {
runLazyInitializers(thing);
return isObservableObjectAdministration(thing.$mobx);
}
return false;
}
exports.isObservableObject = isObservableObject;
var UNCHANGED = {};
var ObservableValue = (function (_super) {
__extends(ObservableValue, _super);
function ObservableValue(value, mode, name, notifySpy) {
if (name === void 0) { name = "ObservableValue@" + getNextId(); }
if (notifySpy === void 0) { notifySpy = true; }
_super.call(this, name);
this.mode = mode;
this.hasUnreportedChange = false;
this.value = undefined;
var _a = getValueModeFromValue(value, ValueMode.Recursive), childmode = _a[0], unwrappedValue = _a[1];
if (this.mode === ValueMode.Recursive)
{ this.mode = childmode; }
this.value = makeChildObservable(unwrappedValue, this.mode, this.name);
if (notifySpy && isSpyEnabled()) {
spyReport({ type: "create", object: this, newValue: this.value });
}
}
ObservableValue.prototype.set = function (newValue) {
var oldValue = this.value;
newValue = this.prepareNewValue(newValue);
if (newValue !== UNCHANGED) {
var notifySpy = isSpyEnabled();
if (notifySpy) {
spyReportStart({
type: "update",
object: this,
newValue: newValue, oldValue: oldValue
});
}
this.setNewValue(newValue);
if (notifySpy)
{ spyReportEnd(); }
}
};
ObservableValue.prototype.prepareNewValue = function (newValue) {
assertUnwrapped(newValue, "Modifiers cannot be used on non-initial values.");
checkIfStateModificationsAreAllowed();
if (hasInterceptors(this)) {
var change = interceptChange(this, { object: this, type: "update", newValue: newValue });
if (!change)
{ return UNCHANGED; }
newValue = change.newValue;
}
var changed = valueDidChange(this.mode === ValueMode.Structure, this.value, newValue);
if (changed)
{ return makeChildObservable(newValue, this.mode, this.name); }
return UNCHANGED;
};
ObservableValue.prototype.setNewValue = function (newValue) {
var oldValue = this.value;
this.value = newValue;
this.reportChanged();
if (hasListeners(this))
{ notifyListeners(this, [newValue, oldValue]); }
};
ObservableValue.prototype.get = function () {
this.reportObserved();
return this.value;
};
ObservableValue.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
ObservableValue.prototype.observe = function (listener, fireImmediately) {
if (fireImmediately)
{ listener(this.value, undefined); }
return registerListener(this, listener);
};
ObservableValue.prototype.toJSON = function () {
return this.get();
};
ObservableValue.prototype.toString = function () {
return this.name + "[" + this.value + "]";
};
return ObservableValue;
}(BaseAtom));
var isObservableValue = createInstanceofPredicate("ObservableValue", ObservableValue);
function getAtom(thing, property) {
if (typeof thing === "object" && thing !== null) {
if (isObservableArray(thing)) {
invariant(property === undefined, "It is not possible to get index atoms from arrays");
return thing.$mobx.atom;
}
if (isObservableMap(thing)) {
if (property === undefined)
{ return getAtom(thing._keys); }
var observable_2 = thing._data[property] || thing._hasMap[property];
invariant(!!observable_2, "the entry '" + property + "' does not exist in the observable map '" + getDebugName(thing) + "'");
return observable_2;
}
runLazyInitializers(thing);
if (isObservableObject(thing)) {
invariant(!!property, "please specify a property");
var observable_3 = thing.$mobx.values[property];
invariant(!!observable_3, "no observable property '" + property + "' found on the observable object '" + getDebugName(thing) + "'");
return observable_3;
}
if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {
return thing;
}
}
else if (typeof thing === "function") {
if (isReaction(thing.$mobx)) {
return thing.$mobx;
}
}
invariant(false, "Cannot obtain atom from " + thing);
}
function getAdministration(thing, property) {
invariant(thing, "Expecting some object");
if (property !== undefined)
{ return getAdministration(getAtom(thing, property)); }
if (isAtom(thing) || isComputedValue(thing) || isReaction(thing))
{ return thing; }
if (isObservableMap(thing))
{ return thing; }
runLazyInitializers(thing);
if (thing.$mobx)
{ return thing.$mobx; }
invariant(false, "Cannot obtain administration from " + thing);
}
function getDebugName(thing, property) {
var named;
if (property !== undefined)
{ named = getAtom(thing, property); }
else if (isObservableObject(thing) || isObservableMap(thing))
{ named = getAdministration(thing); }
else
{ named = getAtom(thing); }
return named.name;
}
function createClassPropertyDecorator(onInitialize, get, set, enumerable, allowCustomArguments) {
function classPropertyDecorator(target, key, descriptor, customArgs, argLen) {
invariant(allowCustomArguments || quacksLikeADecorator(arguments), "This function is a decorator, but it wasn't invoked like a decorator");
if (!descriptor) {
var newDescriptor = {
enumerable: enumerable,
configurable: true,
get: function () {
if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true)
{ typescriptInitializeProperty(this, key, undefined, onInitialize, customArgs, descriptor); }
return get.call(this, key);
},
set: function (v) {
if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true) {
typescriptInitializeProperty(this, key, v, onInitialize, customArgs, descriptor);
}
else {
set.call(this, key, v);
}
}
};
if (arguments.length < 3 || arguments.length === 5 && argLen < 3) {
Object.defineProperty(target, key, newDescriptor);
}
return newDescriptor;
}
else {
if (!hasOwnProperty(target, "__mobxLazyInitializers")) {
addHiddenProp(target, "__mobxLazyInitializers", (target.__mobxLazyInitializers && target.__mobxLazyInitializers.slice()) || []);
}
var value_1 = descriptor.value, initializer_1 = descriptor.initializer;
target.__mobxLazyInitializers.push(function (instance) {
onInitialize(instance, key, (initializer_1 ? initializer_1.call(instance) : value_1), customArgs, descriptor);
});
return {
enumerable: enumerable, configurable: true,
get: function () {
if (this.__mobxDidRunLazyInitializers !== true)
{ runLazyInitializers(this); }
return get.call(this, key);
},
set: function (v) {
if (this.__mobxDidRunLazyInitializers !== true)
{ runLazyInitializers(this); }
set.call(this, key, v);
}
};
}
}
if (allowCustomArguments) {
return function () {
if (quacksLikeADecorator(arguments))
{ return classPropertyDecorator.apply(null, arguments); }
var outerArgs = arguments;
var argLen = arguments.length;
return function (target, key, descriptor) { return classPropertyDecorator(target, key, descriptor, outerArgs, argLen); };
};
}
return classPropertyDecorator;
}
function typescriptInitializeProperty(instance, key, v, onInitialize, customArgs, baseDescriptor) {
if (!hasOwnProperty(instance, "__mobxInitializedProps"))
{ addHiddenProp(instance, "__mobxInitializedProps", {}); }
instance.__mobxInitializedProps[key] = true;
onInitialize(instance, key, v, customArgs, baseDescriptor);
}
function runLazyInitializers(instance) {
if (instance.__mobxDidRunLazyInitializers === true)
{ return; }
if (instance.__mobxLazyInitializers) {
addHiddenProp(instance, "__mobxDidRunLazyInitializers", true);
instance.__mobxDidRunLazyInitializers && instance.__mobxLazyInitializers.forEach(function (initializer) { return initializer(instance); });
}
}
function quacksLikeADecorator(args) {
return (args.length === 2 || args.length === 3) && typeof args[1] === "string";
}
function iteratorSymbol() {
return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator";
}
var IS_ITERATING_MARKER = "__$$iterating";
function arrayAsIterator(array) {
invariant(array[IS_ITERATING_MARKER] !== true, "Illegal state: cannot recycle array as iterator");
addHiddenFinalProp(array, IS_ITERATING_MARKER, true);
var idx = -1;
addHiddenFinalProp(array, "next", function next() {
idx++;
return {
done: idx >= this.length,
value: idx < this.length ? this[idx] : undefined
};
});
return array;
}
function declareIterator(prototType, iteratorFactory) {
addHiddenFinalProp(prototType, iteratorSymbol(), iteratorFactory);
}
var SimpleEventEmitter = (function () {
function SimpleEventEmitter() {
this.listeners = [];
deprecated("extras.SimpleEventEmitter is deprecated and will be removed in the next major release");
}
SimpleEventEmitter.prototype.emit = function () {
var arguments$1 = arguments;
var listeners = this.listeners.slice();
for (var i = 0, l = listeners.length; i < l; i++)
{ listeners[i].apply(null, arguments$1); }
};
SimpleEventEmitter.prototype.on = function (listener) {
var _this = this;
this.listeners.push(listener);
return once(function () {
var idx = _this.listeners.indexOf(listener);
if (idx !== -1)
{ _this.listeners.splice(idx, 1); }
});
};
SimpleEventEmitter.prototype.once = function (listener) {
var subscription = this.on(function () {
subscription();
listener.apply(this, arguments);
});
return subscription;
};
return SimpleEventEmitter;
}());
exports.SimpleEventEmitter = SimpleEventEmitter;
var EMPTY_ARRAY = [];
Object.freeze(EMPTY_ARRAY);
function getNextId() {
return ++globalState.mobxGuid;
}
function invariant(check, message, thing) {
if (!check)
{ throw new Error("[mobx] Invariant failed: " + message + (thing ? " in '" + thing + "'" : "")); }
}
var deprecatedMessages = [];
function deprecated(msg) {
if (deprecatedMessages.indexOf(msg) !== -1)
{ return; }
deprecatedMessages.push(msg);
console.error("[mobx] Deprecated: " + msg);
}
function once(func) {
var invoked = false;
return function () {
if (invoked)
{ return; }
invoked = true;
return func.apply(this, arguments);
};
}
var noop = function () { };
function unique(list) {
var res = [];
list.forEach(function (item) {
if (res.indexOf(item) === -1)
{ res.push(item); }
});
return res;
}
function joinStrings(things, limit, separator) {
if (limit === void 0) { limit = 100; }
if (separator === void 0) { separator = " - "; }
if (!things)
{ return ""; }
var sliced = things.slice(0, limit);
return "" + sliced.join(separator) + (things.length > limit ? " (... and " + (things.length - limit) + "more)" : "");
}
function isObject(value) {
return value !== null && typeof value === "object";
}
function isPlainObject(value) {
if (value === null || typeof value !== "object")
{ return false; }
var proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function objectAssign() {
var arguments$1 = arguments;
var res = arguments[0];
for (var i = 1, l = arguments.length; i < l; i++) {
var source = arguments$1[i];
for (var key in source)
{ if (hasOwnProperty(source, key)) {
res[key] = source[key];
} }
}
return res;
}
function valueDidChange(compareStructural, oldValue, newValue) {
return compareStructural
? !deepEquals(oldValue, newValue)
: oldValue !== newValue;
}
var prototypeHasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwnProperty(object, propName) {
return prototypeHasOwnProperty.call(object, propName);
}
function makeNonEnumerable(object, propNames) {
for (var i = 0; i < propNames.length; i++) {
addHiddenProp(object, propNames[i], object[propNames[i]]);
}
}
function addHiddenProp(object, propName, value) {
Object.defineProperty(object, propName, {
enumerable: false,
writable: true,
configurable: true,
value: value
});
}
function addHiddenFinalProp(object, propName, value) {
Object.defineProperty(object, propName, {
enumerable: false,
writable: false,
configurable: true,
value: value
});
}
function isPropertyConfigurable(object, prop) {
var descriptor = Object.getOwnPropertyDescriptor(object, prop);
return !descriptor || (descriptor.configurable !== false && descriptor.writable !== false);
}
function assertPropertyConfigurable(object, prop) {
invariant(isPropertyConfigurable(object, prop), "Cannot make property '" + prop + "' observable, it is not configurable and writable in the target object");
}
function getEnumerableKeys(obj) {
var res = [];
for (var key in obj)
{ res.push(key); }
return res;
}
function deepEquals(a, b) {
if (a === null && b === null)
{ return true; }
if (a === undefined && b === undefined)
{ return true; }
var aIsArray = isArrayLike(a);
if (aIsArray !== isArrayLike(b)) {
return false;
}
else if (aIsArray) {
if (a.length !== b.length)
{ return false; }
for (var i = a.length - 1; i >= 0; i--)
{ if (!deepEquals(a[i], b[i]))
{ return false; } }
return true;
}
else if (typeof a === "object" && typeof b === "object") {
if (a === null || b === null)
{ return false; }
if (getEnumerableKeys(a).length !== getEnumerableKeys(b).length)
{ return false; }
for (var prop in a) {
if (!(prop in b))
{ return false; }
if (!deepEquals(a[prop], b[prop]))
{ return false; }
}
return true;
}
return a === b;
}
function createInstanceofPredicate(name, clazz) {
var propName = "isMobX" + name;
clazz.prototype[propName] = true;
return function (x) {
return isObject(x) && x[propName] === true;
};
}
function isArrayLike(x) {
return Array.isArray(x) || isObservableArray(x);
}
exports.isArrayLike = isArrayLike;
});
var Reaction = mobx.Reaction;
var isObservable = mobx.isObservable;
var extras = mobx.extras;
var EventEmitter = function EventEmitter() {
this.listeners = [];
};
EventEmitter.prototype.on = function on (cb) {
var this$1 = this;
this.listeners.push(cb);
return function () {
var index = this$1.listeners.indexOf(cb);
if (index !== -1) {
this$1.listeners.splice(index, 1);
}
};
};
EventEmitter.prototype.emit = function emit (data) {
this.listeners.forEach(function (fn) { return fn(data); });
};
EventEmitter.prototype.getTotalListeners = function getTotalListeners () {
return this.listeners.length;
};
EventEmitter.prototype.clearListeners = function clearListeners () {
this.listeners = [];
};
var findDOMNode = Inferno.findDOMNode;
/**
* Dev tools support
*/
var isDevtoolsEnabled = false;
var componentByNodeRegistery = new WeakMap();
var renderReporter = new EventEmitter();
function reportRendering(component) {
var node = findDOMNode(component);
if (node && componentByNodeRegistery) {
componentByNodeRegistery.set(node, component);
}
renderReporter.emit({
event: 'render',
renderTime: component.__$mobRenderEnd - component.__$mobRenderStart,
totalTime: Date.now() - component.__$mobRenderStart,
component: component,
node: node
});
}
function trackComponents() {
if (typeof WeakMap === 'undefined') {
throwError('[inferno-mobx] tracking components is not supported in this browser.');
}
if (!isDevtoolsEnabled) {
isDevtoolsEnabled = true;
}
}
function makeReactive(componentClass) {
var target = componentClass.prototype || componentClass;
var baseDidMount = target.componentDidMount;
var baseWillMount = target.componentWillMount;
var baseUnmount = target.componentWillUnmount;
target.componentWillMount = function () {
var this$1 = this;
// Call original
baseWillMount && baseWillMount.call(this);
var reaction$$1;
var isRenderingPending = false;
var initialName = this.displayName || this.name || (this.constructor && (this.constructor.displayName || this.constructor.name)) || "<component>";
var baseRender = this.render.bind(this);
var initialRender = function (nextProps, nextContext) {
reaction$$1 = new Reaction((initialName + ".render()"), function () {
if (!isRenderingPending) {
isRenderingPending = true;
if (this$1.__$mobxIsUnmounted !== true) {
var hasError = true;
try {
Component.prototype.forceUpdate.call(this$1);
hasError = false;
}
finally {
if (hasError) {
reaction$$1.dispose();
}
}
}
}
});
reactiveRender.$mobx = reaction$$1;
this$1.render = reactiveRender;
return reactiveRender(nextProps, nextContext);
};
var reactiveRender = function (nextProps, nextContext) {
isRenderingPending = false;
var rendering = undefined;
reaction$$1.track(function () {
if (isDevtoolsEnabled) {
this$1.__$mobRenderStart = Date.now();
}
rendering = extras.allowStateChanges(false, baseRender.bind(this$1, nextProps, nextContext));
if (isDevtoolsEnabled) {
this$1.__$mobRenderEnd = Date.now();
}
});
return rendering;
};
this.render = initialRender;
};
target.componentDidMount = function () {
isDevtoolsEnabled && reportRendering(this);
// Call original
baseDidMount && baseDidMount.call(this);
};
target.componentWillUnmount = function () {
// Call original
baseUnmount && baseUnmount.call(this);
// Dispose observables
this.render.$mobx && this.render.$mobx.dispose();
this.__$mobxIsUnmounted = true;
if (isDevtoolsEnabled) {
var node = findDOMNode(this);
if (node && componentByNodeRegistery) {
componentByNodeRegistery.delete(node);
}
renderReporter.emit({
event: 'destroy',
component: this,
node: node
});
}
};
target.shouldComponentUpdate = function (nextProps, nextState) {
var this$1 = this;
// Update on any state changes (as is the default)
if (this.state !== nextState) {
return true;
}
// Update if props are shallowly not equal, inspired by PureRenderMixin
var keys = Object.keys(this.props);
if (keys.length !== Object.keys(nextProps).length) {
return true;
}
for (var i = keys.length - 1; i >= 0; i--) {
var key = keys[i];
var newValue = nextProps[key];
if (newValue !== this$1.props[key]) {
return true;
}
else if (newValue && typeof newValue === 'object' && !isObservable(newValue)) {
// If the newValue is still the same object, but that object is not observable,
// fallback to the default behavior: update, because the object *might* have changed.
return true;
}
}
return true;
};
return componentClass;
}
var index$1 = createCommonjsModule(function (module) {
'use strict';
var INFERNO_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
arguments: true,
arity: true
};
var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function';
function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) {
if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components
var keys = Object.getOwnPropertyNames(sourceComponent);
/* istanbul ignore else */
if (isGetOwnPropertySymbolsAvailable) {
keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent));
}
for (var i = 0; i < keys.length; ++i) {
if (!INFERNO_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) {
try {
targetComponent[keys[i]] = sourceComponent[keys[i]];
} catch (error) {
}
}
}
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
module.exports.default = module.exports;
});
/**
* Store Injection
*/
function createStoreInjector(grabStoresFn, component) {
var Injector = createClass({
displayName: component.name,
render: function render() {
var this$1 = this;
var newProps = {};
for (var key in this.props) {
if (this$1.props.hasOwnProperty(key)) {
newProps[key] = this$1.props[key];
}
}
var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {};
for (var key$1 in additionalProps) {
newProps[key$1] = additionalProps[key$1];
}
newProps.ref = function (instance) {
this$1.wrappedInstance = instance;
};
return createElement(component, newProps);
}
});
Injector.contextTypes = { mobxStores: function mobxStores() { } };
index$1(Injector, component);
return Injector;
}
var grabStoresByName = function (storeNames) { return function (baseStores, nextProps) {
storeNames.forEach(function (storeName) {
// Prefer props over stores
if (storeName in nextProps) {
return;
}
if (!(storeName in baseStores)) {
throw new Error("MobX observer: Store \"" + storeName + "\" is not available! " +
"Make sure it is provided by some Provider");
}
nextProps[storeName] = baseStores[storeName];
});
return nextProps;
}; };
/**
* Higher order component that injects stores to a child.
* takes either a varargs list of strings, which are stores read from the context,
* or a function that manually maps the available stores from the context to props:
* storesToProps(mobxStores, props, context) => newProps
*/
function inject(grabStoresFn) {
var arguments$1 = arguments;
if (typeof grabStoresFn !== 'function') {
var storesNames = [];
for (var i = 0; i < arguments.length; i++) {
storesNames[i] = arguments$1[i];
}
grabStoresFn = grabStoresByName(storesNames);
}
return function (componentClass) { return createStoreInjector(grabStoresFn, componentClass); };
}
/**
* Wraps a component and provides stores as props
*/
function connect(arg1, arg2) {
if ( arg2 === void 0 ) arg2 = null;
if (typeof arg1 === 'string') {
throwError('Store names should be provided as array');
}
if (Array.isArray(arg1)) {
// component needs stores
if (!arg2) {
// invoked as decorator
return function (componentClass) { return connect(arg1, componentClass); };
}
else {
// TODO: deprecate this invocation style
return inject.apply(null, arg1)(connect(arg2));
}
}
var componentClass = arg1;
// Stateless function component:
// If it is function but doesn't seem to be a Inferno class constructor,
// wrap it to a Inferno class automatically
if (typeof componentClass === 'function'
&& (!componentClass.prototype || !componentClass.prototype.render)
&& !componentClass.isReactClass
&& !Component.isPrototypeOf(componentClass)) {
var newClass = createClass({
displayName: componentClass.displayName || componentClass.name,
propTypes: componentClass.propTypes,
contextTypes: componentClass.contextTypes,
getDefaultProps: function () { return componentClass.defaultProps; },
render: function render() {
return componentClass.call(this, this.props, this.context);
}
});
return connect(newClass);
}
if (!componentClass) {
throwError('Please pass a valid component to "observer"');
}
componentClass.isMobXReactObserver = true;
return makeReactive(componentClass);
}
var index = {
Provider: Provider,
inject: inject,
connect: connect,
observer: connect,
trackComponents: trackComponents,
renderReporter: renderReporter,
componentByNodeRegistery: componentByNodeRegistery
};
return index;
})));
|
'use strict';
module.exports = {
set: function (v) {
this.setProperty('background-position-y', v);
},
get: function () {
return this.getPropertyValue('background-position-y');
},
enumerable: true
};
|
var differenceInMilliseconds = require('../difference_in_milliseconds/index.js')
var MILLISECONDS_IN_MINUTE = 60000
/**
* @category Minute Helpers
* @summary Get the number of minutes between the given dates.
*
* @description
* Get the number of minutes between the given dates.
*
* @param {Date|String|Number} dateLeft - the later date
* @param {Date|String|Number} dateRight - the earlier date
* @returns {Number} the number of minutes
*
* @example
* // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
* var result = differenceInMinutes(
* new Date(2014, 6, 2, 12, 20, 0),
* new Date(2014, 6, 2, 12, 7, 59)
* )
* //=> 12
*/
function differenceInMinutes (dirtyDateLeft, dirtyDateRight) {
var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE
return diff > 0 ? Math.floor(diff) : Math.ceil(diff)
}
module.exports = differenceInMinutes
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.2.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("../context/context");
var utils_1 = require('../utils');
var textCellEditor_1 = require("./cellEditors/textCellEditor");
var selectCellEditor_1 = require("./cellEditors/selectCellEditor");
var popupEditorWrapper_1 = require("./cellEditors/popupEditorWrapper");
var popupTextCellEditor_1 = require("./cellEditors/popupTextCellEditor");
var popupSelectCellEditor_1 = require("./cellEditors/popupSelectCellEditor");
var dateCellEditor_1 = require("./cellEditors/dateCellEditor");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var CellEditorFactory = (function () {
function CellEditorFactory() {
this.cellEditorMap = {};
}
CellEditorFactory.prototype.init = function () {
this.cellEditorMap[CellEditorFactory.TEXT] = textCellEditor_1.TextCellEditor;
this.cellEditorMap[CellEditorFactory.SELECT] = selectCellEditor_1.SelectCellEditor;
this.cellEditorMap[CellEditorFactory.POPUP_TEXT] = popupTextCellEditor_1.PopupTextCellEditor;
this.cellEditorMap[CellEditorFactory.POPUP_SELECT] = popupSelectCellEditor_1.PopupSelectCellEditor;
this.cellEditorMap[CellEditorFactory.DATE] = dateCellEditor_1.DateCellEditor;
};
CellEditorFactory.prototype.addCellEditor = function (key, cellEditor) {
this.cellEditorMap[key] = cellEditor;
};
// private registerEditorsFromGridOptions(): void {
// var userProvidedCellEditors = this.gridOptionsWrapper.getCellEditors();
// _.iterateObject(userProvidedCellEditors, (key: string, cellEditor: {new(): ICellEditor})=> {
// this.addCellEditor(key, cellEditor);
// });
// }
CellEditorFactory.prototype.createCellEditor = function (key) {
var CellEditorClass;
if (utils_1.Utils.missing(key)) {
CellEditorClass = this.cellEditorMap[CellEditorFactory.TEXT];
}
else if (typeof key === 'string') {
CellEditorClass = this.cellEditorMap[key];
if (utils_1.Utils.missing(CellEditorClass)) {
console.warn('ag-Grid: unable to find cellEditor for key ' + key);
CellEditorClass = this.cellEditorMap[CellEditorFactory.TEXT];
}
}
else {
CellEditorClass = key;
}
var cellEditor = new CellEditorClass();
this.context.wireBean(cellEditor);
if (cellEditor.isPopup && cellEditor.isPopup()) {
cellEditor = new popupEditorWrapper_1.PopupEditorWrapper(cellEditor);
}
return cellEditor;
};
CellEditorFactory.TEXT = 'text';
CellEditorFactory.SELECT = 'select';
CellEditorFactory.DATE = 'date';
CellEditorFactory.POPUP_TEXT = 'popupText';
CellEditorFactory.POPUP_SELECT = 'popupSelect';
__decorate([
context_1.Autowired('context'),
__metadata('design:type', context_1.Context)
], CellEditorFactory.prototype, "context", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], CellEditorFactory.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.PostConstruct,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], CellEditorFactory.prototype, "init", null);
CellEditorFactory = __decorate([
context_1.Bean('cellEditorFactory'),
__metadata('design:paramtypes', [])
], CellEditorFactory);
return CellEditorFactory;
})();
exports.CellEditorFactory = CellEditorFactory;
|
(function($){
SlideDeckLens['reporter'] = function(slidedeck){
var self = this;
var slidedeck = $(slidedeck);
var slidedeckFrame = slidedeck.closest('.slidedeck-frame');
var images = slidedeckFrame.find('img.slide-image');
var deck = slidedeck.slidedeck();
var deckElement = slidedeck;
var navDeckElement = false;
var navDeck = false;
var mouseIsHoveringOverNav = false;
// Get the accent color
var accentColor = slidedeckFrame.find('.accent-color').css('color');
// For the button nav
var maxButtonsPerPage = 0;
var numberOfPages = 1;
// After loaded callback
deck.loaded(function( thedeck ){
/**
* Hide the slide content when a video play button is clicked.
*/
deckElement.find('.cover .play').click(function(event){
$(this).parents('dd').addClass('show-video-wrapper');
$(this).parents('dd').addClass('hide-slide-content');
});
/**
* For this lens, the structure necessary deviates a bit too much.
* When the viewer clicks the "Play Video" link, we'll trigger a click
* on the generic play button in the template.
*/
$('.slide-type-video .play-video, .slide-type-video .play-video-alternative').bind( "click", function( event ){
event.preventDefault();
var parentSlide = $(this).parents('dd');
var playButton = parentSlide.find('.video-wrapper .cover .play-video-button');
playButton.trigger('click');
} );
// Move the dot nav
if(!slidedeckFrame.hasClass('content-source-custom')){
if(slidedeckFrame.find('dd.slide').eq(deck.current-1).hasClass('no-image')){
slidedeckFrame.find('.dot-nav').css('margin-left', -(slidedeckFrame.find('.dot-nav').outerWidth() / 2)).addClass('no-image');
}
}
});
/**
* Loops through all the images and tries to correct them
* for out of bounds width or height.
*/
this.widthOrHeight = function(){
images.one('load', function(event) {
var image = $(event.target);
var width = image.width();
var outerWidth = image.outerWidth();
var height = image.height();
var outerHeight = image.outerHeight();
var containerWidth = image.parents('div.image').width();
var containerHeight = image.parents('div.image').height();
var imageRatio = width / height;
var containerRatio = containerWidth / containerHeight;
// If the image is taller than it's container...
if( outerHeight > containerHeight ) {
image.css({
width: 'auto',
height: containerHeight
});
}
}).each(function() {
if(this.complete) $(this).load();
});
}
this.dotNavigation = function(){
if( slidedeckFrame.hasClass('sd2-nav-dots') ) {
var maxDots = 20;
if( slidedeckFrame.hasClass('sd2-small') ) {
maxDots = 10;
}
var slideCount = slidedeck.find('dd.slide').length;
var navHtml = '<ul class="dot-nav"></ul>';
$(navHtml).appendTo(slidedeckFrame);
var dotNav = slidedeckFrame.find('.dot-nav');
for( i = 0; i < Math.min( slideCount, maxDots ); i++ ) {
$('<li></li>').appendTo(dotNav);
}
var navDots = dotNav.find('li');
dotNav.css( 'width', Math.min( slideCount, maxDots ) * ( navDots.outerWidth() + 10 ) - 10 )
dotNav.css( 'margin-left', -( dotNav.outerWidth() / 2) );
navDots.eq( deck.current-1 ).addClass('accent-color-background');
// ADD CLICK FUNCTIONS
navDots.bind('click', function(){
var $self = $(this);
deck.goTo(($self).index()+1);
navDots.removeClass('accent-color-background');
$self.addClass('accent-color-background');
});
}
}
this.syncButtonNavigation = function(){
if( navDeck ){
if( !mouseIsHoveringOverNav ){
var slideIsOnPage = Math.ceil( deck.current / maxButtonsPerPage );
navDeck.goTo( slideIsOnPage );
}
}
}
this.positionPlayButtons = function(){
slidedeckFrame.find('.image .play-video-alternative').each(function(){
var playButton = $(this);
playButton.css({
'margin-top': '-' + Math.round( parseInt( playButton.css('padding-top') ) / 2 ) + 'px',
'margin-left': '-' + Math.round( playButton.width() / 2 ) + 'px'
});
// Append the icon-shape element and use it as the Raphael paper.
playButton.append('<span class="play-icon"></span>');
var iconWrapper = playButton.find('.play-icon');
var width = iconWrapper.width();
var height = iconWrapper.height();
var paper = Raphael( iconWrapper[0], width, height );
var circle = paper.circle( Math.round( width/2 ) , Math.round( height/2 ), Math.round( width * 0.48 ) );
var circleOpacity = {
normal: 0.8,
hover: 1.0
};
// Draw the triangle
// Top point
var path = "M" + ( width * 0.35 ) + "," + ( height * 0.25 );
// Right point
path += "L" + ( width * 0.75 ) + "," + ( height / 2 );
// Lower point
path += "L" + ( width * 0.35 ) + "," + ( height * 0.75 );
path += "z";
var triangle = paper.path( path );
// Fill and stroke for these elements
triangle.attr({
stroke: 'none',
fill: 'rgba(0,0,0,1)'
});
circle.attr({
stroke: 'none',
fill: 'rgba(255,255,255,' + circleOpacity.normal + ')'
});
// Bind the mouse events for opacity changes
playButton.bind('mouseenter', function(event){
circle.attr({
fill: 'rgba(255,255,255,' + circleOpacity.hover + ')'
});
});
playButton.bind('mouseleave', function(event){
circle.attr({
fill: 'rgba(255,255,255,' + circleOpacity.normal + ')'
});
});
});
}
this.buttonNavigation = function(){
if( slidedeckFrame.hasClass('sd2-nav-titles') || slidedeckFrame.hasClass('sd2-nav-dates') ) {
var slideCount = slidedeck.find('dd.slide').length;
var buttons = slidedeck.find('dd.slide .nav-button');
var navHtml = '<div class="button-nav"></div>';
var appendedNav = $(navHtml).appendTo(slidedeckFrame);
var navOuterWidth = parseInt( appendedNav.outerWidth() );
// Percentage for each nav arrow
var navArrowWith = 3.5;
// Remaining percentage for nav buttons
var availableForButtons = 100 - (navArrowWith * 2);
if( slidedeckFrame.hasClass('sd2-nav-dates') ){
// Divide the width of the container by the factor to get a max count ( for dates )
maxButtonsPerPage = Math.ceil( navOuterWidth / 140 );
}else{
// Divide the width of the container by the factor to get a max count ( for titles )
maxButtonsPerPage = Math.ceil( navOuterWidth / 160 );
}
numberOfPages = Math.ceil( slideCount / maxButtonsPerPage );
// Special case for small decks.
if( slidedeckFrame.hasClass('sd2-small') ){
maxButtonsPerPage = Math.ceil( navOuterWidth / 100 );
}
if( maxButtonsPerPage >= slideCount ){
navArrowWith = false;
availableForButtons = 100;
}
// Create the button nav
var buttonNav = slidedeckFrame.find('.button-nav');
// Append the previous nav
if( navArrowWith )
buttonNav.append('<a class="nav-arrow prev" href="#prev-page" style="width:' + navArrowWith + '%;"></a>');
// Create the pages
var indexCount = 0;
buttonNav.append('<dl class="nav-slidedeck" style="width:' + availableForButtons + '%;"></dl>');
navDeckElement = slidedeckFrame.find('dl.nav-slidedeck');
for( p = 1; p <= numberOfPages; p++ ){
navDeckElement.append( '<dd class="page"></dd>' );
var thisPage = slidedeckFrame.find('dl.nav-slidedeck dd:eq(' + ( p - 1 ) + ')');
for( i = indexCount; i < Math.min( slideCount, maxButtonsPerPage ) * p; i++ ) {
var button = buttons[indexCount];
$(button).find('.sd2-nav-title').append('<span class="icon-caret"></span>');
if( button ){
$( buttons[indexCount] ).appendTo(thisPage);
}else{
$( '<span class="spacer"></span>' ).appendTo(thisPage);
}
indexCount++;
}
}
navDeck = slidedeckFrame.find('dl.nav-slidedeck').slidedeck({
keys: false,
scroll: false,
cycle: slidedeck.slidedeck().options.cycle
});
// Append the next nav
if( navArrowWith )
buttonNav.append('<a class="nav-arrow next" href="#next-page" style="width:' + navArrowWith + '%;"></a>');
// Handle the accent color backgrounds for the nav buttons.
if( slidedeckFrame.hasClass('sd2-nav-dates') ){
var theClass = 'background';
if( slidedeckFrame.hasClass('sd2-transparent-background') ){
theClass = 'accent-color-background';
}
buttons.eq( deck.current-1 ).find('span').addClass( theClass );
}else{
buttons.eq( deck.current-1 ).addClass('active');
}
buttons.bind('click', function(){
var $self = $(this);
deck.goTo(($self).index('.nav-button')+1);
if( slidedeckFrame.hasClass('sd2-nav-dates') ){
buttons.find('span').removeClass('active');
}else{
buttons.removeClass('active');
}
if( slidedeckFrame.hasClass('sd2-nav-dates') ){
$self.find('span').addClass('active');
}else{
$self.addClass('active');
}
});
// Size the buttons appropriately.
buttons.css({
width: ( 100 / ( Math.min( slideCount, maxButtonsPerPage ) ) ) + '%'
});
navDeckElement.find('span.spacer').css({
width: ( 100 / ( Math.min( slideCount, maxButtonsPerPage ) ) ) + '%'
});
/**
* Add a class to see when the mouse is in the slide area
*
* The basic idea is that if the user's mouse is in the button nav
* area then we can reasonably assume they are about to click either the
* prev/next page button or a button. In this case, we skip auto scrolling.
*/
slidedeckFrame.find('.button-nav').bind('mouseenter mouseleave', function(event){
if( event.type == 'mouseenter' ){
mouseIsHoveringOverNav = true;
}else{
mouseIsHoveringOverNav = false;
}
});
// Append the SVG Arrows to the nav arrows
slidedeckFrame.find('.button-nav .nav-arrow').each(function(){
var button = $(this);
// Append the icon-shape element and use it as the Raphael paper.
button.append('<span class="icon-shape-prev-next"></span>');
var iconWrapper = button.find('.icon-shape-prev-next');
var width = iconWrapper.width();
var height = iconWrapper.height();
var strokeWidth = 2;
var opacity = {
normal: 0.75,
hover: 1
};
var arrowColor = '#ffffff';
var paper = Raphael( iconWrapper[0], width, height );
// Draw the icon
// Move to the top center (minus thickness)
var path = "M0,0";
// Draw thickness
path += "L" + strokeWidth + ",0";
// draw a diagonal to the center right
path += "L" + ( width - strokeWidth ) + "," + ( height / 2 );
// draw to the bottom left
path += "L" + strokeWidth + "," + height;
// minus the stroke width
path += "L" + 0 + "," + height;
// draw a diagonal to the center right (minus thickness)
path += "L" + ( width - strokeWidth * 2 ) + "," + ( height / 2 );
// Close the path
path += "z";
var pointerShape = paper.path( path );
// Flip the arrow if it's the prev arrow
if( this.hash == '#prev-page' ){
pointerShape.transform("s-1,1");
}
if( slidedeckFrame.hasClass('sd2-light') )
arrowColor = '#333333';
pointerShape.attr({
'stroke': 'none',
'fill': arrowColor
});
// Define the data property to adjust the color.
iconWrapper.data('prev-next-arrows', pointerShape);
});
// Bind click events to the prev/next arrows
slidedeckFrame.find('.button-nav .nav-arrow').bind('click', function(event){
event.preventDefault();
switch( this.hash ){
case '#prev-page':
navDeck.prev();
break;
case '#next-page':
navDeck.next();
break;
}
});
self.syncButtonNavigation();
}
}
/**
* Prevents a click on the a tag of the video thumb from opening the
* video in a new window.
*/
this.hijackClickOnVideoThumb = function(){
slidedeckFrame.find('.slide-type-video a.sd2-image-link').click(function(event){
event.preventDefault();
});
}
// Get the old complete option
var oldComplete = deck.options.complete;
deck.setOption('complete', function(){
// If the old complete option was a function, run it
if(typeof(oldComplete) == 'function') {
oldComplete(deck);
}
});
var oldBefore = deck.options.before;
deck.setOption('before', function(deck){
if(typeof(oldBefore) == 'function')
oldBefore(deck);
// Bind the callbacks to the dot nav
if( slidedeckFrame.hasClass('sd2-nav-dots') ){
var navDots = slidedeckFrame.find('.dot-nav').find('li');
navDots.removeClass('accent-color-background');
navDots.eq(deck.current-1).addClass('accent-color-background');
}
var navButtons = slidedeckFrame.find('.button-nav').find('.nav-button');
// Bind the callbacks to the nav buttons (dates)
if( slidedeckFrame.hasClass('sd2-nav-dates') ){
var theClass = 'background';
if( slidedeckFrame.hasClass('sd2-transparent-background') ){
theClass = 'accent-color-background';
}
navButtons.find('span').removeClass( theClass );
navButtons.eq(deck.current-1).find('span').addClass( theClass );
}
// Bind the callbacks to the nav buttons (titles)
if( slidedeckFrame.hasClass('sd2-nav-titles') ){
navButtons.removeClass('active');
navButtons.eq(deck.current-1).addClass('active');
}
self.syncButtonNavigation();
});
this.hijackClickOnVideoThumb();
this.positionPlayButtons();
this.dotNavigation();
this.buttonNavigation();
this.widthOrHeight();
return true;
};
$(document).ready(function(){
$('.lens-reporter .slidedeck').each(function(){
if(typeof($.data(this, 'lens-reporter')) == 'undefined'){
$.data(this, 'lens-reporter', new SlideDeckLens['reporter'](this));
}
});
});
})(jQuery); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.