vue3-visjs
Version:
> Vue3 component that helps with <a href="http://visjs.org/">Visjs</a> interaction. > Originally this is fork of the [vis2vue](https://github.com/alexcode/vue2vis) project to update to the latest split component Visjs structure and a fork of [vue3-visjs](
25,760 lines • 1.79 MB
JavaScript
import { openBlock, createElementBlock, createElementVNode } from 'vue';
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn) {
var module = { exports: {} };
return fn(module, module.exports), module.exports;
}
function commonjsRequire (path) {
throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var moment$4 = createCommonjsModule(function (module, exports) {
(function (global, factory) {
module.exports = factory() ;
})(commonjsGlobal, function () {
var hookCallback;
function hooks() {
return hookCallback.apply(null, arguments);
}
// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback(callback) {
hookCallback = callback;
}
function isArray(input) {
return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
}
function isObject(input) {
// IE8 will treat undefined and null as object if it wasn't for
// input != null
return input != null && Object.prototype.toString.call(input) === '[object Object]';
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function isObjectEmpty(obj) {
if (Object.getOwnPropertyNames) {
return Object.getOwnPropertyNames(obj).length === 0;
} else {
var k;
for (k in obj) {
if (hasOwnProp(obj, k)) {
return false;
}
}
return true;
}
}
function isUndefined(input) {
return input === void 0;
}
function isNumber(input) {
return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
}
function isDate(input) {
return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
}
function map(arr, fn) {
var res = [],
i,
arrLen = arr.length;
for (i = 0; i < arrLen; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, 'toString')) {
a.toString = b.toString;
}
if (hasOwnProp(b, 'valueOf')) {
a.valueOf = b.valueOf;
}
return a;
}
function createUTC(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, true).utc();
}
function defaultParsingFlags() {
// We need to deep clone this object.
return {
empty: false,
unusedTokens: [],
unusedInput: [],
overflow: -2,
charsLeftOver: 0,
nullInput: false,
invalidEra: null,
invalidMonth: null,
invalidFormat: false,
userInvalidated: false,
iso: false,
parsedDateParts: [],
era: null,
meridiem: null,
rfc2822: false,
weekdayMismatch: false
};
}
function getParsingFlags(m) {
if (m._pf == null) {
m._pf = defaultParsingFlags();
}
return m._pf;
}
var some;
if (Array.prototype.some) {
some = Array.prototype.some;
} else {
some = function (fun) {
var t = Object(this),
len = t.length >>> 0,
i;
for (i = 0; i < len; i++) {
if (i in t && fun.call(this, t[i], i, t)) {
return true;
}
}
return false;
};
}
function isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m),
parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
}),
isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
if (m._strict) {
isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined;
}
if (Object.isFrozen == null || !Object.isFrozen(m)) {
m._isValid = isNowValid;
} else {
return isNowValid;
}
}
return m._isValid;
}
function createInvalid(flags) {
var m = createUTC(NaN);
if (flags != null) {
extend(getParsingFlags(m), flags);
} else {
getParsingFlags(m).userInvalidated = true;
}
return m;
}
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = hooks.momentProperties = [],
updateInProgress = false;
function copyConfig(to, from) {
var i,
prop,
val,
momentPropertiesLen = momentProperties.length;
if (!isUndefined(from._isAMomentObject)) {
to._isAMomentObject = from._isAMomentObject;
}
if (!isUndefined(from._i)) {
to._i = from._i;
}
if (!isUndefined(from._f)) {
to._f = from._f;
}
if (!isUndefined(from._l)) {
to._l = from._l;
}
if (!isUndefined(from._strict)) {
to._strict = from._strict;
}
if (!isUndefined(from._tzm)) {
to._tzm = from._tzm;
}
if (!isUndefined(from._isUTC)) {
to._isUTC = from._isUTC;
}
if (!isUndefined(from._offset)) {
to._offset = from._offset;
}
if (!isUndefined(from._pf)) {
to._pf = getParsingFlags(from);
}
if (!isUndefined(from._locale)) {
to._locale = from._locale;
}
if (momentPropertiesLen > 0) {
for (i = 0; i < momentPropertiesLen; i++) {
prop = momentProperties[i];
val = from[prop];
if (!isUndefined(val)) {
to[prop] = val;
}
}
}
return to;
}
// Moment prototype object
function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d != null ? config._d.getTime() : NaN);
if (!this.isValid()) {
this._d = new Date(NaN);
}
// Prevent infinite loop in case updateOffset creates new moment
// objects.
if (updateInProgress === false) {
updateInProgress = true;
hooks.updateOffset(this);
updateInProgress = false;
}
}
function isMoment(obj) {
return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
}
function warn(msg) {
if (hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
console.warn('Deprecation warning: ' + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(null, msg);
}
if (firstTime) {
var args = [],
arg,
i,
key,
argLen = arguments.length;
for (i = 0; i < argLen; i++) {
arg = '';
if (typeof arguments[i] === 'object') {
arg += '\n[' + i + '] ';
for (key in arguments[0]) {
if (hasOwnProp(arguments[0], key)) {
arg += key + ': ' + arguments[0][key] + ', ';
}
}
arg = arg.slice(0, -2); // Remove trailing comma and space
} else {
arg = arguments[i];
}
args.push(arg);
}
warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + new Error().stack);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(name, msg);
}
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;
function isFunction(input) {
return typeof Function !== 'undefined' && input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
function set(config) {
var prop, i;
for (i in config) {
if (hasOwnProp(config, i)) {
prop = config[i];
if (isFunction(prop)) {
this[i] = prop;
} else {
this['_' + i] = prop;
}
}
}
this._config = config;
// Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source);
}
function mergeConfigs(parentConfig, childConfig) {
var res = extend({}, parentConfig),
prop;
for (prop in childConfig) {
if (hasOwnProp(childConfig, prop)) {
if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
res[prop] = {};
extend(res[prop], parentConfig[prop]);
extend(res[prop], childConfig[prop]);
} else if (childConfig[prop] != null) {
res[prop] = childConfig[prop];
} else {
delete res[prop];
}
}
}
for (prop in parentConfig) {
if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) {
// make sure changes to properties don't modify parent config
res[prop] = extend({}, res[prop]);
}
}
return res;
}
function Locale(config) {
if (config != null) {
this.set(config);
}
}
var keys;
if (Object.keys) {
keys = Object.keys;
} else {
keys = function (obj) {
var i,
res = [];
for (i in obj) {
if (hasOwnProp(obj, i)) {
res.push(i);
}
}
return res;
};
}
var defaultCalendar = {
sameDay: '[Today at] LT',
nextDay: '[Tomorrow at] LT',
nextWeek: 'dddd [at] LT',
lastDay: '[Yesterday at] LT',
lastWeek: '[Last] dddd [at] LT',
sameElse: 'L'
};
function calendar(key, mom, now) {
var output = this._calendar[key] || this._calendar['sameElse'];
return isFunction(output) ? output.call(mom, now) : output;
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = '' + Math.abs(number),
zerosToFill = targetLength - absNumber.length,
sign = number >= 0;
return (sign ? forceSign ? '+' : '' : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
}
var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
formatFunctions = {},
formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken(token, padded, ordinal, callback) {
var func = callback;
if (typeof callback === 'string') {
func = function () {
return this[callback]();
};
}
if (token) {
formatTokenFunctions[token] = func;
}
if (padded) {
formatTokenFunctions[padded[0]] = function () {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
};
}
if (ordinal) {
formatTokenFunctions[ordinal] = function () {
return this.localeData().ordinal(func.apply(this, arguments), token);
};
}
}
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, '');
}
return input.replace(/\\/g, '');
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens),
i,
length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = '',
i;
for (i = 0; i < length; i++) {
output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
}
return output;
};
}
// format date using native date object
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
var defaultLongDateFormat = {
LTS: 'h:mm:ss A',
LT: 'h:mm A',
L: 'MM/DD/YYYY',
LL: 'MMMM D, YYYY',
LLL: 'MMMM D, YYYY h:mm A',
LLLL: 'dddd, MMMM D, YYYY h:mm A'
};
function longDateFormat(key) {
var format = this._longDateFormat[key],
formatUpper = this._longDateFormat[key.toUpperCase()];
if (format || !formatUpper) {
return format;
}
this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function (tok) {
if (tok === 'MMMM' || tok === 'MM' || tok === 'DD' || tok === 'dddd') {
return tok.slice(1);
}
return tok;
}).join('');
return this._longDateFormat[key];
}
var defaultInvalidDate = 'Invalid date';
function invalidDate() {
return this._invalidDate;
}
var defaultOrdinal = '%d',
defaultDayOfMonthOrdinalParse = /\d{1,2}/;
function ordinal(number) {
return this._ordinal.replace('%d', number);
}
var defaultRelativeTime = {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
ss: '%d seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
w: 'a week',
ww: '%d weeks',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years'
};
function relativeTime(number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
}
function pastFuture(diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}
var aliases = {};
function addUnitAlias(unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
var priorities = {};
function addUnitPriority(unit, priority) {
priorities[unit] = priority;
}
function getPrioritizedUnits(unitsObj) {
var units = [],
u;
for (u in unitsObj) {
if (hasOwnProp(unitsObj, u)) {
units.push({
unit: u,
priority: priorities[u]
});
}
}
units.sort(function (a, b) {
return a.priority - b.priority;
});
return units;
}
function isLeapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
}
function absFloor(number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
function makeGetSet(unit, keepTime) {
return function (value) {
if (value != null) {
set$1(this, unit, value);
hooks.updateOffset(this, keepTime);
return this;
} else {
return get(this, unit);
}
};
}
function get(mom, unit) {
return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
}
function set$1(mom, unit, value) {
if (mom.isValid() && !isNaN(value)) {
if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
value = toInt(value);
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
} else {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
}
// MOMENTS
function stringGet(units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet(units, value) {
if (typeof units === 'object') {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units),
i,
prioritizedLen = prioritized.length;
for (i = 0; i < prioritizedLen; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
var match1 = /\d/,
// 0 - 9
match2 = /\d\d/,
// 00 - 99
match3 = /\d{3}/,
// 000 - 999
match4 = /\d{4}/,
// 0000 - 9999
match6 = /[+-]?\d{6}/,
// -999999 - 999999
match1to2 = /\d\d?/,
// 0 - 99
match3to4 = /\d\d\d\d?/,
// 999 - 9999
match5to6 = /\d\d\d\d\d\d?/,
// 99999 - 999999
match1to3 = /\d{1,3}/,
// 0 - 999
match1to4 = /\d{1,4}/,
// 0 - 9999
match1to6 = /[+-]?\d{1,6}/,
// -999999 - 999999
matchUnsigned = /\d+/,
// 0 - inf
matchSigned = /[+-]?\d+/,
// -inf - inf
matchOffset = /Z|[+-]\d\d:?\d\d/gi,
// +00:00 -00:00 +0000 -0000 or Z
matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi,
// +00 -00 +00:00 -00:00 +0000 -0000 or Z
matchTimestamp = /[+-]?\d+(\.\d{1,3})?/,
// 123456789 123456789.123
// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
regexes;
regexes = {};
function addRegexToken(token, regex, strictRegex) {
regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
return isStrict && strictRegex ? strictRegex : regex;
};
}
function getParseRegexForToken(token, config) {
if (!hasOwnProp(regexes, token)) {
return new RegExp(unescapeFormat(token));
}
return regexes[token](config._strict, config._locale);
}
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
}));
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var tokens = {};
function addParseToken(token, callback) {
var i,
func = callback,
tokenLen;
if (typeof token === 'string') {
token = [token];
}
if (isNumber(callback)) {
func = function (input, array) {
array[callback] = toInt(input);
};
}
tokenLen = token.length;
for (i = 0; i < tokenLen; i++) {
tokens[token[i]] = func;
}
}
function addWeekParseToken(token, callback) {
addParseToken(token, function (input, array, config, token) {
config._w = config._w || {};
callback(input, config._w, config, token);
});
}
function addTimeToArrayFromToken(token, input, config) {
if (input != null && hasOwnProp(tokens, token)) {
tokens[token](input, config._a, config, token);
}
}
var YEAR = 0,
MONTH = 1,
DATE = 2,
HOUR = 3,
MINUTE = 4,
SECOND = 5,
MILLISECOND = 6,
WEEK = 7,
WEEKDAY = 8;
function mod(n, x) {
return (n % x + x) % x;
}
var indexOf;
if (Array.prototype.indexOf) {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function (o) {
// I know
var i;
for (i = 0; i < this.length; ++i) {
if (this[i] === o) {
return i;
}
}
return -1;
};
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
}
// FORMATTING
addFormatToken('M', ['MM', 2], 'Mo', function () {
return this.month() + 1;
});
addFormatToken('MMM', 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken('MMMM', 0, 0, function (format) {
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias('month', 'M');
// PRIORITY
addUnitPriority('month', 8);
// PARSING
addRegexToken('M', match1to2);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
return locale.monthsRegex(isStrict);
});
addParseToken(['M', 'MM'], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
// LOCALES
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
defaultMonthsShortRegex = matchWord,
defaultMonthsRegex = matchWord;
function localeMonths(m, format) {
if (!m) {
return isArray(this._months) ? this._months : this._months['standalone'];
}
return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
}
function localeMonthsShort(m, format) {
if (!m) {
return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone'];
}
return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
}
function handleStrictParse(monthName, format, strict) {
var i,
ii,
mom,
llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
// this is not used
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i = 0; i < 12; ++i) {
mom = createUTC([2000, i]);
this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeMonthsParse(monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) {
return handleStrictParse.call(this, monthName, format, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
}
if (!strict && !this._monthsParse[i]) {
regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
return i;
} else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
// MOMENTS
function setMonth(mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
}
if (typeof value === 'string') {
if (/^\d+$/.test(value)) {
value = toInt(value);
} else {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (!isNumber(value)) {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
function getSetMonth(value) {
if (value != null) {
setMonth(this, value);
hooks.updateOffset(this, true);
return this;
} else {
return get(this, 'Month');
}
}
function getDaysInMonth() {
return daysInMonth(this.year(), this.month());
}
function monthsShortRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsShortStrictRegex;
} else {
return this._monthsShortRegex;
}
} else {
if (!hasOwnProp(this, '_monthsShortRegex')) {
this._monthsShortRegex = defaultMonthsShortRegex;
}
return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
}
}
function monthsRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsStrictRegex;
} else {
return this._monthsRegex;
}
} else {
if (!hasOwnProp(this, '_monthsRegex')) {
this._monthsRegex = defaultMonthsRegex;
}
return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
}
}
function computeMonthsParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ''));
longPieces.push(this.months(mom, ''));
mixedPieces.push(this.months(mom, ''));
mixedPieces.push(this.monthsShort(mom, ''));
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._monthsShortRegex = this._monthsRegex;
this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
}
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : '+' + y;
});
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
// ALIASES
addUnitAlias('year', 'y');
// PRIORITIES
addUnitPriority('year', 1);
// PARSING
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// HOOKS
hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', true);
function getIsLeapYear() {
return isLeapYear(this.year());
}
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date;
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
date = new Date(y + 400, m, d, h, M, s, ms);
if (isFinite(date.getFullYear())) {
date.setFullYear(y);
}
} else {
date = new Date(y, m, d, h, M, s, ms);
}
return date;
}
function createUTCDate(y) {
var date, args;
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
args = Array.prototype.slice.call(arguments);
// preserve leap years using a full 400 year cycle, then reset
args[0] = y + 400;
date = new Date(Date.UTC.apply(null, args));
if (isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
} else {
date = new Date(Date.UTC.apply(null, arguments));
}
return date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var
// first-week day -- which january is always in the first week (4 for iso, 1 for other)
fwd = 7 + dow - doy,
// first-week day local weekday -- which local weekday is fwd
fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
return -fwdlw + fwd - 1;
}
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var localWeekday = (7 + weekday - dow) % 7,
weekOffset = firstWeekOffset(year, dow, doy),
dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
resYear,
resDayOfYear;
if (dayOfYear <= 0) {
resYear = year - 1;
resDayOfYear = daysInYear(resYear) + dayOfYear;
} else if (dayOfYear > daysInYear(year)) {
resYear = year + 1;
resDayOfYear = dayOfYear - daysInYear(year);
} else {
resYear = year;
resDayOfYear = dayOfYear;
}
return {
year: resYear,
dayOfYear: resDayOfYear
};
}
function weekOfYear(mom, dow, doy) {
var weekOffset = firstWeekOffset(mom.year(), dow, doy),
week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
resWeek,
resYear;
if (week < 1) {
resYear = mom.year() - 1;
resWeek = week + weeksInYear(resYear, dow, doy);
} else if (week > weeksInYear(mom.year(), dow, doy)) {
resWeek = week - weeksInYear(mom.year(), dow, doy);
resYear = mom.year() + 1;
} else {
resYear = mom.year();
resWeek = week;
}
return {
week: resWeek,
year: resYear
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy),
weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// FORMATTING
addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
// ALIASES
addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');
// PRIORITIES
addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);
// PARSING
addRegexToken('w', match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W', match1to2);
addRegexToken('WW', match1to2, match2);
addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
});
// HELPERS
// LOCALES
function localeWeek(mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}
var defaultLocaleWeek = {
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.
};
function localeFirstDayOfWeek() {
return this._week.dow;
}
function localeFirstDayOfYear() {
return this._week.doy;
}
// MOMENTS
function getSetWeek(input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, 'd');
}
function getSetISOWeek(input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, 'd');
}
// FORMATTING
addFormatToken('d', 0, 'do', 'day');
addFormatToken('dd', 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken('ddd', 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken('dddd', 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
// ALIASES
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);
// PARSING
addRegexToken('d', match1to2);
addRegexToken('e', match1to2);
addRegexToken('E', match1to2);
addRegexToken('dd', function (isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd', function (isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd', function (isStrict, locale) {
return locale.weekdaysRegex(isStrict);
});
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
});
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
week[token] = toInt(input);
});
// HELPERS
function parseWeekday(input, locale) {
if (typeof input !== 'string') {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === 'number') {
return input;
}
return null;
}
function parseIsoWeekday(input, locale) {
if (typeof input === 'string') {
return locale.weekdaysParse(input) % 7 || 7;
}
return isNaN(input) ? null : input;
}
// LOCALES
function shiftWeekdays(ws, n) {
return ws.slice(n, 7).concat(ws.slice(0, n));
}
var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
defaultWeekdaysRegex = matchWord,
defaultWeekdaysShortRegex = matchWord,
defaultWeekdaysMinRegex = matchWord;
function localeWeekdays(m, format) {
var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[m && m !== true && this._weekdays.isFormat.test(format) ? 'format' : 'standalone'];
return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays;
}
function localeWeekdaysShort(m) {
return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}
function localeWeekdaysMin(m) {
return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
}
function handleStrictParse$1(weekdayName, format, strict) {
var i,
ii,
mom,
llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i = 0; i < 7; ++i) {
mom = createUTC([2000, 1]).day(i);
this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeWeekdaysParse(weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) {
return handleStrictParse$1.call(this, weekdayName, format, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
if (strict && !this._fullWeekdaysParse[i]) {
this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
}
if (!this._weekdaysParse[i]) {
regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
// MOMENTS
function getSetDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
}
function getSetLocaleDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
}
function getSetISODayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (input != null) {
var weekday = parseIsoWeekday(input, this.localeData());
return this.day(this.day() % 7 ? weekday : weekday - 7);
} else {
return this.day() || 7;
}
}
function weekdaysRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysStrictRegex;
} else {
return this._weekdaysRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysRegex')) {
this._weekdaysRegex = defaultWeekdaysRegex;
}
return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
}
}
function weekdaysShortRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysShortStrictRegex;
} else {
return this._weekdaysShortRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysShortRegex')) {
this._weekdaysShortRegex = defaultWeekdaysShortRegex;
}
return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
}
}
function weekdaysMinRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysMinStrictRegex;
} else {
return this._weekdaysMinRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysMinRegex')) {
this._weekdaysMinRegex = defaultWeekdaysMinRegex;
}
return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
}
}
function computeWeekdaysParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var minPieces = [],
shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom,
minp,
shortp,
longp;
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
minp = regexEscape(this.weekdaysMin(mom, ''));
shortp = regexEscape(this.weekdaysShort(mom, ''));
longp = regexEscape(this.weekdays(mom, ''));
minPieces.push(minp);
shortPieces.push(shortp);
longPieces.push(longp);
mixedPieces.push(minp);
mixedPieces.push(shortp);
mixedPieces.push(longp);
}
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev);
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._weekdaysShortRegex = this._weekdaysRegex;
this._weekdaysMinRegex = this._weekdaysRegex;
this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function kFormat() {
return this.hours() || 24;
}
addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, hFormat);
addFormatToken('k', ['kk', 2], 0, kFormat);
addFormatToken('hmm', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});
addFormatToken('hmmss', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
});
addFormatToken('Hmm', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2);
});
addFormatToken('Hmmss', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
});
function meridiem(token, lowercase) {
addFormatToken(token, 0, 0, function () {
return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
});
}
meridiem('a', true);
meridiem('A', false);
// ALIASES
addUnitAlias('hour', 'h');
// PRIORITY
addUnitPriority('hour', 13);
// PARSING
function matchMeridiem(isStrict, locale) {
return locale._meridiemParse;
}
addRegexToken('a', matchMeridiem);
addRegexToken('A', matchMeridiem);
addRegexToken('H', match1to2);
addRegexToken('h', match1to2);
addRegexToken('k', match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);
addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);
addParseToken(['H', 'HH'], HOUR);
addParseToken(['k', 'kk'], function (input, array, config) {
var kInput = toInt(input);
array[HOUR] = kInput === 24 ? 0 : kInput;
});
addParseToken(['a', 'A'], function (input, array, config) {
config._isPm = config._locale.isPM(input);
config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
array[HOUR] = toInt(input);
getParsingFlags(config).bigHour = true;
});
addParseToken('hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
getParsingFlags(config).bigHour = true;
});
addParseToken('hmmss', function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
getParsingFlags(config).bigHour = true;
});
addParseToken('Hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
});
addParseToken('Hmmss', function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
});
// LOCALES
function localeIsPM(input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return (input + '').toLowerCase().charAt(0) === 'p';
}
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
// Setting the hour should keep the time, because the user explicitly
// specified which hour they want. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
getSetHour = makeGetSet('Hours', true);
function localeMeridiem(hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
}
var baseConfig = {
calendar: defaultCalendar,
longDateFormat: defaultLongDateFormat,
invalidDate: defaultInvalidDate,
ordinal: defaultOrdinal,
dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
relativeTime: defaultRelativeTime,
months: defaultLocaleMonths,
monthsShort: defaultLocaleMonthsShort,
week: defaultLocaleWeek,
weekdays: defaultLocaleWeekdays,
weekdaysMin: defaultLocaleWeekdaysMin,
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: defaultLocaleMeridiemParse
};
// internal storage for locale config files
var locales = {},
localeFamilies = {},
globalLocale;
function commonPrefix(arr1, arr2) {
var i,
minl = Math.min(arr1.length, arr2.length);
for (i = 0; i < minl; i += 1) {
if (arr1[i] !== arr2[i]) {
return i;
}
}
return minl;
}
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
var i = 0,
j,
next,
locale,
split;
while (i < names.length) {
split = normalizeLocale(names[i]).split('-');
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join('-'));
if (locale) {
return locale;
}
if (next && next.length >= j && commonPrefix(split, next) >= j - 1) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return globalLocale;
}
function isLocaleNameSane(name) {
// Prevent names that look like filesystem paths, i.e contain '/' or '\'
return name.match('^[^/\\\\]*$') != null;
}
function loadLocale(name) {
var oldLocale = null,
aliasedRequire;
// TODO: Find a better way to register and load all the locales in Node
if (locales[name] === undefined && 'object' !== 'undefined' && module && module.exports && isLocaleNameSane(name)) {
try {
oldLocale = globalLocale._abbr;
aliasedRequire = commonjsRequire;
aliasedRequire('./locale/' + name);
getSetGlobalLocale(oldLocale);
} catch (e) {
// mark as not found to avoid repeating expensive file require call causing high CPU
// when trying to find en-US, en_US, en-us for every format call
locales[name] = null; // null means not found
}
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale(key, values) {
var data;
if (key) {
if (isUndefined(values)) {
data = getLocale(key);
} else {
data = defineLocale(key, values);
}
if (data) {
// moment.duration._locale = moment._locale = data;
globalLocale = data;
} else {
if (typeof console !== 'undefined' && console.warn) {
//warn user if arguments are passed but the locale could not be set
console.warn('Locale ' + key + ' not found. Did you forget to load it?');
}
}
}
return globalLocale._abbr;
}
function defineLocale(name, config) {
if (config !== null) {
var locale,
parentConfig = baseConfig;
config.abbr = name;
if (locales[name] != null) {
deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
parentConfig = locales[name]._config;
} else if (config.parentLocale != null) {
if (locales[config.parentLocale] != null) {
parentConfig = locales[config.parentLocale]._config;
} else {
locale = loadLocale(config.parentLocale);
if (locale != null) {
parentConfig = locale._config;
} else {
if (!localeFamilies[config.parentLocale]) {
localeFamilies[config.parentLocale] = [];
}
localeFamilies[config.parentLocale].push({
name: name,
config: config
});
return null;
}
}
}
locales[name] = new Locale(mergeConfigs(parentConfig, config));
if (localeFamilies[name]) {
localeFamilies[name].forEach(function (x) {
defineLocale(x.name, x.config);
});
}
// backwards compat for now: also set the locale
// make sure we set the locale AFTER all child locales have been
// created, so we won't end up with the child locale set.
getSetGlobalLocale(name);
return locales[name];
} else {
// useful for testing
delete locales[name];
return null;
}
}
function updateLocale(name, config) {
if (config != null) {
var locale,
tmpLocale,
parentConfig = baseConfig;
if (locales[name] != null && locales[name].parentLocale != null) {
// Update existing child locale in-place to avoid memory-leaks
locales[name].set(mergeConfigs(locales[name]._config, config));
} else {
// MERGE
tmpLocale = loadLocale(name);
if (tmpLocale != null) {
parentConfig = tmpLocale._config;
}
config = mergeConfigs(parentConfig, config);
if (tmpLocale == null) {
// updateLocale is called for creating a new locale
// Set abbr so it will have a name (getters return
// undefined otherwise).
config.abbr = name;
}
locale = new Locale(config);
locale.parentLocale = locales[name];
locales[name] = locale;
}
// backwards compat for now: also set the locale
getSetGlobalLocale(name);
} else {
// pass null for config to unupdate, useful for tests
if (locales[name] != null) {
if (locales[name].parentLocale != null) {
locales[name] = locales[name].parentLocale;
if (name === getSetGlobalLocale()) {
getSetGlobalLocale(name);
}
} else if (locales[name] != null) {
delete locales[name];
}
}
}
return locales[name];
}
// returns locale data
function getLocale(key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
}
function listLocales() {
return keys(locales);
}
function checkOverflow(m) {
var overflow,
a = m._a;
if (a && getParsingFlags(m).overflow === -2) {
overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1;
if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
overflow = DATE;
}
if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
overflow = WEEK;
}
if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
overflow = WEEKDAY;
}
getParsingFlags(m).overflow = overflow;
}
return m;
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
isoDates = [['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/], ['YYYYMM', /\d{6}/, false], ['YYYY', /\d{4}/, false]],
// iso time formats and regexes
isoTimes = [['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/]],
aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,
obsOffsets = {
UT: 0,
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60
};
// date from iso format
function configFromISO(config) {
var i,
l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime,
dateFormat,
timeFormat,
tzFormat,
isoDatesLen = isoDates.length,
isoTimesLen = isoTimes.length;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDatesLen; i < l; i++) {
if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0];
allowTime = isoDates[i][2] !== false;
break;
}
}
if (dateFormat == null) {
config._isValid = false;
return;
}
if (match[3]) {
for (i = 0, l = isoTimesLen; i < l; i++) {
if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || ' ') + isoTimes[i][0];
break;
}
}
if (timeFormat == null) {
config._isValid = false;
return;
}
}
if (!allowTime && timeFormat != null) {
config._isValid = false;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) {
tzFormat = 'Z';
} else {
config._isValid = false;
return;
}
}
config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
configFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
var result = [untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10)];
if (secondStr) {
result.push(parseInt(secondStr, 10));
}
return result;
}
function untruncateYear(yearStr) {
var year = parseInt(yearStr, 10);
if (year <= 49) {
return 2000 + year;
} else if (year <= 999) {
return 1900 + year;
}
return year;
}
function preprocessRFC2822(s) {
// Remove comments and folding whitespace and replace multiple-spaces with a single space
return s.replace(/\([^()]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function checkWeekday(weekdayStr, parsedInput, config) {
if (weekdayStr) {
// TODO: Replace the vanilla JS Date object with an independent day-of-week check.
var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
if (weekdayProvided !== weekdayActual) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return false;
}
}
return true;
}
function calculateOffset(obsOffset, militaryOffset, numOffset) {
if (obsOffset) {
return obsOffsets[obsOffset];
} else if (militaryOffset) {
// the only allowed military tz is Z
return 0;
} else {
var hm = parseInt(numOffset, 10),
m = hm % 100,
h = (hm - m) / 100;
return h * 60 + m;
}
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i)),
parsedArray;
if (match) {
parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
if (!checkWeekday(match[1], parsedArray, config)) {
return;
}
config._a = parsedArray;
config._tzm = calculateOffset(match[8], match[9], match[10]);
config._d = createUTCDate.apply(null, config._a);
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
getParsingFlags(config).rfc2822 = true;
} else {
config._isValid = false;
}
}
// date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
function configFromString(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (matched !== null) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
configFromRFC2822(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
if (config._strict) {
config._isValid = false;
} else {
// Final attempt, use Input Fallback
hooks.createFromInputFallback(config);
}
}
hooks.createFromInputFallback = deprecate('value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
});
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return c;
}
function currentDateArray(config) {
// hooks is actually the exported moment object
var nowValue = new Date(hooks.now());
if (config._useUTC) {
return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
}
return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray(config) {
var i,
date,
input = [],
currentDate,
expectedWeekday,
yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
//compute day of the year from weeks and weekdays
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
//if the day of the year is set, figure out what it is
if (config._dayOfYear != null) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
getParsingFlags(config)._overflowDayOfYear = true;
}
date = createUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
// Zero out whatever was not defaulted, including time
for (; i < 7; i++) {
config._a[i] = input[i] = config._a[i] == null ? i === 2 ? 1 : 0 : config._a[i];
}
// Check for 24:00:00.000
if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
// Apply timezone offset from input. The actual utcOffset can be changed
// with parseZone.
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
// check for mismatching day of week
if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
getParsingFlags(config).weekdayMismatch = true;
}
}
function dayOfYearFromWeekInfo(config) {
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
// TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
week = defaults(w.W, 1);
weekday = defaults(w.E, 1);
if (weekday < 1 || weekday > 7) {
weekdayOverflow = true;
}
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
curWeek = weekOfYear(createLocal(), dow, doy);
weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
// Default to current week.
week = defaults(w.w, curWeek.week);
if (w.d != null) {
// weekday -- low day numbers are considered next week
weekday = w.d;
if (weekday < 0 || weekday > 6) {
weekdayOverflow = true;
}
} else if (w.e != null) {
// local weekday -- counting starts from beginning of week
weekday = w.e + dow;
if (w.e < 0 || w.e > 6) {
weekdayOverflow = true;
}
} else {
// default to beginning of week
weekday = dow;
}
}
if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
getParsingFlags(config)._overflowWeeks = true;
} else if (weekdayOverflow != null) {
getParsingFlags(config)._overflowWeekday = true;
} else {
temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
}
// constant that refers to the ISO standard
hooks.ISO_8601 = function () {};
// constant that refers to the RFC 2822 form
hooks.RFC_2822 = function () {};
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === hooks.ISO_8601) {
configFromISO(config);
return;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(config);
return;
}
config._a = [];
getParsingFlags(config).empty = true;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var string = '' + config._i,
i,
parsedInput,
tokens,
token,
skipped,
stringLength = string.length,
totalParsedInputLength = 0,
era,
tokenLen;
tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
tokenLen = tokens.length;
for (i = 0; i < tokenLen; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
getParsingFlags(config).unusedInput.push(skipped);
}
string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
totalParsedInputLength += parsedInput.length;
}
// don't parse if it's not a known token
if (formatTokenFunctions[token]) {
if (parsedInput) {
getParsingFlags(config).empty = false;
} else {
getParsingFlags(config).unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
} else if (config._strict && !parsedInput) {
getParsingFlags(config).unusedTokens.push(token);
}
}
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
if (string.length > 0) {
getParsingFlags(config).unusedInput.push(string);
}
// clear _12h flag if hour is <= 12
if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) {
getParsingFlags(config).bigHour = undefined;
}
getParsingFlags(config).parsedDateParts = config._a.slice(0);
getParsingFlags(config).meridiem = config._meridiem;
// handle meridiem
config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
// handle era
era = getParsingFlags(config).era;
if (era !== null) {
config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
}
configFromArray(config);
checkOverflow(config);
}
function meridiemFixWrap(locale, hour, meridiem) {
var isPm;
if (meridiem == null) {
// nothing to do
return hour;
}
if (locale.meridiemHour != null) {
return locale.meridiemHour(hour, meridiem);
} else if (locale.isPM != null) {
// Fallback
isPm = locale.isPM(meridiem);
if (isPm && hour < 12) {
hour += 12;
}
if (!isPm && hour === 12) {
hour = 0;
}
return hour;
} else {
// this is not supposed to happen
return hour;
}
}
// date from string and array of format strings
function configFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore,
validFormatFound,
bestFormatIsValid = false,
configfLen = config._f.length;
if (configfLen === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < configfLen; i++) {
currentScore = 0;
validFormatFound = false;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (isValid(tempConfig)) {
validFormatFound = true;
}
// if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver;
//or tokens
currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
getParsingFlags(tempConfig).score = currentScore;
if (!bestFormatIsValid) {
if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
if (validFormatFound) {
bestFormatIsValid = true;
}
}
} else {
if (currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i),
dayOrDate = i.day === undefined ? i.date : i.day;
config._a = map([i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], function (obj) {
return obj && parseInt(obj, 10);
});
configFromArray(config);
}
function createFromConfig(config) {
var res = new Moment(checkOverflow(prepareConfig(config)));
if (res._nextDay) {
// Adding is smart enough around DST
res.add(1, 'd');
res._nextDay = undefined;
}
return res;
}
function prepareConfig(config) {
var input = config._i,
format = config._f;
config._locale = config._locale || getLocale(config._l);
if (input === null || format === undefined && input === '') {
return createInvalid({
nullInput: true
});
}
if (typeof input === 'string') {
config._i = input = config._locale.preparse(input);
}
if (isMoment(input)) {
return new Moment(checkOverflow(input));
} else if (isDate(input)) {
config._d = input;
} else if (isArray(format)) {
configFromStringAndArray(config);
} else if (format) {
configFromStringAndFormat(config);
} else {
configFromInput(config);
}
if (!isValid(config)) {
config._d = null;
}
return config;
}
function configFromInput(config) {
var input = config._i;
if (isUndefined(input)) {
config._d = new Date(hooks.now());
} else if (isDate(input)) {
config._d = new Date(input.valueOf());
} else if (typeof input === 'string') {
configFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
configFromArray(config);
} else if (isObject(input)) {
configFromObject(config);
} else if (isNumber(input)) {
// from milliseconds
config._d = new Date(input);
} else {
hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC(input, format, locale, strict, isUTC) {
var c = {};
if (format === true || format === false) {
strict = format;
format = undefined;
}
if (locale === true || locale === false) {
strict = locale;
locale = undefined;
}
if (isObject(input) && isObjectEmpty(input) || isArray(input) && input.length === 0) {
input = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = true;
c._useUTC = c._isUTC = isUTC;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
return createFromConfig(c);
}
function createLocal(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, false);
}
var prototypeMin = deprecate('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return createInvalid();
}
}),
prototypeMax = deprecate('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return createInvalid();
}
});
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
function min() {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
function max() {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
var now = function () {
return Date.now ? Date.now() : +new Date();
};
var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
function isDurationValid(m) {
var key,
unitHasDecimal = false,
i,
orderLen = ordering.length;
for (key in m) {
if (hasOwnProp(m, key) && !(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
return false;
}
}
for (i = 0; i < orderLen; ++i) {
if (m[ordering[i]]) {
if (unitHasDecimal) {
return false; // only allow non-integers for smallest unit
}
if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
unitHasDecimal = true;
}
}
}
return true;
}
function isValid$1() {
return this._isValid;
}
function createInvalid$1() {
return createDuration(NaN);
}
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
this._isValid = isDurationValid(normalizedInput);
// representation for dateAddRemove
this._milliseconds = +milliseconds + seconds * 1e3 +
// 1000
minutes * 6e4 +
// 1000 * 60
hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
// Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days + weeks * 7;
// It is impossible to translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months + quarters * 3 + years * 12;
this._data = {};
this._locale = getLocale();
this._bubble();
}
function isDuration(obj) {
return obj instanceof Duration;
}
function absRound(number) {
if (number < 0) {
return Math.round(-1 * number) * -1;
} else {
return Math.round(number);
}
}
// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) {
diffs++;
}
}
return diffs + lengthDiff;
}
// FORMATTING
function offset(token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset(),
sign = '+';
if (offset < 0) {
offset = -offset;
sign = '-';
}
return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
});
}
offset('Z', ':');
offset('ZZ', '');
// PARSING
addRegexToken('Z', matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var matches = (string || '').match(matcher),
chunk,
parts,
minutes;
if (matches === null) {
return null;
}
chunk = matches[matches.length - 1] || [];
parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
minutes = +(parts[1] * 60) + toInt(parts[2]);
return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
// Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff);
hooks.updateOffset(res, false);
return res;
} else {
return createLocal(input).local();
}
}
function getDateOffset(m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset());
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};
// MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset(input, keepLocalTime, keepMinutes) {
var offset = this._offset || 0,
localAdjust;
if (!this.isValid()) {
return input != null ? this : NaN;
}
if (input != null) {
if (typeof input === 'string') {
input = offsetFromString(matchShortOffset, input);
if (input === null) {
return this;
}
} else if (Math.abs(input) < 16 && !keepMinutes) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
addSubtract(this, createDuration(input - offset, 'm'), 1, false);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
function getSetZone(input, keepLocalTime) {
if (input != null) {
if (typeof input !== 'string') {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
function setOffsetToUTC(keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
function setOffsetToLocal(keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), 'm');
}
}
return this;
}
function setOffsetToParsedOffset() {
if (this._tzm != null) {
this.utcOffset(this._tzm, false, true);
} else if (typeof this._i === 'string') {
var tZone = offsetFromString(matchOffset, this._i);
if (tZone != null) {
this.utcOffset(tZone);
} else {
this.utcOffset(0, true);
}
}
return this;
}
function hasAlignedHourOffset(input) {
if (!this.isValid()) {
return false;
}
input = input ? createLocal(input).utcOffset() : 0;
return (this.utcOffset() - input) % 60 === 0;
}
function isDaylightSavingTime() {
return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
}
function isDaylightSavingTimeShifted() {
if (!isUndefined(this._isDSTShifted)) {
return this._isDSTShifted;
}
var c = {},
other;
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0;
} else {
this._isDSTShifted = false;
}
return this._isDSTShifted;
}
function isLocal() {
return this.isValid() ? !this._isUTC : false;
}
function isUtcOffset() {
return this.isValid() ? this._isUTC : false;
}
function isUtc() {
return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
// ASP.NET json date format regex
var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
function createDuration(input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms: input._milliseconds,
d: input._days,
M: input._months
};
} else if (isNumber(input) || !isNaN(+input)) {
duration = {};
if (key) {
duration[key] = +input;
} else {
duration.milliseconds = +input;
}
} else if (match = aspNetRegex.exec(input)) {
sign = match[1] === '-' ? -1 : 1;
duration = {
y: 0,
d: toInt(match[DATE]) * sign,
h: toInt(match[HOUR]) * sign,
m: toInt(match[MINUTE]) * sign,
s: toInt(match[SECOND]) * sign,
ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
};
} else if (match = isoRegex.exec(input)) {
sign = match[1] === '-' ? -1 : 1;
duration = {
y: parseIso(match[2], sign),
M: parseIso(match[3], sign),
w: parseIso(match[4], sign),
d: parseIso(match[5], sign),
h: parseIso(match[6], sign),
m: parseIso(match[7], sign),
s: parseIso(match[8], sign)
};
} else if (duration == null) {
// checks for null or undefined
duration = {};
} else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
if (isDuration(input) && hasOwnProp(input, '_isValid')) {
ret._isValid = input._isValid;
}
return ret;
}
createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;
function parseIso(inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {};
res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +base.clone().add(res.months, 'M');
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return {
milliseconds: 0,
months: 0
};
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
//invert the arguments, but complain about it
if (period !== null && !isNaN(+period)) {
deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
tmp = val;
val = period;
period = tmp;
}
dur = createDuration(val, period);
addSubtract(this, dur, direction);
return this;
};
}
function addSubtract(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = absRound(duration._days),
months = absRound(duration._months);
if (!mom.isValid()) {
// No op
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (months) {
setMonth(mom, get(mom, 'Month') + months * isAdding);
}
if (days) {
set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
}
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
}
if (updateOffset) {
hooks.updateOffset(mom, days || months);
}
}
var add = createAdder(1, 'add'),
subtract = createAdder(-1, 'subtract');
function isString(input) {
return typeof input === 'string' || input instanceof String;
}
// type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
function isMomentInput(input) {
return isMoment(input) || isDate(input) || isString(input) || isNumber(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === undefined;
}
function isMomentInputObject(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = ['years', 'year', 'y', 'months', 'month', 'M', 'days', 'day', 'd', 'dates', 'date', 'D', 'hours', 'hour', 'h', 'minutes', 'minute', 'm', 'seconds', 'second', 's', 'milliseconds', 'millisecond', 'ms'],
i,
property,
propertyLen = properties.length;
for (i = 0; i < propertyLen; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function isNumberOrStringArray(input) {
var arrayTest = isArray(input),
dataTypeTest = false;
if (arrayTest) {
dataTypeTest = input.filter(function (item) {
return !isNumber(item) && isString(input);
}).length === 0;
}
return arrayTest && dataTypeTest;
}
function isCalendarSpec(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = ['sameDay', 'nextDay', 'lastDay', 'nextWeek', 'lastWeek', 'sameElse'],
i,
property;
for (i = 0; i < properties.length; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function getCalendarFormat(myMoment, now) {
var diff = myMoment.diff(now, 'days', true);
return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse';
}
function calendar$1(time, formats) {
// Support for single parameter, formats only overload to the calendar function
if (arguments.length === 1) {
if (!arguments[0]) {
time = undefined;
formats = undefined;
} else if (isMomentInput(arguments[0])) {
time = arguments[0];
formats = undefined;
} else if (isCalendarSpec(arguments[0])) {
formats = arguments[0];
time = undefined;
}
}
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || createLocal(),
sod = cloneWithOffset(now, this).startOf('day'),
format = hooks.calendarFormat(this, sod) || 'sameElse',
output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
}
function clone() {
return new Moment(this);
}
function isAfter(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() > localInput.valueOf();
} else {
return localInput.valueOf() < this.clone().startOf(units).valueOf();
}
}
function isBefore(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() < localInput.valueOf();
} else {
return this.clone().endOf(units).valueOf() < localInput.valueOf();
}
}
function isBetween(from, to, units, inclusivity) {
var localFrom = isMoment(from) ? from : createLocal(from),
localTo = isMoment(to) ? to : createLocal(to);
if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
return false;
}
inclusivity = inclusivity || '()';
return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
}
function isSame(input, units) {
var localInput = isMoment(input) ? input : createLocal(input),
inputMs;
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() === localInput.valueOf();
} else {
inputMs = localInput.valueOf();
return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
}
}
function isSameOrAfter(input, units) {
return this.isSame(input, units) || this.isAfter(input, units);
}
function isSameOrBefore(input, units) {
return this.isSame(input, units) || this.isBefore(input, units);
}
function diff(input, units, asFloat) {
var that, zoneDelta, output;
if (!this.isValid()) {
return NaN;
}
that = cloneWithOffset(input, this);
if (!that.isValid()) {
return NaN;
}
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
units = normalizeUnits(units);
switch (units) {
case 'year':
output = monthDiff(this, that) / 12;
break;
case 'month':
output = monthDiff(this, that);
break;
case 'quarter':
output = monthDiff(this, that) / 3;
break;
case 'second':
output = (this - that) / 1e3;
break;
// 1000
case 'minute':
output = (this - that) / 6e4;
break;
// 1000 * 60
case 'hour':
output = (this - that) / 36e5;
break;
// 1000 * 60 * 60
case 'day':
output = (this - that - zoneDelta) / 864e5;
break;
// 1000 * 60 * 60 * 24, negate dst
case 'week':
output = (this - that - zoneDelta) / 6048e5;
break;
// 1000 * 60 * 60 * 24 * 7, negate dst
default:
output = this - that;
}
return asFloat ? output : absFloor(output);
}
function monthDiff(a, b) {
if (a.date() < b.date()) {
// end-of-month calculations work correct when the start month has more
// days than the end month.
return -monthDiff(b, a);
}
// difference in months
var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, 'months'),
anchor2,
adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor2 - anchor);
}
//check for negative zero, return zero if negative zero
return -(wholeMonthDiff + adjust) || 0;
}
hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
function toString() {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}
function toISOString(keepOffset) {
if (!this.isValid()) {
return null;
}
var utc = keepOffset !== true,
m = utc ? this.clone().utc() : this;
if (m.year() < 0 || m.year() > 9999) {
return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
}
if (isFunction(Date.prototype.toISOString)) {
// native implementation is ~50x faster, use it when we can
if (utc) {
return this.toDate().toISOString();
} else {
return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
}
}
return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
}
/**
* Return a human readable representation of a moment that can
* also be evaluated to get a new moment which is the same
*
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
*/
function inspect() {
if (!this.isValid()) {
return 'moment.invalid(/* ' + this._i + ' */)';
}
var func = 'moment',
zone = '',
prefix,
year,
datetime,
suffix;
if (!this.isLocal()) {
func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
zone = 'Z';
}
prefix = '[' + func + '("]';
year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
datetime = '-MM-DD[T]HH:mm:ss.SSS';
suffix = zone + '[")]';
return this.format(prefix + year + datetime + suffix);
}
function format(inputString) {
if (!inputString) {
inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
}
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}
function from(time, withoutSuffix) {
if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
return createDuration({
to: this,
from: time
}).locale(this.locale()).humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function fromNow(withoutSuffix) {
return this.from(createLocal(), withoutSuffix);
}
function to(time, withoutSuffix) {
if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
return createDuration({
from: this,
to: time
}).locale(this.locale()).humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function toNow(withoutSuffix) {
return this.to(createLocal(), withoutSuffix);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale(key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = getLocale(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
}
var lang = deprecate('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
});
function localeData() {
return this._locale;
}
var MS_PER_SECOND = 1000,
MS_PER_MINUTE = 60 * MS_PER_SECOND,
MS_PER_HOUR = 60 * MS_PER_MINUTE,
MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
// actual modulo - handles negative numbers (for dates before 1970):
function mod$1(dividend, divisor) {
return (dividend % divisor + divisor) % divisor;
}
function localStartOfDate(y, m, d) {
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return new Date(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return new Date(y, m, d).valueOf();
}
}
function utcStartOfDate(y, m, d) {
// Date.UTC remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return Date.UTC(y, m, d);
}
}
function startOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year(), 0, 1);
break;
case 'quarter':
time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
break;
case 'month':
time = startOfDate(this.year(), this.month(), 1);
break;
case 'week':
time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
break;
case 'isoWeek':
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date());
break;
case 'hour':
time = this._d.valueOf();
time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
break;
case 'minute':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_MINUTE);
break;
case 'second':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_SECOND);
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function endOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year() + 1, 0, 1) - 1;
break;
case 'quarter':
time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
break;
case 'month':
time = startOfDate(this.year(), this.month() + 1, 1) - 1;
break;
case 'week':
time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
break;
case 'isoWeek':
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
break;
case 'hour':
time = this._d.valueOf();
time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
break;
case 'minute':
time = this._d.valueOf();
time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
break;
case 'second':
time = this._d.valueOf();
time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function valueOf() {
return this._d.valueOf() - (this._offset || 0) * 60000;
}
function unix() {
return Math.floor(this.valueOf() / 1000);
}
function toDate() {
return new Date(this.valueOf());
}
function toArray() {
var m = this;
return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
}
function toObject() {
var m = this;
return {
years: m.year(),
months: m.month(),
date: m.date(),
hours: m.hours(),
minutes: m.minutes(),
seconds: m.seconds(),
milliseconds: m.milliseconds()
};
}
function toJSON() {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}
function isValid$2() {
return isValid(this);
}
function parsingFlags() {
return extend({}, getParsingFlags(this));
}
function invalidAt() {
return getParsingFlags(this).overflow;
}
function creationData() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict
};
}
addFormatToken('N', 0, 0, 'eraAbbr');
addFormatToken('NN', 0, 0, 'eraAbbr');
addFormatToken('NNN', 0, 0, 'eraAbbr');
addFormatToken('NNNN', 0, 0, 'eraName');
addFormatToken('NNNNN', 0, 0, 'eraNarrow');
addFormatToken('y', ['y', 1], 'yo', 'eraYear');
addFormatToken('y', ['yy', 2], 0, 'eraYear');
addFormatToken('y', ['yyy', 3], 0, 'eraYear');
addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
addRegexToken('N', matchEraAbbr);
addRegexToken('NN', matchEraAbbr);
addRegexToken('NNN', matchEraAbbr);
addRegexToken('NNNN', matchEraName);
addRegexToken('NNNNN', matchEraNarrow);
addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (input, array, config, token) {
var era = config._locale.erasParse(input, token, config._strict);
if (era) {
getParsingFlags(config).era = era;
} else {
getParsingFlags(config).invalidEra = input;
}
});
addRegexToken('y', matchUnsigned);
addRegexToken('yy', matchUnsigned);
addRegexToken('yyy', matchUnsigned);
addRegexToken('yyyy', matchUnsigned);
addRegexToken('yo', matchEraYearOrdinal);
addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
addParseToken(['yo'], function (input, array, config, token) {
var match;
if (config._locale._eraYearOrdinalRegex) {
match = input.match(config._locale._eraYearOrdinalRegex);
}
if (config._locale.eraYearOrdinalParse) {
array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
} else {
array[YEAR] = parseInt(input, 10);
}
});
function localeEras(m, format) {
var i,
l,
date,
eras = this._eras || getLocale('en')._eras;
for (i = 0, l = eras.length; i < l; ++i) {
switch (typeof eras[i].since) {
case 'string':
// truncate time
date = hooks(eras[i].since).startOf('day');
eras[i].since = date.valueOf();
break;
}
switch (typeof eras[i].until) {
case 'undefined':
eras[i].until = +Infinity;
break;
case 'string':
// truncate time
date = hooks(eras[i].until).startOf('day').valueOf();
eras[i].until = date.valueOf();
break;
}
}
return eras;
}
function localeErasParse(eraName, format, strict) {
var i,
l,
eras = this.eras(),
name,
abbr,
narrow;
eraName = eraName.toUpperCase();
for (i = 0, l = eras.length; i < l; ++i) {
name = eras[i].name.toUpperCase();
abbr = eras[i].abbr.toUpperCase();
narrow = eras[i].narrow.toUpperCase();
if (strict) {
switch (format) {
case 'N':
case 'NN':
case 'NNN':
if (abbr === eraName) {
return eras[i];
}
break;
case 'NNNN':
if (name === eraName) {
return eras[i];
}
break;
case 'NNNNN':
if (narrow === eraName) {
return eras[i];
}
break;
}
} else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
return eras[i];
}
}
}
function localeErasConvertYear(era, year) {
var dir = era.since <= era.until ? +1 : -1;
if (year === undefined) {
return hooks(era.since).year();
} else {
return hooks(era.since).year() + (year - era.offset) * dir;
}
}
function getEraName() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].name;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].name;
}
}
return '';
}
function getEraNarrow() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].narrow;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].narrow;
}
}
return '';
}
function getEraAbbr() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].abbr;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].abbr;
}
}
return '';
}
function getEraYear() {
var i,
l,
dir,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
dir = eras[i].since <= eras[i].until ? +1 : -1;
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) {
return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset;
}
}
return this.year();
}
function erasNameRegex(isStrict) {
if (!hasOwnProp(this, '_erasNameRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasNameRegex : this._erasRegex;
}
function erasAbbrRegex(isStrict) {
if (!hasOwnProp(this, '_erasAbbrRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasAbbrRegex : this._erasRegex;
}
function erasNarrowRegex(isStrict) {
if (!hasOwnProp(this, '_erasNarrowRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasNarrowRegex : this._erasRegex;
}
function matchEraAbbr(isStrict, locale) {
return locale.erasAbbrRegex(isStrict);
}
function matchEraName(isStrict, locale) {
return locale.erasNameRegex(isStrict);
}
function matchEraNarrow(isStrict, locale) {
return locale.erasNarrowRegex(isStrict);
}
function matchEraYearOrdinal(isStrict, locale) {
return locale._eraYearOrdinalRegex || matchUnsigned;
}
function computeErasParse() {
var abbrPieces = [],
namePieces = [],
narrowPieces = [],
mixedPieces = [],
i,
l,
eras = this.eras();
for (i = 0, l = eras.length; i < l; ++i) {
namePieces.push(regexEscape(eras[i].name));
abbrPieces.push(regexEscape(eras[i].abbr));
narrowPieces.push(regexEscape(eras[i].narrow));
mixedPieces.push(regexEscape(eras[i].name));
mixedPieces.push(regexEscape(eras[i].abbr));
mixedPieces.push(regexEscape(eras[i].narrow));
}
this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
this._erasNarrowRegex = new RegExp('^(' + narrowPieces.join('|') + ')', 'i');
}
// FORMATTING
addFormatToken(0, ['gg', 2], 0, function () {
return this.weekYear() % 100;
});
addFormatToken(0, ['GG', 2], 0, function () {
return this.isoWeekYear() % 100;
});
function addWeekYearFormatToken(token, getter) {
addFormatToken(0, [token, token.length], 0, getter);
}
addWeekYearFormatToken('gggg', 'weekYear');
addWeekYearFormatToken('ggggg', 'weekYear');
addWeekYearFormatToken('GGGG', 'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');
// ALIASES
addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');
// PRIORITY
addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);
// PARSING
addRegexToken('G', matchSigned);
addRegexToken('g', matchSigned);
addRegexToken('GG', match1to2, match2);
addRegexToken('gg', match1to2, match2);
addRegexToken('GGGG', match1to4, match4);
addRegexToken('gggg', match1to4, match4);
addRegexToken('GGGGG', match1to6, match6);
addRegexToken('ggggg', match1to6, match6);
addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
});
addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
week[token] = hooks.parseTwoDigitYear(input);
});
// MOMENTS
function getSetWeekYear(input) {
return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
}
function getSetISOWeekYear(input) {
return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
}
function getISOWeeksInYear() {
return weeksInYear(this.year(), 1, 4);
}
function getISOWeeksInISOWeekYear() {
return weeksInYear(this.isoWeekYear(), 1, 4);
}
function getWeeksInYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}
function getWeeksInWeekYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
if (input == null) {
return weekOfYear(this, dow, doy).year;
} else {
weeksTarget = weeksInYear(input, dow, doy);
if (week > weeksTarget) {
week = weeksTarget;
}
return setWeekAll.call(this, input, week, weekday, dow, doy);
}
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
this.year(date.getUTCFullYear());
this.month(date.getUTCMonth());
this.date(date.getUTCDate());
return this;
}
// FORMATTING
addFormatToken('Q', 0, 'Qo', 'quarter');
// ALIASES
addUnitAlias('quarter', 'Q');
// PRIORITY
addUnitPriority('quarter', 7);
// PARSING
addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
array[MONTH] = (toInt(input) - 1) * 3;
});
// MOMENTS
function getSetQuarter(input) {
return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}
// FORMATTING
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIORITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0]);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet('Date', true);
// FORMATTING
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
// ALIASES
addUnitAlias('dayOfYear', 'DDD');
// PRIORITY
addUnitPriority('dayOfYear', 4);
// PARSING
addRegexToken('DDD', match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
config._dayOfYear = toInt(input);
});
// HELPERS
// MOMENTS
function getSetDayOfYear(input) {
var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
}
// FORMATTING
addFormatToken('m', ['mm', 2], 0, 'minute');
// ALIASES
addUnitAlias('minute', 'm');
// PRIORITY
addUnitPriority('minute', 14);
// PARSING
addRegexToken('m', match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);
// MOMENTS
var getSetMinute = makeGetSet('Minutes', false);
// FORMATTING
addFormatToken('s', ['ss', 2], 0, 'second');
// ALIASES
addUnitAlias('second', 's');
// PRIORITY
addUnitPriority('second', 15);
// PARSING
addRegexToken('s', match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);
// MOMENTS
var getSetSecond = makeGetSet('Seconds', false);
// FORMATTING
addFormatToken('S', 0, 0, function () {
return ~~(this.millisecond() / 100);
});
addFormatToken(0, ['SS', 2], 0, function () {
return ~~(this.millisecond() / 10);
});
addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
return this.millisecond() * 1000000;
});
// ALIASES
addUnitAlias('millisecond', 'ms');
// PRIORITY
addUnitPriority('millisecond', 16);
// PARSING
addRegexToken('S', match1to3, match1);
addRegexToken('SS', match1to3, match2);
addRegexToken('SSS', match1to3, match3);
var token, getSetMillisecond;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
addRegexToken(token, matchUnsigned);
}
function parseMs(input, array) {
array[MILLISECOND] = toInt(('0.' + input) * 1000);
}
for (token = 'S'; token.length <= 9; token += 'S') {
addParseToken(token, parseMs);
}
getSetMillisecond = makeGetSet('Milliseconds', false);
// FORMATTING
addFormatToken('z', 0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');
// MOMENTS
function getZoneAbbr() {
return this._isUTC ? 'UTC' : '';
}
function getZoneName() {
return this._isUTC ? 'Coordinated Universal Time' : '';
}
var proto = Moment.prototype;
proto.add = add;
proto.calendar = calendar$1;
proto.clone = clone;
proto.diff = diff;
proto.endOf = endOf;
proto.format = format;
proto.from = from;
proto.fromNow = fromNow;
proto.to = to;
proto.toNow = toNow;
proto.get = stringGet;
proto.invalidAt = invalidAt;
proto.isAfter = isAfter;
proto.isBefore = isBefore;
proto.isBetween = isBetween;
proto.isSame = isSame;
proto.isSameOrAfter = isSameOrAfter;
proto.isSameOrBefore = isSameOrBefore;
proto.isValid = isValid$2;
proto.lang = lang;
proto.locale = locale;
proto.localeData = localeData;
proto.max = prototypeMax;
proto.min = prototypeMin;
proto.parsingFlags = parsingFlags;
proto.set = stringSet;
proto.startOf = startOf;
proto.subtract = subtract;
proto.toArray = toArray;
proto.toObject = toObject;
proto.toDate = toDate;
proto.toISOString = toISOString;
proto.inspect = inspect;
if (typeof Symbol !== 'undefined' && Symbol.for != null) {
proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
return 'Moment<' + this.format() + '>';
};
}
proto.toJSON = toJSON;
proto.toString = toString;
proto.unix = unix;
proto.valueOf = valueOf;
proto.creationData = creationData;
proto.eraName = getEraName;
proto.eraNarrow = getEraNarrow;
proto.eraAbbr = getEraAbbr;
proto.eraYear = getEraYear;
proto.year = getSetYear;
proto.isLeapYear = getIsLeapYear;
proto.weekYear = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;
proto.quarter = proto.quarters = getSetQuarter;
proto.month = getSetMonth;
proto.daysInMonth = getDaysInMonth;
proto.week = proto.weeks = getSetWeek;
proto.isoWeek = proto.isoWeeks = getSetISOWeek;
proto.weeksInYear = getWeeksInYear;
proto.weeksInWeekYear = getWeeksInWeekYear;
proto.isoWeeksInYear = getISOWeeksInYear;
proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
proto.date = getSetDayOfMonth;
proto.day = proto.days = getSetDayOfWeek;
proto.weekday = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear = getSetDayOfYear;
proto.hour = proto.hours = getSetHour;
proto.minute = proto.minutes = getSetMinute;
proto.second = proto.seconds = getSetSecond;
proto.millisecond = proto.milliseconds = getSetMillisecond;
proto.utcOffset = getSetOffset;
proto.utc = setOffsetToUTC;
proto.local = setOffsetToLocal;
proto.parseZone = setOffsetToParsedOffset;
proto.hasAlignedHourOffset = hasAlignedHourOffset;
proto.isDST = isDaylightSavingTime;
proto.isLocal = isLocal;
proto.isUtcOffset = isUtcOffset;
proto.isUtc = isUtc;
proto.isUTC = isUtc;
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;
proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
function createUnix(input) {
return createLocal(input * 1000);
}
function createInZone() {
return createLocal.apply(null, arguments).parseZone();
}
function preParsePostFormat(string) {
return string;
}
var proto$1 = Locale.prototype;
proto$1.calendar = calendar;
proto$1.longDateFormat = longDateFormat;
proto$1.invalidDate = invalidDate;
proto$1.ordinal = ordinal;
proto$1.preparse = preParsePostFormat;
proto$1.postformat = preParsePostFormat;
proto$1.relativeTime = relativeTime;
proto$1.pastFuture = pastFuture;
proto$1.set = set;
proto$1.eras = localeEras;
proto$1.erasParse = localeErasParse;
proto$1.erasConvertYear = localeErasConvertYear;
proto$1.erasAbbrRegex = erasAbbrRegex;
proto$1.erasNameRegex = erasNameRegex;
proto$1.erasNarrowRegex = erasNarrowRegex;
proto$1.months = localeMonths;
proto$1.monthsShort = localeMonthsShort;
proto$1.monthsParse = localeMonthsParse;
proto$1.monthsRegex = monthsRegex;
proto$1.monthsShortRegex = monthsShortRegex;
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;
proto$1.weekdays = localeWeekdays;
proto$1.weekdaysMin = localeWeekdaysMin;
proto$1.weekdaysShort = localeWeekdaysShort;
proto$1.weekdaysParse = localeWeekdaysParse;
proto$1.weekdaysRegex = weekdaysRegex;
proto$1.weekdaysShortRegex = weekdaysShortRegex;
proto$1.weekdaysMinRegex = weekdaysMinRegex;
proto$1.isPM = localeIsPM;
proto$1.meridiem = localeMeridiem;
function get$1(format, index, field, setter) {
var locale = getLocale(),
utc = createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl(format, index, field) {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
if (index != null) {
return get$1(format, index, field, 'month');
}
var i,
out = [];
for (i = 0; i < 12; i++) {
out[i] = get$1(format, i, field, 'month');
}
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl(localeSorted, format, index, field) {
if (typeof localeSorted === 'boolean') {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
} else {
format = localeSorted;
index = format;
localeSorted = false;
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
}
var locale = getLocale(),
shift = localeSorted ? locale._week.dow : 0,
i,
out = [];
if (index != null) {
return get$1(format, (index + shift) % 7, field, 'day');
}
for (i = 0; i < 7; i++) {
out[i] = get$1(format, (i + shift) % 7, field, 'day');
}
return out;
}
function listMonths(format, index) {
return listMonthsImpl(format, index, 'months');
}
function listMonthsShort(format, index) {
return listMonthsImpl(format, index, 'monthsShort');
}
function listWeekdays(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}
function listWeekdaysShort(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}
function listWeekdaysMin(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}
getSetGlobalLocale('en', {
eras: [{
since: '0001-01-01',
until: +Infinity,
offset: 1,
name: 'Anno Domini',
narrow: 'AD',
abbr: 'AD'
}, {
since: '0000-12-31',
until: -Infinity,
offset: 1,
name: 'Before Christ',
narrow: 'BC',
abbr: 'BC'
}],
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: function (number) {
var b = number % 10,
output = toInt(number % 100 / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th';
return number + output;
}
});
// Side effect imports
hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
var mathAbs = Math.abs;
function abs() {
var data = this._data;
this._milliseconds = mathAbs(this._milliseconds);
this._days = mathAbs(this._days);
this._months = mathAbs(this._months);
data.milliseconds = mathAbs(data.milliseconds);
data.seconds = mathAbs(data.seconds);
data.minutes = mathAbs(data.minutes);
data.hours = mathAbs(data.hours);
data.months = mathAbs(data.months);
data.years = mathAbs(data.years);
return this;
}
function addSubtract$1(duration, input, value, direction) {
var other = createDuration(input, value);
duration._milliseconds += direction * other._milliseconds;
duration._days += direction * other._days;
duration._months += direction * other._months;
return duration._bubble();
}
// supports only 2.0-style add(1, 's') or add(duration)
function add$1(input, value) {
return addSubtract$1(this, input, value, 1);
}
// supports only 2.0-style subtract(1, 's') or subtract(duration)
function subtract$1(input, value) {
return addSubtract$1(this, input, value, -1);
}
function absCeil(number) {
if (number < 0) {
return Math.floor(number);
} else {
return Math.ceil(number);
}
}
function bubble() {
var milliseconds = this._milliseconds,
days = this._days,
months = this._months,
data = this._data,
seconds,
minutes,
hours,
years,
monthsFromDays;
// if we have a mix of positive and negative values, bubble down first
// check: https://github.com/moment/moment/issues/2166
if (!(milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0)) {
milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
days = 0;
months = 0;
}
// The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000;
seconds = absFloor(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absFloor(seconds / 60);
data.minutes = minutes % 60;
hours = absFloor(minutes / 60);
data.hours = hours % 24;
days += absFloor(hours / 24);
// convert days to months
monthsFromDays = absFloor(daysToMonths(days));
months += monthsFromDays;
days -= absCeil(monthsToDays(monthsFromDays));
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
return this;
}
function daysToMonths(days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return days * 4800 / 146097;
}
function monthsToDays(months) {
// the reverse of daysToMonths
return months * 146097 / 4800;
}
function as(units) {
if (!this.isValid()) {
return NaN;
}
var days,
months,
milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === 'month' || units === 'quarter' || units === 'year') {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
switch (units) {
case 'month':
return months;
case 'quarter':
return months / 3;
case 'year':
return months / 12;
}
} else {
// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months));
switch (units) {
case 'week':
return days / 7 + milliseconds / 6048e5;
case 'day':
return days + milliseconds / 864e5;
case 'hour':
return days * 24 + milliseconds / 36e5;
case 'minute':
return days * 1440 + milliseconds / 6e4;
case 'second':
return days * 86400 + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case 'millisecond':
return Math.floor(days * 864e5) + milliseconds;
default:
throw new Error('Unknown unit ' + units);
}
}
}
// TODO: Use this.as('ms')?
function valueOf$1() {
if (!this.isValid()) {
return NaN;
}
return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6;
}
function makeAs(alias) {
return function () {
return this.as(alias);
};
}
var asMilliseconds = makeAs('ms'),
asSeconds = makeAs('s'),
asMinutes = makeAs('m'),
asHours = makeAs('h'),
asDays = makeAs('d'),
asWeeks = makeAs('w'),
asMonths = makeAs('M'),
asQuarters = makeAs('Q'),
asYears = makeAs('y');
function clone$1() {
return createDuration(this);
}
function get$2(units) {
units = normalizeUnits(units);
return this.isValid() ? this[units + 's']() : NaN;
}
function makeGetter(name) {
return function () {
return this.isValid() ? this._data[name] : NaN;
};
}
var milliseconds = makeGetter('milliseconds'),
seconds = makeGetter('seconds'),
minutes = makeGetter('minutes'),
hours = makeGetter('hours'),
days = makeGetter('days'),
months = makeGetter('months'),
years = makeGetter('years');
function weeks() {
return absFloor(this.days() / 7);
}
var round = Math.round,
thresholds = {
ss: 44,
// a few seconds to seconds
s: 45,
// seconds to minute
m: 45,
// minutes to hour
h: 22,
// hours to day
d: 26,
// days to month/week
w: null,
// weeks to month
M: 11 // months to year
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
var duration = createDuration(posNegDuration).abs(),
seconds = round(duration.as('s')),
minutes = round(duration.as('m')),
hours = round(duration.as('h')),
days = round(duration.as('d')),
months = round(duration.as('M')),
weeks = round(duration.as('w')),
years = round(duration.as('y')),
a = seconds <= thresholds.ss && ['s', seconds] || seconds < thresholds.s && ['ss', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days];
if (thresholds.w != null) {
a = a || weeks <= 1 && ['w'] || weeks < thresholds.w && ['ww', weeks];
}
a = a || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years];
a[2] = withoutSuffix;
a[3] = +posNegDuration > 0;
a[4] = locale;
return substituteTimeAgo.apply(null, a);
}
// This function allows you to set the rounding function for relative time strings
function getSetRelativeTimeRounding(roundingFunction) {
if (roundingFunction === undefined) {
return round;
}
if (typeof roundingFunction === 'function') {
round = roundingFunction;
return true;
}
return false;
}
// This function allows you to set a threshold for relative time strings
function getSetRelativeTimeThreshold(threshold, limit) {
if (thresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return thresholds[threshold];
}
thresholds[threshold] = limit;
if (threshold === 's') {
thresholds.ss = limit - 1;
}
return true;
}
function humanize(argWithSuffix, argThresholds) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var withSuffix = false,
th = thresholds,
locale,
output;
if (typeof argWithSuffix === 'object') {
argThresholds = argWithSuffix;
argWithSuffix = false;
}
if (typeof argWithSuffix === 'boolean') {
withSuffix = argWithSuffix;
}
if (typeof argThresholds === 'object') {
th = Object.assign({}, thresholds, argThresholds);
if (argThresholds.s != null && argThresholds.ss == null) {
th.ss = argThresholds.s - 1;
}
}
locale = this.localeData();
output = relativeTime$1(this, !withSuffix, th, locale);
if (withSuffix) {
output = locale.pastFuture(+this, output);
}
return locale.postformat(output);
}
var abs$1 = Math.abs;
function sign(x) {
return (x > 0) - (x < 0) || +x;
}
function toISOString$1() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var seconds = abs$1(this._milliseconds) / 1000,
days = abs$1(this._days),
months = abs$1(this._months),
minutes,
hours,
years,
s,
total = this.asSeconds(),
totalSign,
ymSign,
daysSign,
hmsSign;
if (!total) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return 'P0D';
}
// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60);
hours = absFloor(minutes / 60);
seconds %= 60;
minutes %= 60;
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
totalSign = total < 0 ? '-' : '';
ymSign = sign(this._months) !== sign(total) ? '-' : '';
daysSign = sign(this._days) !== sign(total) ? '-' : '';
hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
return totalSign + 'P' + (years ? ymSign + years + 'Y' : '') + (months ? ymSign + months + 'M' : '') + (days ? daysSign + days + 'D' : '') + (hours || minutes || seconds ? 'T' : '') + (hours ? hmsSign + hours + 'H' : '') + (minutes ? hmsSign + minutes + 'M' : '') + (seconds ? hmsSign + s + 'S' : '');
}
var proto$2 = Duration.prototype;
proto$2.isValid = isValid$1;
proto$2.abs = abs;
proto$2.add = add$1;
proto$2.subtract = subtract$1;
proto$2.as = as;
proto$2.asMilliseconds = asMilliseconds;
proto$2.asSeconds = asSeconds;
proto$2.asMinutes = asMinutes;
proto$2.asHours = asHours;
proto$2.asDays = asDays;
proto$2.asWeeks = asWeeks;
proto$2.asMonths = asMonths;
proto$2.asQuarters = asQuarters;
proto$2.asYears = asYears;
proto$2.valueOf = valueOf$1;
proto$2._bubble = bubble;
proto$2.clone = clone$1;
proto$2.get = get$2;
proto$2.milliseconds = milliseconds;
proto$2.seconds = seconds;
proto$2.minutes = minutes;
proto$2.hours = hours;
proto$2.days = days;
proto$2.weeks = weeks;
proto$2.months = months;
proto$2.years = years;
proto$2.humanize = humanize;
proto$2.toISOString = toISOString$1;
proto$2.toString = toISOString$1;
proto$2.toJSON = toISOString$1;
proto$2.locale = locale;
proto$2.localeData = localeData;
proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
proto$2.lang = lang;
// FORMATTING
addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');
// PARSING
addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
config._d = new Date(parseFloat(input) * 1000);
});
addParseToken('x', function (input, array, config) {
config._d = new Date(toInt(input));
});
//! moment.js
hooks.version = '2.29.4';
setHookCallback(createLocal);
hooks.fn = proto;
hooks.min = min;
hooks.max = max;
hooks.now = now;
hooks.utc = createUTC;
hooks.unix = createUnix;
hooks.months = listMonths;
hooks.isDate = isDate;
hooks.locale = getSetGlobalLocale;
hooks.invalid = createInvalid;
hooks.duration = createDuration;
hooks.isMoment = isMoment;
hooks.weekdays = listWeekdays;
hooks.parseZone = createInZone;
hooks.localeData = getLocale;
hooks.isDuration = isDuration;
hooks.monthsShort = listMonthsShort;
hooks.weekdaysMin = listWeekdaysMin;
hooks.defineLocale = defineLocale;
hooks.updateLocale = updateLocale;
hooks.locales = listLocales;
hooks.weekdaysShort = listWeekdaysShort;
hooks.normalizeUnits = normalizeUnits;
hooks.relativeTimeRounding = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat = getCalendarFormat;
hooks.prototype = proto;
// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',
// <input type="datetime-local" />
DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',
// <input type="datetime-local" step="1" />
DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',
// <input type="datetime-local" step="0.001" />
DATE: 'YYYY-MM-DD',
// <input type="date" />
TIME: 'HH:mm',
// <input type="time" />
TIME_SECONDS: 'HH:mm:ss',
// <input type="time" step="1" />
TIME_MS: 'HH:mm:ss.SSS',
// <input type="time" step="0.001" />
WEEK: 'GGGG-[W]WW',
// <input type="week" />
MONTH: 'YYYY-MM' // <input type="month" />
};
return hooks;
});
});
var componentEmitter = createCommonjsModule(function (module) {
/**
* Expose `Emitter`.
*/
{
module.exports = Emitter;
}
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
}
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
this._callbacks = this._callbacks || {};
(this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function (event, fn) {
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks['$' + event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
// Remove event specific arrays for event types that no
// one is subscribed for to avoid memory leak.
if (callbacks.length === 0) {
delete this._callbacks['$' + event];
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function (event) {
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1),
callbacks = this._callbacks['$' + event];
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function (event) {
this._callbacks = this._callbacks || {};
return this._callbacks['$' + event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function (event) {
return !!this.listeners(event).length;
};
});
/*! Hammer.JS - v2.0.17-rc - 2019-12-16
* http://naver.github.io/egjs
*
* Forked By Naver egjs
* Copyright (c) hammerjs
* Licensed under the MIT license */
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
/**
* @private
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} target
* @param {...Object} objects_to_assign
* @returns {Object} target
*/
var assign;
if (typeof Object.assign !== 'function') {
assign = function assign(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
} else {
assign = Object.assign;
}
var assign$1 = assign;
var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = typeof document === "undefined" ? {
style: {}
} : document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round,
abs = Math.abs;
var now = Date.now;
/**
* @private
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix;
var prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = prefix ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/* eslint-disable no-new-func, no-nested-ternary */
var win;
if (typeof window === "undefined") {
// window is undefined in node.js
win = {};
} else {
win = window;
}
var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
function getTouchActionProps() {
if (!NATIVE_TOUCH_ACTION) {
return false;
}
var touchMap = {};
var cssSupports = win.CSS && win.CSS.supports;
['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function (val) {
// If css.supports is not supported but there is native touch-action assume it supports
// all values. This is the case for IE 10 and 11.
return touchMap[val] = cssSupports ? win.CSS.supports('touch-action', val) : true;
});
return touchMap;
}
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = ('ontouchstart' in win);
var SUPPORT_POINTER_EVENTS = prefixed(win, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';
var COMPUTE_INTERVAL = 25;
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];
/**
* @private
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
/**
* @private
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val === TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* @private
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* @private
* when the touchActions are collected they are not a valid value, so we need to clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // if both pan-x and pan-y are set (different recognizers
// for different directions, e.g. horizontal pan but vertical swipe?)
// we need none (as otherwise with pan-x pan-y combined none of these
// recognizers will work, since the browser would handle all panning
if (hasPanX && hasPanY) {
return TOUCH_ACTION_NONE;
} // pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
} // manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
/**
* @private
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
var TouchAction = /*#__PURE__*/
function () {
function TouchAction(manager, value) {
this.manager = manager;
this.set(value);
}
/**
* @private
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
var _proto = TouchAction.prototype;
_proto.set = function set(value) {
// find out the touch-action by the event handlers
if (value === TOUCH_ACTION_COMPUTE) {
value = this.compute();
}
if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
}
this.actions = value.toLowerCase().trim();
};
/**
* @private
* just re-set the touchAction value
*/
_proto.update = function update() {
this.set(this.manager.options.touchAction);
};
/**
* @private
* compute the value for the touchAction property based on the recognizer's settings
* @returns {String} value
*/
_proto.compute = function compute() {
var actions = [];
each(this.manager.recognizers, function (recognizer) {
if (boolOrFn(recognizer.options.enable, [recognizer])) {
actions = actions.concat(recognizer.getTouchAction());
}
});
return cleanTouchActions(actions.join(' '));
};
/**
* @private
* this method is called on each input cycle and provides the preventing of the browser behavior
* @param {Object} input
*/
_proto.preventDefaults = function preventDefaults(input) {
var srcEvent = input.srcEvent;
var direction = input.offsetDirection; // if the touch action did prevented once this session
if (this.manager.session.prevented) {
srcEvent.preventDefault();
return;
}
var actions = this.actions;
var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
if (hasNone) {
// do not prevent defaults if this is a tap gesture
var isTapPointer = input.pointers.length === 1;
var isTapMovement = input.distance < 2;
var isTapTouchTime = input.deltaTime < 250;
if (isTapPointer && isTapMovement && isTapTouchTime) {
return;
}
}
if (hasPanX && hasPanY) {
// `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
return;
}
if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {
return this.preventSrc(srcEvent);
}
};
/**
* @private
* call preventDefault to prevent the browser's default behavior (scrolling in most cases)
* @param {Object} srcEvent
*/
_proto.preventSrc = function preventSrc(srcEvent) {
this.manager.session.prevented = true;
srcEvent.preventDefault();
};
return TouchAction;
}();
/**
* @private
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent$1(node, parent) {
while (node) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* @private
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = pointers.length; // no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0;
var y = 0;
var i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* @private
* create a simple clone from the input used for storage of firstInput and firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
/**
* @private
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return Math.sqrt(x * x + y * y);
}
/**
* @private
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / Math.PI;
}
/**
* @private
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
if (abs(x) >= abs(y)) {
return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}
function computeDeltaXY(session, input) {
var center = input.center; // let { offsetDelta:offset = {}, prevDelta = {}, prevInput = {} } = session;
// jscs throwing error on defalut destructured values and without defaults tests fail
var offset = session.offsetDelta || {};
var prevDelta = session.prevDelta || {};
var prevInput = session.prevInput || {};
if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
prevDelta = session.prevDelta = {
x: prevInput.deltaX || 0,
y: prevInput.deltaY || 0
};
offset = session.offsetDelta = {
x: center.x,
y: center.y
};
}
input.deltaX = prevDelta.x + (center.x - offset.x);
input.deltaY = prevDelta.y + (center.y - offset.y);
}
/**
* @private
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* @private
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}
/**
* @private
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}
/**
* @private
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = session.lastInterval || input;
var deltaTime = input.timeStamp - last.timeStamp;
var velocity;
var velocityX;
var velocityY;
var direction;
if (input.eventType !== INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = abs(v.x) > abs(v.y) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
/**
* @private
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = manager.session;
var pointers = input.pointers;
var pointersLength = pointers.length; // store the first input to calculate the distance and direction
if (!session.firstInput) {
session.firstInput = simpleCloneInputData(input);
} // to compute scale and rotation we need to store the multiple touches
if (pointersLength > 1 && !session.firstMultiple) {
session.firstMultiple = simpleCloneInputData(input);
} else if (pointersLength === 1) {
session.firstMultiple = false;
}
var firstInput = session.firstInput,
firstMultiple = session.firstMultiple;
var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
var center = input.center = getCenter(pointers);
input.timeStamp = now();
input.deltaTime = input.timeStamp - firstInput.timeStamp;
input.angle = getAngle(offsetCenter, center);
input.distance = getDistance(offsetCenter, center);
computeDeltaXY(session, input);
input.offsetDirection = getDirection(input.deltaX, input.deltaY);
var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
input.overallVelocityX = overallVelocity.x;
input.overallVelocityY = overallVelocity.y;
input.overallVelocity = abs(overallVelocity.x) > abs(overallVelocity.y) ? overallVelocity.x : overallVelocity.y;
input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
input.maxPointers = !session.prevInput ? input.pointers.length : input.pointers.length > session.prevInput.maxPointers ? input.pointers.length : session.prevInput.maxPointers;
computeIntervalInputData(session, input); // find the correct target
var target = manager.element;
var srcEvent = input.srcEvent;
var srcEventTarget;
if (srcEvent.composedPath) {
srcEventTarget = srcEvent.composedPath()[0];
} else if (srcEvent.path) {
srcEventTarget = srcEvent.path[0];
} else {
srcEventTarget = srcEvent.target;
}
if (hasParent$1(srcEventTarget, target)) {
target = srcEventTarget;
}
input.target = target;
}
/**
* @private
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = input.pointers.length;
var changedPointersLen = input.changedPointers.length;
var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;
var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;
input.isFirst = !!isFirst;
input.isFinal = !!isFinal;
if (isFirst) {
manager.session = {};
} // source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType = eventType; // compute scale, rotation etc
computeInputData(manager, input); // emit secret event
manager.emit('hammer.input', input);
manager.recognize(input);
manager.session.prevInput = input;
}
/**
* @private
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* @private
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function (type) {
target.addEventListener(type, handler, false);
});
}
/**
* @private
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function (type) {
target.removeEventListener(type, handler, false);
});
}
/**
* @private
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument || element;
return doc.defaultView || doc.parentWindow || window;
}
/**
* @private
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
var Input = /*#__PURE__*/
function () {
function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function (ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
/**
* @private
* should handle the inputEvent data and trigger the callback
* @virtual
*/
var _proto = Input.prototype;
_proto.handler = function handler() {};
/**
* @private
* bind the events
*/
_proto.init = function init() {
this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
};
/**
* @private
* unbind the events
*/
_proto.destroy = function destroy() {
this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
};
return Input;
}();
/**
* @private
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if (findByKey && src[i][findByKey] == find || !findByKey && src[i] === find) {
// do not use === here, test fails
return i;
}
i++;
}
return -1;
}
}
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
}; // in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
2: INPUT_TYPE_TOUCH,
3: INPUT_TYPE_PEN,
4: INPUT_TYPE_MOUSE,
5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};
var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive
if (win.MSPointerEvent && !win.PointerEvent) {
POINTER_ELEMENT_EVENTS = 'MSPointerDown';
POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}
/**
* @private
* Pointer events input
* @constructor
* @extends Input
*/
var PointerEventInput = /*#__PURE__*/
function (_Input) {
_inheritsLoose(PointerEventInput, _Input);
function PointerEventInput() {
var _this;
var proto = PointerEventInput.prototype;
proto.evEl = POINTER_ELEMENT_EVENTS;
proto.evWin = POINTER_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.store = _this.manager.session.pointerEvents = [];
return _this;
}
/**
* @private
* handle mouse events
* @param {Object} ev
*/
var _proto = PointerEventInput.prototype;
_proto.handler = function handler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = pointerType === INPUT_TYPE_TOUCH; // get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
} // it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
} // update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
};
return PointerEventInput;
}(Input);
/**
* @private
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray$1(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* @private
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function (a, b) {
return a[key] > b[key];
});
}
}
return results;
}
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* @private
* Multi-user touch events input
* @constructor
* @extends Input
*/
var TouchInput = /*#__PURE__*/
function (_Input) {
_inheritsLoose(TouchInput, _Input);
function TouchInput() {
var _this;
TouchInput.prototype.evTarget = TOUCH_TARGET_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.targetIds = {}; // this.evTarget = TOUCH_TARGET_EVENTS;
return _this;
}
var _proto = TouchInput.prototype;
_proto.handler = function handler(ev) {
var type = TOUCH_INPUT_MAP[ev.type];
var touches = getTouches.call(this, ev, type);
if (!touches) {
return;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
};
return TouchInput;
}(Input);
function getTouches(ev, type) {
var allTouches = toArray$1(ev.touches);
var targetIds = this.targetIds; // when there is only one touch, the process can be simplified
if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
targetIds[allTouches[0].identifier] = true;
return [allTouches, allTouches];
}
var i;
var targetTouches;
var changedTouches = toArray$1(ev.changedTouches);
var changedTargetTouches = [];
var target = this.target; // get target touches from touches
targetTouches = allTouches.filter(function (touch) {
return hasParent$1(touch.target, target);
}); // collect touches
if (type === INPUT_START) {
i = 0;
while (i < targetTouches.length) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
} // filter changed touches to only contain touches that exist in the collected target ids
i = 0;
while (i < changedTouches.length) {
if (targetIds[changedTouches[i].identifier]) {
changedTargetTouches.push(changedTouches[i]);
} // cleanup removed touches
if (type & (INPUT_END | INPUT_CANCEL)) {
delete targetIds[changedTouches[i].identifier];
}
i++;
}
if (!changedTargetTouches.length) {
return;
}
return [
// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches];
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
/**
* @private
* Mouse events input
* @constructor
* @extends Input
*/
var MouseInput = /*#__PURE__*/
function (_Input) {
_inheritsLoose(MouseInput, _Input);
function MouseInput() {
var _this;
var proto = MouseInput.prototype;
proto.evEl = MOUSE_ELEMENT_EVENTS;
proto.evWin = MOUSE_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.pressed = false; // mousedown state
return _this;
}
/**
* @private
* handle mouse events
* @param {Object} ev
*/
var _proto = MouseInput.prototype;
_proto.handler = function handler(ev) {
var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down
if (eventType & INPUT_START && ev.button === 0) {
this.pressed = true;
}
if (eventType & INPUT_MOVE && ev.which !== 1) {
eventType = INPUT_END;
} // mouse must be down
if (!this.pressed) {
return;
}
if (eventType & INPUT_END) {
this.pressed = false;
}
this.callback(this.manager, eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
};
return MouseInput;
}(Input);
/**
* @private
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;
function setLastTouch(eventData) {
var _eventData$changedPoi = eventData.changedPointers,
touch = _eventData$changedPoi[0];
if (touch.identifier === this.primaryTouch) {
var lastTouch = {
x: touch.clientX,
y: touch.clientY
};
var lts = this.lastTouches;
this.lastTouches.push(lastTouch);
var removeLastTouch = function removeLastTouch() {
var i = lts.indexOf(lastTouch);
if (i > -1) {
lts.splice(i, 1);
}
};
setTimeout(removeLastTouch, DEDUP_TIMEOUT);
}
}
function recordTouches(eventType, eventData) {
if (eventType & INPUT_START) {
this.primaryTouch = eventData.changedPointers[0].identifier;
setLastTouch.call(this, eventData);
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
setLastTouch.call(this, eventData);
}
}
function isSyntheticEvent(eventData) {
var x = eventData.srcEvent.clientX;
var y = eventData.srcEvent.clientY;
for (var i = 0; i < this.lastTouches.length; i++) {
var t = this.lastTouches[i];
var dx = Math.abs(x - t.x);
var dy = Math.abs(y - t.y);
if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
return true;
}
}
return false;
}
var TouchMouseInput = /*#__PURE__*/
function () {
var TouchMouseInput = /*#__PURE__*/
function (_Input) {
_inheritsLoose(TouchMouseInput, _Input);
function TouchMouseInput(_manager, callback) {
var _this;
_this = _Input.call(this, _manager, callback) || this;
_this.handler = function (manager, inputEvent, inputData) {
var isTouch = inputData.pointerType === INPUT_TYPE_TOUCH;
var isMouse = inputData.pointerType === INPUT_TYPE_MOUSE;
if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
return;
} // when we're in a touch event, record touches to de-dupe synthetic mouse event
if (isTouch) {
recordTouches.call(_assertThisInitialized(_assertThisInitialized(_this)), inputEvent, inputData);
} else if (isMouse && isSyntheticEvent.call(_assertThisInitialized(_assertThisInitialized(_this)), inputData)) {
return;
}
_this.callback(manager, inputEvent, inputData);
};
_this.touch = new TouchInput(_this.manager, _this.handler);
_this.mouse = new MouseInput(_this.manager, _this.handler);
_this.primaryTouch = null;
_this.lastTouches = [];
return _this;
}
/**
* @private
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
var _proto = TouchMouseInput.prototype;
/**
* @private
* remove the event listeners
*/
_proto.destroy = function destroy() {
this.touch.destroy();
this.mouse.destroy();
};
return TouchMouseInput;
}(Input);
return TouchMouseInput;
}();
/**
* @private
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type; // let inputClass = manager.options.inputClass;
var inputClass = manager.options.inputClass;
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new Type(manager, inputHandler);
}
/**
* @private
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* @private
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* @private
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
}
/**
* @private
* get a usable string, used as event postfix
* @param {constant} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* @private
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input, with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
/**
* @private
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
var Recognizer = /*#__PURE__*/
function () {
function Recognizer(options) {
if (options === void 0) {
options = {};
}
this.options = _extends({
enable: true
}, options);
this.id = uniqueId();
this.manager = null; // default is enable true
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
}
/**
* @private
* set options
* @param {Object} options
* @return {Recognizer}
*/
var _proto = Recognizer.prototype;
_proto.set = function set(options) {
assign$1(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state
this.manager && this.manager.touchAction.update();
return this;
};
/**
* @private
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.recognizeWith = function recognizeWith(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
};
/**
* @private
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.dropRecognizeWith = function dropRecognizeWith(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
delete this.simultaneous[otherRecognizer.id];
return this;
};
/**
* @private
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.requireFailure = function requireFailure(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
var requireFail = this.requireFail;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (inArray(requireFail, otherRecognizer) === -1) {
requireFail.push(otherRecognizer);
otherRecognizer.requireFailure(this);
}
return this;
};
/**
* @private
* drop the requireFailure link. it does not remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.dropRequireFailure = function dropRequireFailure(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
var index = inArray(this.requireFail, otherRecognizer);
if (index > -1) {
this.requireFail.splice(index, 1);
}
return this;
};
/**
* @private
* has require failures boolean
* @returns {boolean}
*/
_proto.hasRequireFailures = function hasRequireFailures() {
return this.requireFail.length > 0;
};
/**
* @private
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
_proto.canRecognizeWith = function canRecognizeWith(otherRecognizer) {
return !!this.simultaneous[otherRecognizer.id];
};
/**
* @private
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
_proto.emit = function emit(input) {
var self = this;
var state = this.state;
function emit(event) {
self.manager.emit(event, input);
} // 'panstart' and 'panmove'
if (state < STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
emit(self.options.event); // simple 'eventName' events
if (input.additionalEvent) {
// additional event(panleft, panright, pinchin, pinchout...)
emit(input.additionalEvent);
} // panend and pancancel
if (state >= STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
};
/**
* @private
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
_proto.tryEmit = function tryEmit(input) {
if (this.canEmit()) {
return this.emit(input);
} // it's failing anyway
this.state = STATE_FAILED;
};
/**
* @private
* can we emit?
* @returns {boolean}
*/
_proto.canEmit = function canEmit() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
};
/**
* @private
* update the recognizer
* @param {Object} inputData
*/
_proto.recognize = function recognize(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign$1({}, inputData); // is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
} // reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone); // the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
};
/**
* @private
* return the state of the recognizer
* the actual recognizing happens in this method
* @virtual
* @param {Object} inputData
* @returns {constant} STATE
*/
/* jshint ignore:start */
_proto.process = function process(inputData) {};
/* jshint ignore:end */
/**
* @private
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
_proto.getTouchAction = function getTouchAction() {};
/**
* @private
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
_proto.reset = function reset() {};
return Recognizer;
}();
/**
* @private
* A tap is recognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
* between the given interval and position. The delay option can be used to recognize multi-taps without firing
* a single tap.
*
* The eventData from the emitted event contains the property `tapCount`, which contains the amount of
* multi-taps being recognized.
* @constructor
* @extends Recognizer
*/
var TapRecognizer = /*#__PURE__*/
function (_Recognizer) {
_inheritsLoose(TapRecognizer, _Recognizer);
function TapRecognizer(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _Recognizer.call(this, _extends({
event: 'tap',
pointers: 1,
taps: 1,
interval: 300,
// max time between the multi-tap taps
time: 250,
// max time of the pointer to be down (like finger on the screen)
threshold: 9,
// a minimal movement is ok, but keep it low
posThreshold: 10
}, options)) || this; // previous time and center,
// used for tap counting
_this.pTime = false;
_this.pCenter = false;
_this._timer = null;
_this._input = null;
_this.count = 0;
return _this;
}
var _proto = TapRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_MANIPULATION];
};
_proto.process = function process(input) {
var _this2 = this;
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTouchTime = input.deltaTime < options.time;
this.reset();
if (input.eventType & INPUT_START && this.count === 0) {
return this.failTimeout();
} // we only allow little movement
// and we've reached an end event, so a tap is possible
if (validMovement && validTouchTime && validPointers) {
if (input.eventType !== INPUT_END) {
return this.failTimeout();
}
var validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;
var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
this.pTime = input.timeStamp;
this.pCenter = input.center;
if (!validMultiTap || !validInterval) {
this.count = 1;
} else {
this.count += 1;
}
this._input = input; // if tap count matches we have recognized it,
// else it has began recognizing...
var tapCount = this.count % options.taps;
if (tapCount === 0) {
// no failing requirements, immediately trigger the tap event
// or wait as long as the multitap interval to trigger
if (!this.hasRequireFailures()) {
return STATE_RECOGNIZED;
} else {
this._timer = setTimeout(function () {
_this2.state = STATE_RECOGNIZED;
_this2.tryEmit();
}, options.interval);
return STATE_BEGAN;
}
}
}
return STATE_FAILED;
};
_proto.failTimeout = function failTimeout() {
var _this3 = this;
this._timer = setTimeout(function () {
_this3.state = STATE_FAILED;
}, this.options.interval);
return STATE_FAILED;
};
_proto.reset = function reset() {
clearTimeout(this._timer);
};
_proto.emit = function emit() {
if (this.state === STATE_RECOGNIZED) {
this._input.tapCount = this.count;
this.manager.emit(this.options.event, this._input);
}
};
return TapRecognizer;
}(Recognizer);
/**
* @private
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
var AttrRecognizer = /*#__PURE__*/
function (_Recognizer) {
_inheritsLoose(AttrRecognizer, _Recognizer);
function AttrRecognizer(options) {
if (options === void 0) {
options = {};
}
return _Recognizer.call(this, _extends({
pointers: 1
}, options)) || this;
}
/**
* @private
* Used to check if it the recognizer receives valid input, like input.distance > 10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
var _proto = AttrRecognizer.prototype;
_proto.attrTest = function attrTest(input) {
var optionPointers = this.options.pointers;
return optionPointers === 0 || input.pointers.length === optionPointers;
};
/**
* @private
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
_proto.process = function process(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
};
return AttrRecognizer;
}(Recognizer);
/**
* @private
* direction cons to string
* @param {constant} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction === DIRECTION_DOWN) {
return 'down';
} else if (direction === DIRECTION_UP) {
return 'up';
} else if (direction === DIRECTION_LEFT) {
return 'left';
} else if (direction === DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* @private
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
var PanRecognizer = /*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(PanRecognizer, _AttrRecognizer);
function PanRecognizer(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _AttrRecognizer.call(this, _extends({
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
}, options)) || this;
_this.pX = null;
_this.pY = null;
return _this;
}
var _proto = PanRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
var direction = this.options.direction;
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
};
_proto.directionTest = function directionTest(input) {
var options = this.options;
var hasMoved = true;
var distance = input.distance;
var direction = input.direction;
var x = input.deltaX;
var y = input.deltaY; // lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = x === 0 ? DIRECTION_NONE : x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x !== this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = y === 0 ? DIRECTION_NONE : y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y !== this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction & options.direction;
};
_proto.attrTest = function attrTest(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) && (
// replace with a super call
this.state & STATE_BEGAN || !(this.state & STATE_BEGAN) && this.directionTest(input));
};
_proto.emit = function emit(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
var direction = directionStr(input.direction);
if (direction) {
input.additionalEvent = this.options.event + direction;
}
_AttrRecognizer.prototype.emit.call(this, input);
};
return PanRecognizer;
}(AttrRecognizer);
/**
* @private
* Swipe
* Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
var SwipeRecognizer = /*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(SwipeRecognizer, _AttrRecognizer);
function SwipeRecognizer(options) {
if (options === void 0) {
options = {};
}
return _AttrRecognizer.call(this, _extends({
event: 'swipe',
threshold: 10,
velocity: 0.3,
direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
pointers: 1
}, options)) || this;
}
var _proto = SwipeRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return PanRecognizer.prototype.getTouchAction.call(this);
};
_proto.attrTest = function attrTest(input) {
var direction = this.options.direction;
var velocity;
if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
velocity = input.overallVelocity;
} else if (direction & DIRECTION_HORIZONTAL) {
velocity = input.overallVelocityX;
} else if (direction & DIRECTION_VERTICAL) {
velocity = input.overallVelocityY;
}
return _AttrRecognizer.prototype.attrTest.call(this, input) && direction & input.offsetDirection && input.distance > this.options.threshold && input.maxPointers === this.options.pointers && abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
};
_proto.emit = function emit(input) {
var direction = directionStr(input.offsetDirection);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this.manager.emit(this.options.event, input);
};
return SwipeRecognizer;
}(AttrRecognizer);
/**
* @private
* Pinch
* Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
* @constructor
* @extends AttrRecognizer
*/
var PinchRecognizer = /*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(PinchRecognizer, _AttrRecognizer);
function PinchRecognizer(options) {
if (options === void 0) {
options = {};
}
return _AttrRecognizer.call(this, _extends({
event: 'pinch',
threshold: 0,
pointers: 2
}, options)) || this;
}
var _proto = PinchRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_NONE];
};
_proto.attrTest = function attrTest(input) {
return _AttrRecognizer.prototype.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
};
_proto.emit = function emit(input) {
if (input.scale !== 1) {
var inOut = input.scale < 1 ? 'in' : 'out';
input.additionalEvent = this.options.event + inOut;
}
_AttrRecognizer.prototype.emit.call(this, input);
};
return PinchRecognizer;
}(AttrRecognizer);
/**
* @private
* Rotate
* Recognized when two or more pointer are moving in a circular motion.
* @constructor
* @extends AttrRecognizer
*/
var RotateRecognizer = /*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(RotateRecognizer, _AttrRecognizer);
function RotateRecognizer(options) {
if (options === void 0) {
options = {};
}
return _AttrRecognizer.call(this, _extends({
event: 'rotate',
threshold: 0,
pointers: 2
}, options)) || this;
}
var _proto = RotateRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_NONE];
};
_proto.attrTest = function attrTest(input) {
return _AttrRecognizer.prototype.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
};
return RotateRecognizer;
}(AttrRecognizer);
/**
* @private
* Press
* Recognized when the pointer is down for x ms without any movement.
* @constructor
* @extends Recognizer
*/
var PressRecognizer = /*#__PURE__*/
function (_Recognizer) {
_inheritsLoose(PressRecognizer, _Recognizer);
function PressRecognizer(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _Recognizer.call(this, _extends({
event: 'press',
pointers: 1,
time: 251,
// minimal time of the pointer to be pressed
threshold: 9
}, options)) || this;
_this._timer = null;
_this._input = null;
return _this;
}
var _proto = PressRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_AUTO];
};
_proto.process = function process(input) {
var _this2 = this;
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTime = input.deltaTime > options.time;
this._input = input; // we only allow little movement
// and we've reached an end event, so a tap is possible
if (!validMovement || !validPointers || input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime) {
this.reset();
} else if (input.eventType & INPUT_START) {
this.reset();
this._timer = setTimeout(function () {
_this2.state = STATE_RECOGNIZED;
_this2.tryEmit();
}, options.time);
} else if (input.eventType & INPUT_END) {
return STATE_RECOGNIZED;
}
return STATE_FAILED;
};
_proto.reset = function reset() {
clearTimeout(this._timer);
};
_proto.emit = function emit(input) {
if (this.state !== STATE_RECOGNIZED) {
return;
}
if (input && input.eventType & INPUT_END) {
this.manager.emit(this.options.event + "up", input);
} else {
this._input.timeStamp = now();
this.manager.emit(this.options.event, this._input);
}
};
return PressRecognizer;
}(Recognizer);
var defaults = {
/**
* @private
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* @private
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @private
* @type {Boolean}
* @default true
*/
enable: true,
/**
* @private
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* @private
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* @private
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* @private
* Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userSelect: "none",
/**
* @private
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: "none",
/**
* @private
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: "none",
/**
* @private
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: "none",
/**
* @private
* Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: "none",
/**
* @private
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: "rgba(0,0,0,0)"
}
};
/**
* @private
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* This is separated with other defaults because of tree-shaking.
* @type {Array}
*/
var preset = [[RotateRecognizer, {
enable: false
}], [PinchRecognizer, {
enable: false
}, ['rotate']], [SwipeRecognizer, {
direction: DIRECTION_HORIZONTAL
}], [PanRecognizer, {
direction: DIRECTION_HORIZONTAL
}, ['swipe']], [TapRecognizer], [TapRecognizer, {
event: 'doubletap',
taps: 2
}, ['tap']], [PressRecognizer]];
var STOP = 1;
var FORCED_STOP = 2;
/**
* @private
* add/remove the css properties as defined in manager.options.cssProps
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = manager.element;
if (!element.style) {
return;
}
var prop;
each(manager.options.cssProps, function (value, name) {
prop = prefixed(element.style, name);
if (add) {
manager.oldCssProps[prop] = element.style[prop];
element.style[prop] = value;
} else {
element.style[prop] = manager.oldCssProps[prop] || "";
}
});
if (!add) {
manager.oldCssProps = {};
}
}
/**
* @private
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = document.createEvent("Event");
gestureEvent.initEvent(event, true, true);
gestureEvent.gesture = data;
data.target.dispatchEvent(gestureEvent);
}
/**
* @private
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
var Manager = /*#__PURE__*/
function () {
function Manager(element, options) {
var _this = this;
this.options = assign$1({}, defaults, options || {});
this.options.inputTarget = this.options.inputTarget || element;
this.handlers = {};
this.session = {};
this.recognizers = [];
this.oldCssProps = {};
this.element = element;
this.input = createInputInstance(this);
this.touchAction = new TouchAction(this, this.options.touchAction);
toggleCssProps(this, true);
each(this.options.recognizers, function (item) {
var recognizer = _this.add(new item[0](item[1]));
item[2] && recognizer.recognizeWith(item[2]);
item[3] && recognizer.requireFailure(item[3]);
}, this);
}
/**
* @private
* set options
* @param {Object} options
* @returns {Manager}
*/
var _proto = Manager.prototype;
_proto.set = function set(options) {
assign$1(this.options, options); // Options that need a little more setup
if (options.touchAction) {
this.touchAction.update();
}
if (options.inputTarget) {
// Clean up existing event listeners and reinitialize
this.input.destroy();
this.input.target = options.inputTarget;
this.input.init();
}
return this;
};
/**
* @private
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
_proto.stop = function stop(force) {
this.session.stopped = force ? FORCED_STOP : STOP;
};
/**
* @private
* run the recognizers!
* called by the inputHandler function on every movement of the pointers (touches)
* it walks through all the recognizers and tries to detect the gesture that is being made
* @param {Object} inputData
*/
_proto.recognize = function recognize(inputData) {
var session = this.session;
if (session.stopped) {
return;
} // run the touch-action polyfill
this.touchAction.preventDefaults(inputData);
var recognizer;
var recognizers = this.recognizers; // this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized
// or when we're in a new session
if (!curRecognizer || curRecognizer && curRecognizer.state & STATE_RECOGNIZED) {
session.curRecognizer = null;
curRecognizer = null;
}
var i = 0;
while (i < recognizers.length) {
recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the recognizer.
if (session.stopped !== FORCED_STOP && (
// 1
!curRecognizer || recognizer === curRecognizer ||
// 2
recognizer.canRecognizeWith(curRecognizer))) {
// 3
recognizer.recognize(inputData);
} else {
recognizer.reset();
} // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
session.curRecognizer = recognizer;
curRecognizer = recognizer;
}
i++;
}
};
/**
* @private
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
_proto.get = function get(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event === recognizer) {
return recognizers[i];
}
}
return null;
};
/**
* @private add a recognizer to the manager
* existing recognizers with the same event name will be removed
* @param {Recognizer} recognizer
* @returns {Recognizer|Manager}
*/
_proto.add = function add(recognizer) {
if (invokeArrayArg(recognizer, "add", this)) {
return this;
} // remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
recognizer.manager = this;
this.touchAction.update();
return recognizer;
};
/**
* @private
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
_proto.remove = function remove(recognizer) {
if (invokeArrayArg(recognizer, "remove", this)) {
return this;
}
var targetRecognizer = this.get(recognizer); // let's make sure this recognizer exists
if (recognizer) {
var recognizers = this.recognizers;
var index = inArray(recognizers, targetRecognizer);
if (index !== -1) {
recognizers.splice(index, 1);
this.touchAction.update();
}
}
return this;
};
/**
* @private
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
_proto.on = function on(events, handler) {
if (events === undefined || handler === undefined) {
return this;
}
var handlers = this.handlers;
each(splitStr(events), function (event) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
});
return this;
};
/**
* @private unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
_proto.off = function off(events, handler) {
if (events === undefined) {
return this;
}
var handlers = this.handlers;
each(splitStr(events), function (event) {
if (!handler) {
delete handlers[event];
} else {
handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
}
});
return this;
};
/**
* @private emit event to the listeners
* @param {String} event
* @param {Object} data
*/
_proto.emit = function emit(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
} // no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) {
return;
}
data.type = event;
data.preventDefault = function () {
data.srcEvent.preventDefault();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
};
/**
* @private
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
_proto.destroy = function destroy() {
this.element && toggleCssProps(this, false);
this.handlers = {};
this.session = {};
this.input.destroy();
this.element = null;
};
return Manager;
}();
var SINGLE_TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* @private
* Touch events input
* @constructor
* @extends Input
*/
var SingleTouchInput = /*#__PURE__*/
function (_Input) {
_inheritsLoose(SingleTouchInput, _Input);
function SingleTouchInput() {
var _this;
var proto = SingleTouchInput.prototype;
proto.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
proto.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.started = false;
return _this;
}
var _proto = SingleTouchInput.prototype;
_proto.handler = function handler(ev) {
var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; // should we handle the touch events?
if (type === INPUT_START) {
this.started = true;
}
if (!this.started) {
return;
}
var touches = normalizeSingleTouches.call(this, ev, type); // when done, reset the started state
if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
this.started = false;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
};
return SingleTouchInput;
}(Input);
function normalizeSingleTouches(ev, type) {
var all = toArray$1(ev.touches);
var changed = toArray$1(ev.changedTouches);
if (type & (INPUT_END | INPUT_CANCEL)) {
all = uniqueArray(all.concat(changed), 'identifier', true);
}
return [all, changed];
}
/**
* @private
* wrap a method with a deprecation warning and stack trace
* @param {Function} method
* @param {String} name
* @param {String} message
* @returns {Function} A new function wrapping the supplied method.
*/
function deprecate(method, name, message) {
var deprecationMessage = "DEPRECATED METHOD: " + name + "\n" + message + " AT \n";
return function () {
var e = new Error('get-stack-trace');
var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '').replace(/^\s+at\s+/gm, '').replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
var log = window.console && (window.console.warn || window.console.log);
if (log) {
log.call(window.console, deprecationMessage, stack);
}
return method.apply(this, arguments);
};
}
/**
* @private
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge=false]
* @returns {Object} dest
*/
var extend$1 = deprecate(function (dest, src, merge) {
var keys = Object.keys(src);
var i = 0;
while (i < keys.length) {
if (!merge || merge && dest[keys[i]] === undefined) {
dest[keys[i]] = src[keys[i]];
}
i++;
}
return dest;
}, 'extend', 'Use `assign`.');
/**
* @private
* merge the values from src in the dest.
* means that properties that exist in dest will not be overwritten by src
* @param {Object} dest
* @param {Object} src
* @returns {Object} dest
*/
var merge$1 = deprecate(function (dest, src) {
return extend$1(dest, src, true);
}, 'merge', 'Use `assign`.');
/**
* @private
* simple class inheritance
* @param {Function} child
* @param {Function} base
* @param {Object} [properties]
*/
function inherit(child, base, properties) {
var baseP = base.prototype;
var childP;
childP = child.prototype = Object.create(baseP);
childP.constructor = child;
childP._super = baseP;
if (properties) {
assign$1(childP, properties);
}
}
/**
* @private
* simple function bind
* @param {Function} fn
* @param {Object} context
* @returns {Function}
*/
function bindFn(fn, context) {
return function boundFn() {
return fn.apply(context, arguments);
};
}
/**
* @private
* Simple way to create a manager with a default set of recognizers.
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
var Hammer$3 = /*#__PURE__*/
function () {
var Hammer =
/**
* @private
* @const {string}
*/
function Hammer(element, options) {
if (options === void 0) {
options = {};
}
return new Manager(element, _extends({
recognizers: preset.concat()
}, options));
};
Hammer.VERSION = "2.0.17-rc";
Hammer.DIRECTION_ALL = DIRECTION_ALL;
Hammer.DIRECTION_DOWN = DIRECTION_DOWN;
Hammer.DIRECTION_LEFT = DIRECTION_LEFT;
Hammer.DIRECTION_RIGHT = DIRECTION_RIGHT;
Hammer.DIRECTION_UP = DIRECTION_UP;
Hammer.DIRECTION_HORIZONTAL = DIRECTION_HORIZONTAL;
Hammer.DIRECTION_VERTICAL = DIRECTION_VERTICAL;
Hammer.DIRECTION_NONE = DIRECTION_NONE;
Hammer.DIRECTION_DOWN = DIRECTION_DOWN;
Hammer.INPUT_START = INPUT_START;
Hammer.INPUT_MOVE = INPUT_MOVE;
Hammer.INPUT_END = INPUT_END;
Hammer.INPUT_CANCEL = INPUT_CANCEL;
Hammer.STATE_POSSIBLE = STATE_POSSIBLE;
Hammer.STATE_BEGAN = STATE_BEGAN;
Hammer.STATE_CHANGED = STATE_CHANGED;
Hammer.STATE_ENDED = STATE_ENDED;
Hammer.STATE_RECOGNIZED = STATE_RECOGNIZED;
Hammer.STATE_CANCELLED = STATE_CANCELLED;
Hammer.STATE_FAILED = STATE_FAILED;
Hammer.Manager = Manager;
Hammer.Input = Input;
Hammer.TouchAction = TouchAction;
Hammer.TouchInput = TouchInput;
Hammer.MouseInput = MouseInput;
Hammer.PointerEventInput = PointerEventInput;
Hammer.TouchMouseInput = TouchMouseInput;
Hammer.SingleTouchInput = SingleTouchInput;
Hammer.Recognizer = Recognizer;
Hammer.AttrRecognizer = AttrRecognizer;
Hammer.Tap = TapRecognizer;
Hammer.Pan = PanRecognizer;
Hammer.Swipe = SwipeRecognizer;
Hammer.Pinch = PinchRecognizer;
Hammer.Rotate = RotateRecognizer;
Hammer.Press = PressRecognizer;
Hammer.on = addEventListeners;
Hammer.off = removeEventListeners;
Hammer.each = each;
Hammer.merge = merge$1;
Hammer.extend = extend$1;
Hammer.bindFn = bindFn;
Hammer.assign = assign$1;
Hammer.inherit = inherit;
Hammer.bindFn = bindFn;
Hammer.prefixed = prefixed;
Hammer.toArray = toArray$1;
Hammer.inArray = inArray;
Hammer.uniqueArray = uniqueArray;
Hammer.splitStr = splitStr;
Hammer.boolOrFn = boolOrFn;
Hammer.hasParent = hasParent$1;
Hammer.addEventListeners = addEventListeners;
Hammer.removeEventListeners = removeEventListeners;
Hammer.defaults = assign$1({}, defaults, {
preset: preset
});
return Hammer;
}();
// style loader but by script tag, not by the loader.
Hammer$3.defaults;
var Hammer$1$1 = Hammer$3;
/**
* vis-util
* https://github.com/visjs/vis-util
*
* utilitie collection for visjs
*
* @version 5.0.7
* @date 2023-11-20T09:06:51.067Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*/
/**
* Use this symbol to delete properies in deepObjectAssign.
*/
const DELETE = Symbol("DELETE");
/**
* Pure version of deepObjectAssign, it doesn't modify any of it's arguments.
*
* @param base - The base object that fullfils the whole interface T.
* @param updates - Updates that may change or delete props.
* @returns A brand new instance with all the supplied objects deeply merged.
*/
function pureDeepObjectAssign(base, ...updates) {
return deepObjectAssign({}, base, ...updates);
}
/**
* Deep version of object assign with additional deleting by the DELETE symbol.
*
* @param values - Objects to be deeply merged.
* @returns The first object from values.
*/
function deepObjectAssign(...values) {
const merged = deepObjectAssignNonentry(...values);
stripDelete(merged);
return merged;
}
/**
* Deep version of object assign with additional deleting by the DELETE symbol.
*
* @remarks
* This doesn't strip the DELETE symbols so they may end up in the final object.
* @param values - Objects to be deeply merged.
* @returns The first object from values.
*/
function deepObjectAssignNonentry(...values) {
if (values.length < 2) {
return values[0];
} else if (values.length > 2) {
return deepObjectAssignNonentry(deepObjectAssign(values[0], values[1]), ...values.slice(2));
}
const a = values[0];
const b = values[1];
if (a instanceof Date && b instanceof Date) {
a.setTime(b.getTime());
return a;
}
for (const prop of Reflect.ownKeys(b)) {
if (!Object.prototype.propertyIsEnumerable.call(b, prop)) ;else if (b[prop] === DELETE) {
delete a[prop];
} else if (a[prop] !== null && b[prop] !== null && typeof a[prop] === "object" && typeof b[prop] === "object" && !Array.isArray(a[prop]) && !Array.isArray(b[prop])) {
a[prop] = deepObjectAssignNonentry(a[prop], b[prop]);
} else {
a[prop] = clone(b[prop]);
}
}
return a;
}
/**
* Deep clone given object or array. In case of primitive simply return.
*
* @param a - Anything.
* @returns Deep cloned object/array or unchanged a.
*/
function clone(a) {
if (Array.isArray(a)) {
return a.map(value => clone(value));
} else if (typeof a === "object" && a !== null) {
if (a instanceof Date) {
return new Date(a.getTime());
}
return deepObjectAssignNonentry({}, a);
} else {
return a;
}
}
/**
* Strip DELETE from given object.
*
* @param a - Object which may contain DELETE but won't after this is executed.
*/
function stripDelete(a) {
for (const prop of Object.keys(a)) {
if (a[prop] === DELETE) {
delete a[prop];
} else if (typeof a[prop] === "object" && a[prop] !== null) {
stripDelete(a[prop]);
}
}
}
/**
* Seedable, fast and reasonably good (not crypto but more than okay for our
* needs) random number generator.
*
* @remarks
* Adapted from {@link https://web.archive.org/web/20110429100736/http://baagoe.com:80/en/RandomMusings/javascript}.
* Original algorithm created by Johannes Baagøe \<baagoe\@baagoe.com\> in 2010.
*/
/**
* Create a seeded pseudo random generator based on Alea by Johannes Baagøe.
*
* @param seed - All supplied arguments will be used as a seed. In case nothing
* is supplied the current time will be used to seed the generator.
* @returns A ready to use seeded generator.
*/
function Alea(...seed) {
return AleaImplementation(seed.length ? seed : [Date.now()]);
}
/**
* An implementation of [[Alea]] without user input validation.
*
* @param seed - The data that will be used to seed the generator.
* @returns A ready to use seeded generator.
*/
function AleaImplementation(seed) {
let [s0, s1, s2] = mashSeed(seed);
let c = 1;
const random = () => {
const t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
s0 = s1;
s1 = s2;
return s2 = t - (c = t | 0);
};
random.uint32 = () => random() * 0x100000000; // 2^32
random.fract53 = () => random() + (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
random.algorithm = "Alea";
random.seed = seed;
random.version = "0.9";
return random;
}
/**
* Turn arbitrary data into values [[AleaImplementation]] can use to generate
* random numbers.
*
* @param seed - Arbitrary data that will be used as the seed.
* @returns Three numbers to use as initial values for [[AleaImplementation]].
*/
function mashSeed(...seed) {
const mash = Mash();
let s0 = mash(" ");
let s1 = mash(" ");
let s2 = mash(" ");
for (let i = 0; i < seed.length; i++) {
s0 -= mash(seed[i]);
if (s0 < 0) {
s0 += 1;
}
s1 -= mash(seed[i]);
if (s1 < 0) {
s1 += 1;
}
s2 -= mash(seed[i]);
if (s2 < 0) {
s2 += 1;
}
}
return [s0, s1, s2];
}
/**
* Create a new mash function.
*
* @returns A nonpure function that takes arbitrary [[Mashable]] data and turns
* them into numbers.
*/
function Mash() {
let n = 0xefc8249d;
return function (data) {
const string = data.toString();
for (let i = 0; i < string.length; i++) {
n += string.charCodeAt(i);
let h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
}
/**
* Setup a mock hammer.js object, for unit testing.
*
* Inspiration: https://github.com/uber/deck.gl/pull/658
*
* @returns {{on: noop, off: noop, destroy: noop, emit: noop, get: get}}
*/
function hammerMock$1() {
const noop = () => {};
return {
on: noop,
off: noop,
destroy: noop,
emit: noop,
get() {
return {
set: noop
};
}
};
}
const Hammer$1 = typeof window !== "undefined" ? window.Hammer || Hammer$1$1 : function () {
// hammer.js is only available in a browser, not in node.js. Replacing it with a mock object.
return hammerMock$1();
};
/**
* Turn an element into an clickToUse element.
* When not active, the element has a transparent overlay. When the overlay is
* clicked, the mode is changed to active.
* When active, the element is displayed with a blue border around it, and
* the interactive contents of the element can be used. When clicked outside
* the element, the elements mode is changed to inactive.
*
* @param {Element} container
* @class Activator
*/
function Activator$1(container) {
this._cleanupQueue = [];
this.active = false;
this._dom = {
container,
overlay: document.createElement("div")
};
this._dom.overlay.classList.add("vis-overlay");
this._dom.container.appendChild(this._dom.overlay);
this._cleanupQueue.push(() => {
this._dom.overlay.parentNode.removeChild(this._dom.overlay);
});
const hammer = Hammer$1(this._dom.overlay);
hammer.on("tap", this._onTapOverlay.bind(this));
this._cleanupQueue.push(() => {
hammer.destroy();
// FIXME: cleaning up hammer instances doesn't work (Timeline not removed
// from memory)
});
// block all touch events (except tap)
const events = ["tap", "doubletap", "press", "pinch", "pan", "panstart", "panmove", "panend"];
events.forEach(event => {
hammer.on(event, event => {
event.srcEvent.stopPropagation();
});
});
// attach a click event to the window, in order to deactivate when clicking outside the timeline
if (document && document.body) {
this._onClick = event => {
if (!_hasParent$1(event.target, container)) {
this.deactivate();
}
};
document.body.addEventListener("click", this._onClick);
this._cleanupQueue.push(() => {
document.body.removeEventListener("click", this._onClick);
});
}
// prepare escape key listener for deactivating when active
this._escListener = event => {
if ("key" in event ? event.key === "Escape" : event.keyCode === 27 /* the keyCode is for IE11 */) {
this.deactivate();
}
};
}
// turn into an event emitter
componentEmitter(Activator$1.prototype);
// The currently active activator
Activator$1.current = null;
/**
* Destroy the activator. Cleans up all created DOM and event listeners
*/
Activator$1.prototype.destroy = function () {
this.deactivate();
for (const callback of this._cleanupQueue.splice(0).reverse()) {
callback();
}
};
/**
* Activate the element
* Overlay is hidden, element is decorated with a blue shadow border
*/
Activator$1.prototype.activate = function () {
// we allow only one active activator at a time
if (Activator$1.current) {
Activator$1.current.deactivate();
}
Activator$1.current = this;
this.active = true;
this._dom.overlay.style.display = "none";
this._dom.container.classList.add("vis-active");
this.emit("change");
this.emit("activate");
// ugly hack: bind ESC after emitting the events, as the Network rebinds all
// keyboard events on a 'change' event
document.body.addEventListener("keydown", this._escListener);
};
/**
* Deactivate the element
* Overlay is displayed on top of the element
*/
Activator$1.prototype.deactivate = function () {
this.active = false;
this._dom.overlay.style.display = "block";
this._dom.container.classList.remove("vis-active");
document.body.removeEventListener("keydown", this._escListener);
this.emit("change");
this.emit("deactivate");
};
/**
* Handle a tap event: activate the container
*
* @param {Event} event The event
* @private
*/
Activator$1.prototype._onTapOverlay = function (event) {
// activate the container
this.activate();
event.srcEvent.stopPropagation();
};
/**
* Test whether the element has the requested parent element somewhere in
* its chain of parent nodes.
*
* @param {HTMLElement} element
* @param {HTMLElement} parent
* @returns {boolean} Returns true when the parent is found somewhere in the
* chain of parent nodes.
* @private
*/
function _hasParent$1(element, parent) {
while (element) {
if (element === parent) {
return true;
}
element = element.parentNode;
}
return false;
}
// utility functions
// parse ASP.Net Date pattern,
// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
// code from http://momentjs.com/
const ASPDateRegex$1 = /^\/?Date\((-?\d+)/i;
// Color REs
const fullHexRE = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
const shortHexRE = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const rgbRE = /^rgb\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *\)$/i;
const rgbaRE = /^rgba\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *([01]|0?\.\d+) *\)$/i;
/**
* Test whether given object is a number.
*
* @param value - Input value of unknown type.
* @returns True if number, false otherwise.
*/
function isNumber(value) {
return value instanceof Number || typeof value === "number";
}
/**
* Remove everything in the DOM object.
*
* @param DOMobject - Node whose child nodes will be recursively deleted.
*/
function recursiveDOMDelete(DOMobject) {
if (DOMobject) {
while (DOMobject.hasChildNodes() === true) {
const child = DOMobject.firstChild;
if (child) {
recursiveDOMDelete(child);
DOMobject.removeChild(child);
}
}
}
}
/**
* Test whether given object is a string.
*
* @param value - Input value of unknown type.
* @returns True if string, false otherwise.
*/
function isString(value) {
return value instanceof String || typeof value === "string";
}
/**
* Test whether given object is a object (not primitive or null).
*
* @param value - Input value of unknown type.
* @returns True if not null object, false otherwise.
*/
function isObject(value) {
return typeof value === "object" && value !== null;
}
/**
* Test whether given object is a Date, or a String containing a Date.
*
* @param value - Input value of unknown type.
* @returns True if Date instance or string date representation, false otherwise.
*/
function isDate(value) {
if (value instanceof Date) {
return true;
} else if (isString(value)) {
// test whether this string contains a date
const match = ASPDateRegex$1.exec(value);
if (match) {
return true;
} else if (!isNaN(Date.parse(value))) {
return true;
}
}
return false;
}
/**
* Copy property from b to a if property present in a.
* If property in b explicitly set to null, delete it if `allowDeletion` set.
*
* Internal helper routine, should not be exported. Not added to `exports` for that reason.
*
* @param a - Target object.
* @param b - Source object.
* @param prop - Name of property to copy from b to a.
* @param allowDeletion - If true, delete property in a if explicitly set to null in b.
*/
function copyOrDelete(a, b, prop, allowDeletion) {
let doDeletion = false;
if (allowDeletion === true) {
doDeletion = b[prop] === null && a[prop] !== undefined;
}
if (doDeletion) {
delete a[prop];
} else {
a[prop] = b[prop]; // Remember, this is a reference copy!
}
}
/**
* Fill an object with a possibly partially defined other object.
*
* Only copies values for the properties already present in a.
* That means an object is not created on a property if only the b object has it.
*
* @param a - The object that will have it's properties updated.
* @param b - The object with property updates.
* @param allowDeletion - If true, delete properties in a that are explicitly set to null in b.
*/
function fillIfDefined(a, b, allowDeletion = false) {
// NOTE: iteration of properties of a
// NOTE: prototype properties iterated over as well
for (const prop in a) {
if (b[prop] !== undefined) {
if (b[prop] === null || typeof b[prop] !== "object") {
// Note: typeof null === 'object'
copyOrDelete(a, b, prop, allowDeletion);
} else {
const aProp = a[prop];
const bProp = b[prop];
if (isObject(aProp) && isObject(bProp)) {
fillIfDefined(aProp, bProp, allowDeletion);
}
}
}
}
}
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
*
* @param target - The target object to copy to.
* @param source - The source object from which to copy properties.
* @returns The target object.
*/
const extend = Object.assign;
/**
* Extend object a with selected properties of object b or a series of objects.
*
* @remarks
* Only properties with defined values are copied.
* @param props - Properties to be copied to a.
* @param a - The target.
* @param others - The sources.
* @returns Argument a.
*/
function selectiveExtend(props, a, ...others) {
if (!Array.isArray(props)) {
throw new Error("Array with property names expected as first argument");
}
for (const other of others) {
for (let p = 0; p < props.length; p++) {
const prop = props[p];
if (other && Object.prototype.hasOwnProperty.call(other, prop)) {
a[prop] = other[prop];
}
}
}
return a;
}
/**
* Extend object a with selected properties of object b.
* Only properties with defined values are copied.
*
* @remarks
* Previous version of this routine implied that multiple source objects could
* be used; however, the implementation was **wrong**. Since multiple (\>1)
* sources weren't used anywhere in the `vis.js` code, this has been removed
* @param props - Names of first-level properties to copy over.
* @param a - Target object.
* @param b - Source object.
* @param allowDeletion - If true, delete property in a if explicitly set to null in b.
* @returns Argument a.
*/
function selectiveDeepExtend(props, a, b, allowDeletion = false) {
// TODO: add support for Arrays to deepExtend
if (Array.isArray(b)) {
throw new TypeError("Arrays are not supported by deepExtend");
}
for (let p = 0; p < props.length; p++) {
const prop = props[p];
if (Object.prototype.hasOwnProperty.call(b, prop)) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
deepExtend(a[prop], b[prop], false, allowDeletion);
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
throw new TypeError("Arrays are not supported by deepExtend");
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
}
return a;
}
/**
* Extend object `a` with properties of object `b`, ignoring properties which
* are explicitly specified to be excluded.
*
* @remarks
* The properties of `b` are considered for copying. Properties which are
* themselves objects are are also extended. Only properties with defined
* values are copied.
* @param propsToExclude - Names of properties which should *not* be copied.
* @param a - Object to extend.
* @param b - Object to take properties from for extension.
* @param allowDeletion - If true, delete properties in a that are explicitly
* set to null in b.
* @returns Argument a.
*/
function selectiveNotDeepExtend(propsToExclude, a, b, allowDeletion = false) {
// TODO: add support for Arrays to deepExtend
// NOTE: array properties have an else-below; apparently, there is a problem here.
if (Array.isArray(b)) {
throw new TypeError("Arrays are not supported by deepExtend");
}
for (const prop in b) {
if (!Object.prototype.hasOwnProperty.call(b, prop)) {
continue;
} // Handle local properties only
if (propsToExclude.includes(prop)) {
continue;
} // In exclusion list, skip
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
deepExtend(a[prop], b[prop]); // NOTE: allowDeletion not propagated!
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
a[prop] = [];
for (let i = 0; i < b[prop].length; i++) {
a[prop].push(b[prop][i]);
}
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
return a;
}
/**
* Deep extend an object a with the properties of object b.
*
* @param a - Target object.
* @param b - Source object.
* @param protoExtend - If true, the prototype values will also be extended.
* (That is the options objects that inherit from others will also get the
* inherited options).
* @param allowDeletion - If true, the values of fields that are null will be deleted.
* @returns Argument a.
*/
function deepExtend(a, b, protoExtend = false, allowDeletion = false) {
for (const prop in b) {
if (Object.prototype.hasOwnProperty.call(b, prop) || protoExtend === true) {
if (typeof b[prop] === "object" && b[prop] !== null && Object.getPrototypeOf(b[prop]) === Object.prototype) {
if (a[prop] === undefined) {
a[prop] = deepExtend({}, b[prop], protoExtend); // NOTE: allowDeletion not propagated!
} else if (typeof a[prop] === "object" && a[prop] !== null && Object.getPrototypeOf(a[prop]) === Object.prototype) {
deepExtend(a[prop], b[prop], protoExtend); // NOTE: allowDeletion not propagated!
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
a[prop] = b[prop].slice();
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
}
return a;
}
/**
* Test whether all elements in two arrays are equal.
*
* @param a - First array.
* @param b - Second array.
* @returns True if both arrays have the same length and same elements (1 = '1').
*/
function equalArray(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = 0, len = a.length; i < len; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
/**
* Get the type of an object, for example exports.getType([]) returns 'Array'.
*
* @param object - Input value of unknown type.
* @returns Detected type.
*/
function getType(object) {
const type = typeof object;
if (type === "object") {
if (object === null) {
return "null";
}
if (object instanceof Boolean) {
return "Boolean";
}
if (object instanceof Number) {
return "Number";
}
if (object instanceof String) {
return "String";
}
if (Array.isArray(object)) {
return "Array";
}
if (object instanceof Date) {
return "Date";
}
return "Object";
}
if (type === "number") {
return "Number";
}
if (type === "boolean") {
return "Boolean";
}
if (type === "string") {
return "String";
}
if (type === undefined) {
return "undefined";
}
return type;
}
/**
* Used to extend an array and copy it. This is used to propagate paths recursively.
*
* @param arr - First part.
* @param newValue - The value to be aadded into the array.
* @returns A new array with all items from arr and newValue (which is last).
*/
function copyAndExtendArray(arr, newValue) {
return [...arr, newValue];
}
/**
* Used to extend an array and copy it. This is used to propagate paths recursively.
*
* @param arr - The array to be copied.
* @returns Shallow copy of arr.
*/
function copyArray(arr) {
return arr.slice();
}
/**
* Retrieve the absolute left value of a DOM element.
*
* @param elem - A dom element, for example a div.
* @returns The absolute left position of this element in the browser page.
*/
function getAbsoluteLeft(elem) {
return elem.getBoundingClientRect().left;
}
/**
* Retrieve the absolute right value of a DOM element.
*
* @param elem - A dom element, for example a div.
* @returns The absolute right position of this element in the browser page.
*/
function getAbsoluteRight(elem) {
return elem.getBoundingClientRect().right;
}
/**
* Retrieve the absolute top value of a DOM element.
*
* @param elem - A dom element, for example a div.
* @returns The absolute top position of this element in the browser page.
*/
function getAbsoluteTop(elem) {
return elem.getBoundingClientRect().top;
}
/**
* Add a className to the given elements style.
*
* @param elem - The element to which the classes will be added.
* @param classNames - Space separated list of classes.
*/
function addClassName(elem, classNames) {
let classes = elem.className.split(" ");
const newClasses = classNames.split(" ");
classes = classes.concat(newClasses.filter(function (className) {
return !classes.includes(className);
}));
elem.className = classes.join(" ");
}
/**
* Remove a className from the given elements style.
*
* @param elem - The element from which the classes will be removed.
* @param classNames - Space separated list of classes.
*/
function removeClassName(elem, classNames) {
let classes = elem.className.split(" ");
const oldClasses = classNames.split(" ");
classes = classes.filter(function (className) {
return !oldClasses.includes(className);
});
elem.className = classes.join(" ");
}
/**
* For each method for both arrays and objects.
* In case of an array, the built-in Array.forEach() is applied (**No, it's not!**).
* In case of an Object, the method loops over all properties of the object.
*
* @param object - An Object or Array to be iterated over.
* @param callback - Array.forEach-like callback.
*/
function forEach(object, callback) {
if (Array.isArray(object)) {
// array
const len = object.length;
for (let i = 0; i < len; i++) {
callback(object[i], i, object);
}
} else {
// object
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
callback(object[key], key, object);
}
}
}
}
/**
* Convert an object into an array: all objects properties are put into the array. The resulting array is unordered.
*
* @param o - Object that contains the properties and methods.
* @returns An array of unordered values.
*/
const toArray = Object.values;
/**
* Update a property in an object.
*
* @param object - The object whose property will be updated.
* @param key - Name of the property to be updated.
* @param value - The new value to be assigned.
* @returns Whether the value was updated (true) or already strictly the same in the original object (false).
*/
function updateProperty(object, key, value) {
if (object[key] !== value) {
object[key] = value;
return true;
} else {
return false;
}
}
/**
* Throttle the given function to be only executed once per animation frame.
*
* @param fn - The original function.
* @returns The throttled function.
*/
function throttle(fn) {
let scheduled = false;
return () => {
if (!scheduled) {
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
fn();
});
}
};
}
/**
* Cancels the event's default action if it is cancelable, without stopping further propagation of the event.
*
* @param event - The event whose default action should be prevented.
*/
function preventDefault(event) {
if (!event) {
event = window.event;
}
if (!event) ;else if (event.preventDefault) {
event.preventDefault(); // non-IE browsers
} else {
// @TODO: IE types? Does anyone care?
event.returnValue = false; // IE browsers
}
}
/**
* Get HTML element which is the target of the event.
*
* @param event - The event.
* @returns The element or null if not obtainable.
*/
function getTarget(event = window.event) {
// code from http://www.quirksmode.org/js/events_properties.html
// @TODO: EventTarget can be almost anything, is it okay to return only Elements?
let target = null;
if (!event) ;else if (event.target) {
target = event.target;
} else if (event.srcElement) {
target = event.srcElement;
}
if (!(target instanceof Element)) {
return null;
}
if (target.nodeType != null && target.nodeType == 3) {
// defeat Safari bug
target = target.parentNode;
if (!(target instanceof Element)) {
return null;
}
}
return target;
}
/**
* Check if given element contains given parent somewhere in the DOM tree.
*
* @param element - The element to be tested.
* @param parent - The ancestor (not necessarily parent) of the element.
* @returns True if parent is an ancestor of the element, false otherwise.
*/
function hasParent(element, parent) {
let elem = element;
while (elem) {
if (elem === parent) {
return true;
} else if (elem.parentNode) {
elem = elem.parentNode;
} else {
return false;
}
}
return false;
}
const option = {
/**
* Convert a value into a boolean.
*
* @param value - Value to be converted intoboolean, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding boolean value, if none then the default value, if none then null.
*/
asBoolean(value, defaultValue) {
if (typeof value == "function") {
value = value();
}
if (value != null) {
return value != false;
}
return defaultValue || null;
},
/**
* Convert a value into a number.
*
* @param value - Value to be converted intonumber, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding **boxed** number value, if none then the default value, if none then null.
*/
asNumber(value, defaultValue) {
if (typeof value == "function") {
value = value();
}
if (value != null) {
return Number(value) || defaultValue || null;
}
return defaultValue || null;
},
/**
* Convert a value into a string.
*
* @param value - Value to be converted intostring, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding **boxed** string value, if none then the default value, if none then null.
*/
asString(value, defaultValue) {
if (typeof value == "function") {
value = value();
}
if (value != null) {
return String(value);
}
return defaultValue || null;
},
/**
* Convert a value into a size.
*
* @param value - Value to be converted intosize, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns Corresponding string value (number + 'px'), if none then the default value, if none then null.
*/
asSize(value, defaultValue) {
if (typeof value == "function") {
value = value();
}
if (isString(value)) {
return value;
} else if (isNumber(value)) {
return value + "px";
} else {
return defaultValue || null;
}
},
/**
* Convert a value into a DOM Element.
*
* @param value - Value to be converted into DOM Element, a function will be executed as `(() => unknown)`.
* @param defaultValue - If the value or the return value of the function == null then this will be returned.
* @returns The DOM Element, if none then the default value, if none then null.
*/
asElement(value, defaultValue) {
if (typeof value == "function") {
value = value();
}
return value || defaultValue || null;
}
};
/**
* Convert hex color string into RGB color object.
*
* @remarks
* {@link http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb}
* @param hex - Hex color string (3 or 6 digits, with or without #).
* @returns RGB color object.
*/
function hexToRGB(hex) {
let result;
switch (hex.length) {
case 3:
case 4:
result = shortHexRE.exec(hex);
return result ? {
r: parseInt(result[1] + result[1], 16),
g: parseInt(result[2] + result[2], 16),
b: parseInt(result[3] + result[3], 16)
} : null;
case 6:
case 7:
result = fullHexRE.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
default:
return null;
}
}
/**
* This function takes string color in hex or RGB format and adds the opacity, RGBA is passed through unchanged.
*
* @param color - The color string (hex, RGB, RGBA).
* @param opacity - The new opacity.
* @returns RGBA string, for example 'rgba(255, 0, 127, 0.3)'.
*/
function overrideOpacity(color, opacity) {
if (color.includes("rgba")) {
return color;
} else if (color.includes("rgb")) {
const rgb = color.substr(color.indexOf("(") + 1).replace(")", "").split(",");
return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")";
} else {
const rgb = hexToRGB(color);
if (rgb == null) {
return color;
} else {
return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")";
}
}
}
/**
* Convert RGB \<0, 255\> into hex color string.
*
* @param red - Red channel.
* @param green - Green channel.
* @param blue - Blue channel.
* @returns Hex color string (for example: '#0acdc0').
*/
function RGBToHex(red, green, blue) {
return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
}
/**
* Parse a color property into an object with border, background, and highlight colors.
*
* @param inputColor - Shorthand color string or input color object.
* @param defaultColor - Full color object to fill in missing values in inputColor.
* @returns Color object.
*/
function parseColor(inputColor, defaultColor) {
if (isString(inputColor)) {
let colorStr = inputColor;
if (isValidRGB(colorStr)) {
const rgb = colorStr.substr(4).substr(0, colorStr.length - 5).split(",").map(function (value) {
return parseInt(value);
});
colorStr = RGBToHex(rgb[0], rgb[1], rgb[2]);
}
if (isValidHex(colorStr) === true) {
const hsv = hexToHSV(colorStr);
const lighterColorHSV = {
h: hsv.h,
s: hsv.s * 0.8,
v: Math.min(1, hsv.v * 1.02)
};
const darkerColorHSV = {
h: hsv.h,
s: Math.min(1, hsv.s * 1.25),
v: hsv.v * 0.8
};
const darkerColorHex = HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
const lighterColorHex = HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
return {
background: colorStr,
border: darkerColorHex,
highlight: {
background: lighterColorHex,
border: darkerColorHex
},
hover: {
background: lighterColorHex,
border: darkerColorHex
}
};
} else {
return {
background: colorStr,
border: colorStr,
highlight: {
background: colorStr,
border: colorStr
},
hover: {
background: colorStr,
border: colorStr
}
};
}
} else {
if (defaultColor) {
const color = {
background: inputColor.background || defaultColor.background,
border: inputColor.border || defaultColor.border,
highlight: isString(inputColor.highlight) ? {
border: inputColor.highlight,
background: inputColor.highlight
} : {
background: inputColor.highlight && inputColor.highlight.background || defaultColor.highlight.background,
border: inputColor.highlight && inputColor.highlight.border || defaultColor.highlight.border
},
hover: isString(inputColor.hover) ? {
border: inputColor.hover,
background: inputColor.hover
} : {
border: inputColor.hover && inputColor.hover.border || defaultColor.hover.border,
background: inputColor.hover && inputColor.hover.background || defaultColor.hover.background
}
};
return color;
} else {
const color = {
background: inputColor.background || undefined,
border: inputColor.border || undefined,
highlight: isString(inputColor.highlight) ? {
border: inputColor.highlight,
background: inputColor.highlight
} : {
background: inputColor.highlight && inputColor.highlight.background || undefined,
border: inputColor.highlight && inputColor.highlight.border || undefined
},
hover: isString(inputColor.hover) ? {
border: inputColor.hover,
background: inputColor.hover
} : {
border: inputColor.hover && inputColor.hover.border || undefined,
background: inputColor.hover && inputColor.hover.background || undefined
}
};
return color;
}
}
}
/**
* Convert RGB \<0, 255\> into HSV object.
*
* @remarks
* {@link http://www.javascripter.net/faq/rgb2hsv.htm}
* @param red - Red channel.
* @param green - Green channel.
* @param blue - Blue channel.
* @returns HSV color object.
*/
function RGBToHSV(red, green, blue) {
red = red / 255;
green = green / 255;
blue = blue / 255;
const minRGB = Math.min(red, Math.min(green, blue));
const maxRGB = Math.max(red, Math.max(green, blue));
// Black-gray-white
if (minRGB === maxRGB) {
return {
h: 0,
s: 0,
v: minRGB
};
}
// Colors other than black-gray-white:
const d = red === minRGB ? green - blue : blue === minRGB ? red - green : blue - red;
const h = red === minRGB ? 3 : blue === minRGB ? 1 : 5;
const hue = 60 * (h - d / (maxRGB - minRGB)) / 360;
const saturation = (maxRGB - minRGB) / maxRGB;
const value = maxRGB;
return {
h: hue,
s: saturation,
v: value
};
}
/**
* Split a string with css styles into an object with key/values.
*
* @param cssText - CSS source code to split into key/value object.
* @returns Key/value object corresponding to {@link cssText}.
*/
function splitCSSText(cssText) {
const tmpEllement = document.createElement("div");
const styles = {};
tmpEllement.style.cssText = cssText;
for (let i = 0; i < tmpEllement.style.length; ++i) {
styles[tmpEllement.style[i]] = tmpEllement.style.getPropertyValue(tmpEllement.style[i]);
}
return styles;
}
/**
* Append a string with css styles to an element.
*
* @param element - The element that will receive new styles.
* @param cssText - The styles to be appended.
*/
function addCssText(element, cssText) {
const cssStyle = splitCSSText(cssText);
for (const [key, value] of Object.entries(cssStyle)) {
element.style.setProperty(key, value);
}
}
/**
* Remove a string with css styles from an element.
*
* @param element - The element from which styles should be removed.
* @param cssText - The styles to be removed.
*/
function removeCssText(element, cssText) {
const cssStyle = splitCSSText(cssText);
for (const key of Object.keys(cssStyle)) {
element.style.removeProperty(key);
}
}
/**
* Convert HSV \<0, 1\> into RGB color object.
*
* @remarks
* {@link https://gist.github.com/mjijackson/5311256}
* @param h - Hue.
* @param s - Saturation.
* @param v - Value.
* @returns RGB color object.
*/
function HSVToRGB(h, s, v) {
let r;
let g;
let b;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v, g = t, b = p;
break;
case 1:
r = q, g = v, b = p;
break;
case 2:
r = p, g = v, b = t;
break;
case 3:
r = p, g = q, b = v;
break;
case 4:
r = t, g = p, b = v;
break;
case 5:
r = v, g = p, b = q;
break;
}
return {
r: Math.floor(r * 255),
g: Math.floor(g * 255),
b: Math.floor(b * 255)
};
}
/**
* Convert HSV \<0, 1\> into hex color string.
*
* @param h - Hue.
* @param s - Saturation.
* @param v - Value.
* @returns Hex color string.
*/
function HSVToHex(h, s, v) {
const rgb = HSVToRGB(h, s, v);
return RGBToHex(rgb.r, rgb.g, rgb.b);
}
/**
* Convert hex color string into HSV \<0, 1\>.
*
* @param hex - Hex color string.
* @returns HSV color object.
*/
function hexToHSV(hex) {
const rgb = hexToRGB(hex);
if (!rgb) {
throw new TypeError(`'${hex}' is not a valid color.`);
}
return RGBToHSV(rgb.r, rgb.g, rgb.b);
}
/**
* Validate hex color string.
*
* @param hex - Unknown string that may contain a color.
* @returns True if the string is valid, false otherwise.
*/
function isValidHex(hex) {
const isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
return isOk;
}
/**
* Validate RGB color string.
*
* @param rgb - Unknown string that may contain a color.
* @returns True if the string is valid, false otherwise.
*/
function isValidRGB(rgb) {
return rgbRE.test(rgb);
}
/**
* Validate RGBA color string.
*
* @param rgba - Unknown string that may contain a color.
* @returns True if the string is valid, false otherwise.
*/
function isValidRGBA(rgba) {
return rgbaRE.test(rgba);
}
/**
* This recursively redirects the prototype of JSON objects to the referenceObject.
* This is used for default options.
*
* @param fields - Names of properties to be bridged.
* @param referenceObject - The original object.
* @returns A new object inheriting from the referenceObject.
*/
function selectiveBridgeObject(fields, referenceObject) {
if (referenceObject !== null && typeof referenceObject === "object") {
// !!! typeof null === 'object'
const objectTo = Object.create(referenceObject);
for (let i = 0; i < fields.length; i++) {
if (Object.prototype.hasOwnProperty.call(referenceObject, fields[i])) {
if (typeof referenceObject[fields[i]] == "object") {
objectTo[fields[i]] = bridgeObject(referenceObject[fields[i]]);
}
}
}
return objectTo;
} else {
return null;
}
}
/**
* This recursively redirects the prototype of JSON objects to the referenceObject.
* This is used for default options.
*
* @param referenceObject - The original object.
* @returns The Element if the referenceObject is an Element, or a new object inheriting from the referenceObject.
*/
function bridgeObject(referenceObject) {
if (referenceObject === null || typeof referenceObject !== "object") {
return null;
}
if (referenceObject instanceof Element) {
// Avoid bridging DOM objects
return referenceObject;
}
const objectTo = Object.create(referenceObject);
for (const i in referenceObject) {
if (Object.prototype.hasOwnProperty.call(referenceObject, i)) {
if (typeof referenceObject[i] == "object") {
objectTo[i] = bridgeObject(referenceObject[i]);
}
}
}
return objectTo;
}
/**
* This method provides a stable sort implementation, very fast for presorted data.
*
* @param a - The array to be sorted (in-place).
* @param compare - An order comparator.
* @returns The argument a.
*/
function insertSort(a, compare) {
for (let i = 0; i < a.length; i++) {
const k = a[i];
let j;
for (j = i; j > 0 && compare(k, a[j - 1]) < 0; j--) {
a[j] = a[j - 1];
}
a[j] = k;
}
return a;
}
/**
* This is used to set the options of subobjects in the options object.
*
* A requirement of these subobjects is that they have an 'enabled' element
* which is optional for the user but mandatory for the program.
*
* The added value here of the merge is that option 'enabled' is set as required.
*
* @param mergeTarget - Either this.options or the options used for the groups.
* @param options - Options.
* @param option - Option key in the options argument.
* @param globalOptions - Global options, passed in to determine value of option 'enabled'.
*/
function mergeOptions(mergeTarget, options, option, globalOptions = {}) {
// Local helpers
const isPresent = function (obj) {
return obj !== null && obj !== undefined;
};
const isObject = function (obj) {
return obj !== null && typeof obj === "object";
};
// https://stackoverflow.com/a/34491287/1223531
const isEmpty = function (obj) {
for (const x in obj) {
if (Object.prototype.hasOwnProperty.call(obj, x)) {
return false;
}
}
return true;
};
// Guards
if (!isObject(mergeTarget)) {
throw new Error("Parameter mergeTarget must be an object");
}
if (!isObject(options)) {
throw new Error("Parameter options must be an object");
}
if (!isPresent(option)) {
throw new Error("Parameter option must have a value");
}
if (!isObject(globalOptions)) {
throw new Error("Parameter globalOptions must be an object");
}
//
// Actual merge routine, separated from main logic
// Only a single level of options is merged. Deeper levels are ref'd. This may actually be an issue.
//
const doMerge = function (target, options, option) {
if (!isObject(target[option])) {
target[option] = {};
}
const src = options[option];
const dst = target[option];
for (const prop in src) {
if (Object.prototype.hasOwnProperty.call(src, prop)) {
dst[prop] = src[prop];
}
}
};
// Local initialization
const srcOption = options[option];
const globalPassed = isObject(globalOptions) && !isEmpty(globalOptions);
const globalOption = globalPassed ? globalOptions[option] : undefined;
const globalEnabled = globalOption ? globalOption.enabled : undefined;
/////////////////////////////////////////
// Main routine
/////////////////////////////////////////
if (srcOption === undefined) {
return; // Nothing to do
}
if (typeof srcOption === "boolean") {
if (!isObject(mergeTarget[option])) {
mergeTarget[option] = {};
}
mergeTarget[option].enabled = srcOption;
return;
}
if (srcOption === null && !isObject(mergeTarget[option])) {
// If possible, explicit copy from globals
if (isPresent(globalOption)) {
mergeTarget[option] = Object.create(globalOption);
} else {
return; // Nothing to do
}
}
if (!isObject(srcOption)) {
return;
}
//
// Ensure that 'enabled' is properly set. It is required internally
// Note that the value from options will always overwrite the existing value
//
let enabled = true; // default value
if (srcOption.enabled !== undefined) {
enabled = srcOption.enabled;
} else {
// Take from globals, if present
if (globalEnabled !== undefined) {
enabled = globalOption.enabled;
}
}
doMerge(mergeTarget, options, option);
mergeTarget[option].enabled = enabled;
}
/**
* This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
* this function will then iterate in both directions over this sorted list to find all visible items.
*
* @param orderedItems - Items ordered by start.
* @param comparator - -1 is lower, 0 is equal, 1 is higher.
* @param field - Property name on an item (That is item[field]).
* @param field2 - Second property name on an item (That is item[field][field2]).
* @returns Index of the found item or -1 if nothing was found.
*/
function binarySearchCustom(orderedItems, comparator, field, field2) {
const maxIterations = 10000;
let iteration = 0;
let low = 0;
let high = orderedItems.length - 1;
while (low <= high && iteration < maxIterations) {
const middle = Math.floor((low + high) / 2);
const item = orderedItems[middle];
const value = field2 === undefined ? item[field] : item[field][field2];
const searchResult = comparator(value);
if (searchResult == 0) {
// jihaa, found a visible item!
return middle;
} else if (searchResult == -1) {
// it is too small --> increase low
low = middle + 1;
} else {
// it is too big --> decrease high
high = middle - 1;
}
iteration++;
}
return -1;
}
/**
* This function does a binary search for a specific value in a sorted array.
* If it does not exist but is in between of two values, we return either the
* one before or the one after, depending on user input If it is found, we
* return the index, else -1.
*
* @param orderedItems - Sorted array.
* @param target - The searched value.
* @param field - Name of the property in items to be searched.
* @param sidePreference - If the target is between two values, should the index of the before or the after be returned?
* @param comparator - An optional comparator, returning -1, 0, 1 for \<, ===, \>.
* @returns The index of found value or -1 if nothing was found.
*/
function binarySearchValue(orderedItems, target, field, sidePreference, comparator) {
const maxIterations = 10000;
let iteration = 0;
let low = 0;
let high = orderedItems.length - 1;
let prevValue;
let value;
let nextValue;
let middle;
comparator = comparator != undefined ? comparator : function (a, b) {
return a == b ? 0 : a < b ? -1 : 1;
};
while (low <= high && iteration < maxIterations) {
// get a new guess
middle = Math.floor(0.5 * (high + low));
prevValue = orderedItems[Math.max(0, middle - 1)][field];
value = orderedItems[middle][field];
nextValue = orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
if (comparator(value, target) == 0) {
// we found the target
return middle;
} else if (comparator(prevValue, target) < 0 && comparator(value, target) > 0) {
// target is in between of the previous and the current
return sidePreference == "before" ? Math.max(0, middle - 1) : middle;
} else if (comparator(value, target) < 0 && comparator(nextValue, target) > 0) {
// target is in between of the current and the next
return sidePreference == "before" ? middle : Math.min(orderedItems.length - 1, middle + 1);
} else {
// didnt find the target, we need to change our boundaries.
if (comparator(value, target) < 0) {
// it is too small --> increase low
low = middle + 1;
} else {
// it is too big --> decrease high
high = middle - 1;
}
}
iteration++;
}
// didnt find anything. Return -1.
return -1;
}
/*
* Easing Functions.
* Only considering the t value for the range [0, 1] => [0, 1].
*
* Inspiration: from http://gizma.com/easing/
* https://gist.github.com/gre/1650294
*/
const easingFunctions = {
/**
* Provides no easing and no acceleration.
*
* @param t - Time.
* @returns Value at time t.
*/
linear(t) {
return t;
},
/**
* Accelerate from zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInQuad(t) {
return t * t;
},
/**
* Decelerate to zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeOutQuad(t) {
return t * (2 - t);
},
/**
* Accelerate until halfway, then decelerate.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
},
/**
* Accelerate from zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInCubic(t) {
return t * t * t;
},
/**
* Decelerate to zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeOutCubic(t) {
return --t * t * t + 1;
},
/**
* Accelerate until halfway, then decelerate.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInOutCubic(t) {
return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
},
/**
* Accelerate from zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInQuart(t) {
return t * t * t * t;
},
/**
* Decelerate to zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeOutQuart(t) {
return 1 - --t * t * t * t;
},
/**
* Accelerate until halfway, then decelerate.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInOutQuart(t) {
return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
},
/**
* Accelerate from zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInQuint(t) {
return t * t * t * t * t;
},
/**
* Decelerate to zero velocity.
*
* @param t - Time.
* @returns Value at time t.
*/
easeOutQuint(t) {
return 1 + --t * t * t * t * t;
},
/**
* Accelerate until halfway, then decelerate.
*
* @param t - Time.
* @returns Value at time t.
*/
easeInOutQuint(t) {
return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
}
};
/**
* Experimentaly compute the width of the scrollbar for this browser.
*
* @returns The width in pixels.
*/
function getScrollBarWidth() {
const inner = document.createElement("p");
inner.style.width = "100%";
inner.style.height = "200px";
const outer = document.createElement("div");
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
const w1 = inner.offsetWidth;
outer.style.overflow = "scroll";
let w2 = inner.offsetWidth;
if (w1 == w2) {
w2 = outer.clientWidth;
}
document.body.removeChild(outer);
return w1 - w2;
}
// @TODO: This doesn't work properly.
// It works only for single property objects,
// otherwise it combines all of the types in a union.
// export function topMost<K1 extends string, V1> (
// pile: Record<K1, undefined | V1>[],
// accessors: K1 | [K1]
// ): undefined | V1
// export function topMost<K1 extends string, K2 extends string, V1, V2> (
// pile: Record<K1, undefined | V1 | Record<K2, undefined | V2>>[],
// accessors: [K1, K2]
// ): undefined | V1 | V2
// export function topMost<K1 extends string, K2 extends string, K3 extends string, V1, V2, V3> (
// pile: Record<K1, undefined | V1 | Record<K2, undefined | V2 | Record<K3, undefined | V3>>>[],
// accessors: [K1, K2, K3]
// ): undefined | V1 | V2 | V3
/**
* Get the top most property value from a pile of objects.
*
* @param pile - Array of objects, no required format.
* @param accessors - Array of property names.
* For example `object['foo']['bar']` → `['foo', 'bar']`.
* @returns Value of the property with given accessors path from the first pile item where it's not undefined.
*/
function topMost(pile, accessors) {
let candidate;
if (!Array.isArray(accessors)) {
accessors = [accessors];
}
for (const member of pile) {
if (member) {
candidate = member[accessors[0]];
for (let i = 1; i < accessors.length; i++) {
if (candidate) {
candidate = candidate[accessors[i]];
}
}
if (typeof candidate !== "undefined") {
break;
}
}
}
return candidate;
}
const htmlColors$1 = {
black: "#000000",
navy: "#000080",
darkblue: "#00008B",
mediumblue: "#0000CD",
blue: "#0000FF",
darkgreen: "#006400",
green: "#008000",
teal: "#008080",
darkcyan: "#008B8B",
deepskyblue: "#00BFFF",
darkturquoise: "#00CED1",
mediumspringgreen: "#00FA9A",
lime: "#00FF00",
springgreen: "#00FF7F",
aqua: "#00FFFF",
cyan: "#00FFFF",
midnightblue: "#191970",
dodgerblue: "#1E90FF",
lightseagreen: "#20B2AA",
forestgreen: "#228B22",
seagreen: "#2E8B57",
darkslategray: "#2F4F4F",
limegreen: "#32CD32",
mediumseagreen: "#3CB371",
turquoise: "#40E0D0",
royalblue: "#4169E1",
steelblue: "#4682B4",
darkslateblue: "#483D8B",
mediumturquoise: "#48D1CC",
indigo: "#4B0082",
darkolivegreen: "#556B2F",
cadetblue: "#5F9EA0",
cornflowerblue: "#6495ED",
mediumaquamarine: "#66CDAA",
dimgray: "#696969",
slateblue: "#6A5ACD",
olivedrab: "#6B8E23",
slategray: "#708090",
lightslategray: "#778899",
mediumslateblue: "#7B68EE",
lawngreen: "#7CFC00",
chartreuse: "#7FFF00",
aquamarine: "#7FFFD4",
maroon: "#800000",
purple: "#800080",
olive: "#808000",
gray: "#808080",
skyblue: "#87CEEB",
lightskyblue: "#87CEFA",
blueviolet: "#8A2BE2",
darkred: "#8B0000",
darkmagenta: "#8B008B",
saddlebrown: "#8B4513",
darkseagreen: "#8FBC8F",
lightgreen: "#90EE90",
mediumpurple: "#9370D8",
darkviolet: "#9400D3",
palegreen: "#98FB98",
darkorchid: "#9932CC",
yellowgreen: "#9ACD32",
sienna: "#A0522D",
brown: "#A52A2A",
darkgray: "#A9A9A9",
lightblue: "#ADD8E6",
greenyellow: "#ADFF2F",
paleturquoise: "#AFEEEE",
lightsteelblue: "#B0C4DE",
powderblue: "#B0E0E6",
firebrick: "#B22222",
darkgoldenrod: "#B8860B",
mediumorchid: "#BA55D3",
rosybrown: "#BC8F8F",
darkkhaki: "#BDB76B",
silver: "#C0C0C0",
mediumvioletred: "#C71585",
indianred: "#CD5C5C",
peru: "#CD853F",
chocolate: "#D2691E",
tan: "#D2B48C",
lightgrey: "#D3D3D3",
palevioletred: "#D87093",
thistle: "#D8BFD8",
orchid: "#DA70D6",
goldenrod: "#DAA520",
crimson: "#DC143C",
gainsboro: "#DCDCDC",
plum: "#DDA0DD",
burlywood: "#DEB887",
lightcyan: "#E0FFFF",
lavender: "#E6E6FA",
darksalmon: "#E9967A",
violet: "#EE82EE",
palegoldenrod: "#EEE8AA",
lightcoral: "#F08080",
khaki: "#F0E68C",
aliceblue: "#F0F8FF",
honeydew: "#F0FFF0",
azure: "#F0FFFF",
sandybrown: "#F4A460",
wheat: "#F5DEB3",
beige: "#F5F5DC",
whitesmoke: "#F5F5F5",
mintcream: "#F5FFFA",
ghostwhite: "#F8F8FF",
salmon: "#FA8072",
antiquewhite: "#FAEBD7",
linen: "#FAF0E6",
lightgoldenrodyellow: "#FAFAD2",
oldlace: "#FDF5E6",
red: "#FF0000",
fuchsia: "#FF00FF",
magenta: "#FF00FF",
deeppink: "#FF1493",
orangered: "#FF4500",
tomato: "#FF6347",
hotpink: "#FF69B4",
coral: "#FF7F50",
darkorange: "#FF8C00",
lightsalmon: "#FFA07A",
orange: "#FFA500",
lightpink: "#FFB6C1",
pink: "#FFC0CB",
gold: "#FFD700",
peachpuff: "#FFDAB9",
navajowhite: "#FFDEAD",
moccasin: "#FFE4B5",
bisque: "#FFE4C4",
mistyrose: "#FFE4E1",
blanchedalmond: "#FFEBCD",
papayawhip: "#FFEFD5",
lavenderblush: "#FFF0F5",
seashell: "#FFF5EE",
cornsilk: "#FFF8DC",
lemonchiffon: "#FFFACD",
floralwhite: "#FFFAF0",
snow: "#FFFAFA",
yellow: "#FFFF00",
lightyellow: "#FFFFE0",
ivory: "#FFFFF0",
white: "#FFFFFF"
};
/**
* @param {number} [pixelRatio=1]
*/
let ColorPicker$1 = class ColorPicker {
/**
* @param {number} [pixelRatio=1]
*/
constructor(pixelRatio = 1) {
this.pixelRatio = pixelRatio;
this.generated = false;
this.centerCoordinates = {
x: 289 / 2,
y: 289 / 2
};
this.r = 289 * 0.49;
this.color = {
r: 255,
g: 255,
b: 255,
a: 1.0
};
this.hueCircle = undefined;
this.initialColor = {
r: 255,
g: 255,
b: 255,
a: 1.0
};
this.previousColor = undefined;
this.applied = false;
// bound by
this.updateCallback = () => {};
this.closeCallback = () => {};
// create all DOM elements
this._create();
}
/**
* this inserts the colorPicker into a div from the DOM
*
* @param {Element} container
*/
insertTo(container) {
if (this.hammer !== undefined) {
this.hammer.destroy();
this.hammer = undefined;
}
this.container = container;
this.container.appendChild(this.frame);
this._bindHammer();
this._setSize();
}
/**
* the callback is executed on apply and save. Bind it to the application
*
* @param {Function} callback
*/
setUpdateCallback(callback) {
if (typeof callback === "function") {
this.updateCallback = callback;
} else {
throw new Error("Function attempted to set as colorPicker update callback is not a function.");
}
}
/**
* the callback is executed on apply and save. Bind it to the application
*
* @param {Function} callback
*/
setCloseCallback(callback) {
if (typeof callback === "function") {
this.closeCallback = callback;
} else {
throw new Error("Function attempted to set as colorPicker closing callback is not a function.");
}
}
/**
*
* @param {string} color
* @returns {string}
* @private
*/
_isColorString(color) {
if (typeof color === "string") {
return htmlColors$1[color];
}
}
/**
* Set the color of the colorPicker
* Supported formats:
* 'red' --> HTML color string
* '#ffffff' --> hex string
* 'rgb(255,255,255)' --> rgb string
* 'rgba(255,255,255,1.0)' --> rgba string
* {r:255,g:255,b:255} --> rgb object
* {r:255,g:255,b:255,a:1.0} --> rgba object
*
* @param {string | object} color
* @param {boolean} [setInitial=true]
*/
setColor(color, setInitial = true) {
if (color === "none") {
return;
}
let rgba;
// if a html color shorthand is used, convert to hex
const htmlColor = this._isColorString(color);
if (htmlColor !== undefined) {
color = htmlColor;
}
// check format
if (isString(color) === true) {
if (isValidRGB(color) === true) {
const rgbaArray = color.substr(4).substr(0, color.length - 5).split(",");
rgba = {
r: rgbaArray[0],
g: rgbaArray[1],
b: rgbaArray[2],
a: 1.0
};
} else if (isValidRGBA(color) === true) {
const rgbaArray = color.substr(5).substr(0, color.length - 6).split(",");
rgba = {
r: rgbaArray[0],
g: rgbaArray[1],
b: rgbaArray[2],
a: rgbaArray[3]
};
} else if (isValidHex(color) === true) {
const rgbObj = hexToRGB(color);
rgba = {
r: rgbObj.r,
g: rgbObj.g,
b: rgbObj.b,
a: 1.0
};
}
} else {
if (color instanceof Object) {
if (color.r !== undefined && color.g !== undefined && color.b !== undefined) {
const alpha = color.a !== undefined ? color.a : "1.0";
rgba = {
r: color.r,
g: color.g,
b: color.b,
a: alpha
};
}
}
}
// set color
if (rgba === undefined) {
throw new Error("Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: " + JSON.stringify(color));
} else {
this._setColor(rgba, setInitial);
}
}
/**
* this shows the color picker.
* The hue circle is constructed once and stored.
*/
show() {
if (this.closeCallback !== undefined) {
this.closeCallback();
this.closeCallback = undefined;
}
this.applied = false;
this.frame.style.display = "block";
this._generateHueCircle();
}
// ------------------------------------------ PRIVATE ----------------------------- //
/**
* Hide the picker. Is called by the cancel button.
* Optional boolean to store the previous color for easy access later on.
*
* @param {boolean} [storePrevious=true]
* @private
*/
_hide(storePrevious = true) {
// store the previous color for next time;
if (storePrevious === true) {
this.previousColor = Object.assign({}, this.color);
}
if (this.applied === true) {
this.updateCallback(this.initialColor);
}
this.frame.style.display = "none";
// call the closing callback, restoring the onclick method.
// this is in a setTimeout because it will trigger the show again before the click is done.
setTimeout(() => {
if (this.closeCallback !== undefined) {
this.closeCallback();
this.closeCallback = undefined;
}
}, 0);
}
/**
* bound to the save button. Saves and hides.
*
* @private
*/
_save() {
this.updateCallback(this.color);
this.applied = false;
this._hide();
}
/**
* Bound to apply button. Saves but does not close. Is undone by the cancel button.
*
* @private
*/
_apply() {
this.applied = true;
this.updateCallback(this.color);
this._updatePicker(this.color);
}
/**
* load the color from the previous session.
*
* @private
*/
_loadLast() {
if (this.previousColor !== undefined) {
this.setColor(this.previousColor, false);
} else {
alert("There is no last color to load...");
}
}
/**
* set the color, place the picker
*
* @param {object} rgba
* @param {boolean} [setInitial=true]
* @private
*/
_setColor(rgba, setInitial = true) {
// store the initial color
if (setInitial === true) {
this.initialColor = Object.assign({}, rgba);
}
this.color = rgba;
const hsv = RGBToHSV(rgba.r, rgba.g, rgba.b);
const angleConvert = 2 * Math.PI;
const radius = this.r * hsv.s;
const x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h);
const y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h);
this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + "px";
this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + "px";
this._updatePicker(rgba);
}
/**
* bound to opacity control
*
* @param {number} value
* @private
*/
_setOpacity(value) {
this.color.a = value / 100;
this._updatePicker(this.color);
}
/**
* bound to brightness control
*
* @param {number} value
* @private
*/
_setBrightness(value) {
const hsv = RGBToHSV(this.color.r, this.color.g, this.color.b);
hsv.v = value / 100;
const rgba = HSVToRGB(hsv.h, hsv.s, hsv.v);
rgba["a"] = this.color.a;
this.color = rgba;
this._updatePicker();
}
/**
* update the color picker. A black circle overlays the hue circle to mimic the brightness decreasing.
*
* @param {object} rgba
* @private
*/
_updatePicker(rgba = this.color) {
const hsv = RGBToHSV(rgba.r, rgba.g, rgba.b);
const ctx = this.colorPickerCanvas.getContext("2d");
if (this.pixelRation === undefined) {
this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
}
ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
// clear the canvas
const w = this.colorPickerCanvas.clientWidth;
const h = this.colorPickerCanvas.clientHeight;
ctx.clearRect(0, 0, w, h);
ctx.putImageData(this.hueCircle, 0, 0);
ctx.fillStyle = "rgba(0,0,0," + (1 - hsv.v) + ")";
ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
ctx.fill();
this.brightnessRange.value = 100 * hsv.v;
this.opacityRange.value = 100 * rgba.a;
this.initialColorDiv.style.backgroundColor = "rgba(" + this.initialColor.r + "," + this.initialColor.g + "," + this.initialColor.b + "," + this.initialColor.a + ")";
this.newColorDiv.style.backgroundColor = "rgba(" + this.color.r + "," + this.color.g + "," + this.color.b + "," + this.color.a + ")";
}
/**
* used by create to set the size of the canvas.
*
* @private
*/
_setSize() {
this.colorPickerCanvas.style.width = "100%";
this.colorPickerCanvas.style.height = "100%";
this.colorPickerCanvas.width = 289 * this.pixelRatio;
this.colorPickerCanvas.height = 289 * this.pixelRatio;
}
/**
* create all dom elements
* TODO: cleanup, lots of similar dom elements
*
* @private
*/
_create() {
this.frame = document.createElement("div");
this.frame.className = "vis-color-picker";
this.colorPickerDiv = document.createElement("div");
this.colorPickerSelector = document.createElement("div");
this.colorPickerSelector.className = "vis-selector";
this.colorPickerDiv.appendChild(this.colorPickerSelector);
this.colorPickerCanvas = document.createElement("canvas");
this.colorPickerDiv.appendChild(this.colorPickerCanvas);
if (!this.colorPickerCanvas.getContext) {
const noCanvas = document.createElement("DIV");
noCanvas.style.color = "red";
noCanvas.style.fontWeight = "bold";
noCanvas.style.padding = "10px";
noCanvas.innerText = "Error: your browser does not support HTML canvas";
this.colorPickerCanvas.appendChild(noCanvas);
} else {
const ctx = this.colorPickerCanvas.getContext("2d");
this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
this.colorPickerCanvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
}
this.colorPickerDiv.className = "vis-color";
this.opacityDiv = document.createElement("div");
this.opacityDiv.className = "vis-opacity";
this.brightnessDiv = document.createElement("div");
this.brightnessDiv.className = "vis-brightness";
this.arrowDiv = document.createElement("div");
this.arrowDiv.className = "vis-arrow";
this.opacityRange = document.createElement("input");
try {
this.opacityRange.type = "range"; // Not supported on IE9
this.opacityRange.min = "0";
this.opacityRange.max = "100";
} catch (err) {
// TODO: Add some error handling.
}
this.opacityRange.value = "100";
this.opacityRange.className = "vis-range";
this.brightnessRange = document.createElement("input");
try {
this.brightnessRange.type = "range"; // Not supported on IE9
this.brightnessRange.min = "0";
this.brightnessRange.max = "100";
} catch (err) {
// TODO: Add some error handling.
}
this.brightnessRange.value = "100";
this.brightnessRange.className = "vis-range";
this.opacityDiv.appendChild(this.opacityRange);
this.brightnessDiv.appendChild(this.brightnessRange);
const me = this;
this.opacityRange.onchange = function () {
me._setOpacity(this.value);
};
this.opacityRange.oninput = function () {
me._setOpacity(this.value);
};
this.brightnessRange.onchange = function () {
me._setBrightness(this.value);
};
this.brightnessRange.oninput = function () {
me._setBrightness(this.value);
};
this.brightnessLabel = document.createElement("div");
this.brightnessLabel.className = "vis-label vis-brightness";
this.brightnessLabel.innerText = "brightness:";
this.opacityLabel = document.createElement("div");
this.opacityLabel.className = "vis-label vis-opacity";
this.opacityLabel.innerText = "opacity:";
this.newColorDiv = document.createElement("div");
this.newColorDiv.className = "vis-new-color";
this.newColorDiv.innerText = "new";
this.initialColorDiv = document.createElement("div");
this.initialColorDiv.className = "vis-initial-color";
this.initialColorDiv.innerText = "initial";
this.cancelButton = document.createElement("div");
this.cancelButton.className = "vis-button vis-cancel";
this.cancelButton.innerText = "cancel";
this.cancelButton.onclick = this._hide.bind(this, false);
this.applyButton = document.createElement("div");
this.applyButton.className = "vis-button vis-apply";
this.applyButton.innerText = "apply";
this.applyButton.onclick = this._apply.bind(this);
this.saveButton = document.createElement("div");
this.saveButton.className = "vis-button vis-save";
this.saveButton.innerText = "save";
this.saveButton.onclick = this._save.bind(this);
this.loadButton = document.createElement("div");
this.loadButton.className = "vis-button vis-load";
this.loadButton.innerText = "load last";
this.loadButton.onclick = this._loadLast.bind(this);
this.frame.appendChild(this.colorPickerDiv);
this.frame.appendChild(this.arrowDiv);
this.frame.appendChild(this.brightnessLabel);
this.frame.appendChild(this.brightnessDiv);
this.frame.appendChild(this.opacityLabel);
this.frame.appendChild(this.opacityDiv);
this.frame.appendChild(this.newColorDiv);
this.frame.appendChild(this.initialColorDiv);
this.frame.appendChild(this.cancelButton);
this.frame.appendChild(this.applyButton);
this.frame.appendChild(this.saveButton);
this.frame.appendChild(this.loadButton);
}
/**
* bind hammer to the color picker
*
* @private
*/
_bindHammer() {
this.drag = {};
this.pinch = {};
this.hammer = new Hammer$1(this.colorPickerCanvas);
this.hammer.get("pinch").set({
enable: true
});
this.hammer.on("hammer.input", event => {
if (event.isFirst) {
this._moveSelector(event);
}
});
this.hammer.on("tap", event => {
this._moveSelector(event);
});
this.hammer.on("panstart", event => {
this._moveSelector(event);
});
this.hammer.on("panmove", event => {
this._moveSelector(event);
});
this.hammer.on("panend", event => {
this._moveSelector(event);
});
}
/**
* generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
*
* @private
*/
_generateHueCircle() {
if (this.generated === false) {
const ctx = this.colorPickerCanvas.getContext("2d");
if (this.pixelRation === undefined) {
this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
}
ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
// clear the canvas
const w = this.colorPickerCanvas.clientWidth;
const h = this.colorPickerCanvas.clientHeight;
ctx.clearRect(0, 0, w, h);
// draw hue circle
let x, y, hue, sat;
this.centerCoordinates = {
x: w * 0.5,
y: h * 0.5
};
this.r = 0.49 * w;
const angleConvert = 2 * Math.PI / 360;
const hfac = 1 / 360;
const sfac = 1 / this.r;
let rgb;
for (hue = 0; hue < 360; hue++) {
for (sat = 0; sat < this.r; sat++) {
x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue);
y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue);
rgb = HSVToRGB(hue * hfac, sat * sfac, 1);
ctx.fillStyle = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
ctx.fillRect(x - 0.5, y - 0.5, 2, 2);
}
}
ctx.strokeStyle = "rgba(0,0,0,1)";
ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
ctx.stroke();
this.hueCircle = ctx.getImageData(0, 0, w, h);
}
this.generated = true;
}
/**
* move the selector. This is called by hammer functions.
*
* @param {Event} event The event
* @private
*/
_moveSelector(event) {
const rect = this.colorPickerDiv.getBoundingClientRect();
const left = event.center.x - rect.left;
const top = event.center.y - rect.top;
const centerY = 0.5 * this.colorPickerDiv.clientHeight;
const centerX = 0.5 * this.colorPickerDiv.clientWidth;
const x = left - centerX;
const y = top - centerY;
const angle = Math.atan2(x, y);
const radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX);
const newTop = Math.cos(angle) * radius + centerY;
const newLeft = Math.sin(angle) * radius + centerX;
this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + "px";
this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + "px";
// set color
let h = angle / (2 * Math.PI);
h = h < 0 ? h + 1 : h;
const s = radius / this.r;
const hsv = RGBToHSV(this.color.r, this.color.g, this.color.b);
hsv.h = h;
hsv.s = s;
const rgba = HSVToRGB(hsv.h, hsv.s, hsv.v);
rgba["a"] = this.color.a;
this.color = rgba;
// update previews
this.initialColorDiv.style.backgroundColor = "rgba(" + this.initialColor.r + "," + this.initialColor.g + "," + this.initialColor.b + "," + this.initialColor.a + ")";
this.newColorDiv.style.backgroundColor = "rgba(" + this.color.r + "," + this.color.g + "," + this.color.b + "," + this.color.a + ")";
}
};
/**
* Wrap given text (last argument) in HTML elements (all preceding arguments).
*
* @param {...any} rest - List of tag names followed by inner text.
* @returns An element or a text node.
*/
function wrapInTag(...rest) {
if (rest.length < 1) {
throw new TypeError("Invalid arguments.");
} else if (rest.length === 1) {
return document.createTextNode(rest[0]);
} else {
const element = document.createElement(rest[0]);
element.appendChild(wrapInTag(...rest.slice(1)));
return element;
}
}
/**
* The way this works is for all properties of this.possible options, you can supply the property name in any form to list the options.
* Boolean options are recognised as Boolean
* Number options should be written as array: [default value, min value, max value, stepsize]
* Colors should be written as array: ['color', '#ffffff']
* Strings with should be written as array: [option1, option2, option3, ..]
*
* The options are matched with their counterparts in each of the modules and the values used in the configuration are
*/
let Configurator$1 = class Configurator {
/**
* @param {object} parentModule | the location where parentModule.setOptions() can be called
* @param {object} defaultContainer | the default container of the module
* @param {object} configureOptions | the fully configured and predefined options set found in allOptions.js
* @param {number} pixelRatio | canvas pixel ratio
* @param {Function} hideOption | custom logic to dynamically hide options
*/
constructor(parentModule, defaultContainer, configureOptions, pixelRatio = 1, hideOption = () => false) {
this.parent = parentModule;
this.changedOptions = [];
this.container = defaultContainer;
this.allowCreation = false;
this.hideOption = hideOption;
this.options = {};
this.initialized = false;
this.popupCounter = 0;
this.defaultOptions = {
enabled: false,
filter: true,
container: undefined,
showButton: true
};
Object.assign(this.options, this.defaultOptions);
this.configureOptions = configureOptions;
this.moduleOptions = {};
this.domElements = [];
this.popupDiv = {};
this.popupLimit = 5;
this.popupHistory = {};
this.colorPicker = new ColorPicker$1(pixelRatio);
this.wrapper = undefined;
}
/**
* refresh all options.
* Because all modules parse their options by themselves, we just use their options. We copy them here.
*
* @param {object} options
*/
setOptions(options) {
if (options !== undefined) {
// reset the popup history because the indices may have been changed.
this.popupHistory = {};
this._removePopup();
let enabled = true;
if (typeof options === "string") {
this.options.filter = options;
} else if (Array.isArray(options)) {
this.options.filter = options.join();
} else if (typeof options === "object") {
if (options == null) {
throw new TypeError("options cannot be null");
}
if (options.container !== undefined) {
this.options.container = options.container;
}
if (options.filter !== undefined) {
this.options.filter = options.filter;
}
if (options.showButton !== undefined) {
this.options.showButton = options.showButton;
}
if (options.enabled !== undefined) {
enabled = options.enabled;
}
} else if (typeof options === "boolean") {
this.options.filter = true;
enabled = options;
} else if (typeof options === "function") {
this.options.filter = options;
enabled = true;
}
if (this.options.filter === false) {
enabled = false;
}
this.options.enabled = enabled;
}
this._clean();
}
/**
*
* @param {object} moduleOptions
*/
setModuleOptions(moduleOptions) {
this.moduleOptions = moduleOptions;
if (this.options.enabled === true) {
this._clean();
if (this.options.container !== undefined) {
this.container = this.options.container;
}
this._create();
}
}
/**
* Create all DOM elements
*
* @private
*/
_create() {
this._clean();
this.changedOptions = [];
const filter = this.options.filter;
let counter = 0;
let show = false;
for (const option in this.configureOptions) {
if (Object.prototype.hasOwnProperty.call(this.configureOptions, option)) {
this.allowCreation = false;
show = false;
if (typeof filter === "function") {
show = filter(option, []);
show = show || this._handleObject(this.configureOptions[option], [option], true);
} else if (filter === true || filter.indexOf(option) !== -1) {
show = true;
}
if (show !== false) {
this.allowCreation = true;
// linebreak between categories
if (counter > 0) {
this._makeItem([]);
}
// a header for the category
this._makeHeader(option);
// get the sub options
this._handleObject(this.configureOptions[option], [option]);
}
counter++;
}
}
this._makeButton();
this._push();
//~ this.colorPicker.insertTo(this.container);
}
/**
* draw all DOM elements on the screen
*
* @private
*/
_push() {
this.wrapper = document.createElement("div");
this.wrapper.className = "vis-configuration-wrapper";
this.container.appendChild(this.wrapper);
for (let i = 0; i < this.domElements.length; i++) {
this.wrapper.appendChild(this.domElements[i]);
}
this._showPopupIfNeeded();
}
/**
* delete all DOM elements
*
* @private
*/
_clean() {
for (let i = 0; i < this.domElements.length; i++) {
this.wrapper.removeChild(this.domElements[i]);
}
if (this.wrapper !== undefined) {
this.container.removeChild(this.wrapper);
this.wrapper = undefined;
}
this.domElements = [];
this._removePopup();
}
/**
* get the value from the actualOptions if it exists
*
* @param {Array} path | where to look for the actual option
* @returns {*}
* @private
*/
_getValue(path) {
let base = this.moduleOptions;
for (let i = 0; i < path.length; i++) {
if (base[path[i]] !== undefined) {
base = base[path[i]];
} else {
base = undefined;
break;
}
}
return base;
}
/**
* all option elements are wrapped in an item
*
* @param {Array} path | where to look for the actual option
* @param {Array.<Element>} domElements
* @returns {number}
* @private
*/
_makeItem(path, ...domElements) {
if (this.allowCreation === true) {
const item = document.createElement("div");
item.className = "vis-configuration vis-config-item vis-config-s" + path.length;
domElements.forEach(element => {
item.appendChild(element);
});
this.domElements.push(item);
return this.domElements.length;
}
return 0;
}
/**
* header for major subjects
*
* @param {string} name
* @private
*/
_makeHeader(name) {
const div = document.createElement("div");
div.className = "vis-configuration vis-config-header";
div.innerText = name;
this._makeItem([], div);
}
/**
* make a label, if it is an object label, it gets different styling.
*
* @param {string} name
* @param {Array} path | where to look for the actual option
* @param {string} objectLabel
* @returns {HTMLElement}
* @private
*/
_makeLabel(name, path, objectLabel = false) {
const div = document.createElement("div");
div.className = "vis-configuration vis-config-label vis-config-s" + path.length;
if (objectLabel === true) {
while (div.firstChild) {
div.removeChild(div.firstChild);
}
div.appendChild(wrapInTag("i", "b", name));
} else {
div.innerText = name + ":";
}
return div;
}
/**
* make a dropdown list for multiple possible string optoins
*
* @param {Array.<number>} arr
* @param {number} value
* @param {Array} path | where to look for the actual option
* @private
*/
_makeDropdown(arr, value, path) {
const select = document.createElement("select");
select.className = "vis-configuration vis-config-select";
let selectedValue = 0;
if (value !== undefined) {
if (arr.indexOf(value) !== -1) {
selectedValue = arr.indexOf(value);
}
}
for (let i = 0; i < arr.length; i++) {
const option = document.createElement("option");
option.value = arr[i];
if (i === selectedValue) {
option.selected = "selected";
}
option.innerText = arr[i];
select.appendChild(option);
}
const me = this;
select.onchange = function () {
me._update(this.value, path);
};
const label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, select);
}
/**
* make a range object for numeric options
*
* @param {Array.<number>} arr
* @param {number} value
* @param {Array} path | where to look for the actual option
* @private
*/
_makeRange(arr, value, path) {
const defaultValue = arr[0];
const min = arr[1];
const max = arr[2];
const step = arr[3];
const range = document.createElement("input");
range.className = "vis-configuration vis-config-range";
try {
range.type = "range"; // not supported on IE9
range.min = min;
range.max = max;
} catch (err) {
// TODO: Add some error handling.
}
range.step = step;
// set up the popup settings in case they are needed.
let popupString = "";
let popupValue = 0;
if (value !== undefined) {
const factor = 1.2;
if (value < 0 && value * factor < min) {
range.min = Math.ceil(value * factor);
popupValue = range.min;
popupString = "range increased";
} else if (value / factor < min) {
range.min = Math.ceil(value / factor);
popupValue = range.min;
popupString = "range increased";
}
if (value * factor > max && max !== 1) {
range.max = Math.ceil(value * factor);
popupValue = range.max;
popupString = "range increased";
}
range.value = value;
} else {
range.value = defaultValue;
}
const input = document.createElement("input");
input.className = "vis-configuration vis-config-rangeinput";
input.value = range.value;
const me = this;
range.onchange = function () {
input.value = this.value;
me._update(Number(this.value), path);
};
range.oninput = function () {
input.value = this.value;
};
const label = this._makeLabel(path[path.length - 1], path);
const itemIndex = this._makeItem(path, label, range, input);
// if a popup is needed AND it has not been shown for this value, show it.
if (popupString !== "" && this.popupHistory[itemIndex] !== popupValue) {
this.popupHistory[itemIndex] = popupValue;
this._setupPopup(popupString, itemIndex);
}
}
/**
* make a button object
*
* @private
*/
_makeButton() {
if (this.options.showButton === true) {
const generateButton = document.createElement("div");
generateButton.className = "vis-configuration vis-config-button";
generateButton.innerText = "generate options";
generateButton.onclick = () => {
this._printOptions();
};
generateButton.onmouseover = () => {
generateButton.className = "vis-configuration vis-config-button hover";
};
generateButton.onmouseout = () => {
generateButton.className = "vis-configuration vis-config-button";
};
this.optionsContainer = document.createElement("div");
this.optionsContainer.className = "vis-configuration vis-config-option-container";
this.domElements.push(this.optionsContainer);
this.domElements.push(generateButton);
}
}
/**
* prepare the popup
*
* @param {string} string
* @param {number} index
* @private
*/
_setupPopup(string, index) {
if (this.initialized === true && this.allowCreation === true && this.popupCounter < this.popupLimit) {
const div = document.createElement("div");
div.id = "vis-configuration-popup";
div.className = "vis-configuration-popup";
div.innerText = string;
div.onclick = () => {
this._removePopup();
};
this.popupCounter += 1;
this.popupDiv = {
html: div,
index: index
};
}
}
/**
* remove the popup from the dom
*
* @private
*/
_removePopup() {
if (this.popupDiv.html !== undefined) {
this.popupDiv.html.parentNode.removeChild(this.popupDiv.html);
clearTimeout(this.popupDiv.hideTimeout);
clearTimeout(this.popupDiv.deleteTimeout);
this.popupDiv = {};
}
}
/**
* Show the popup if it is needed.
*
* @private
*/
_showPopupIfNeeded() {
if (this.popupDiv.html !== undefined) {
const correspondingElement = this.domElements[this.popupDiv.index];
const rect = correspondingElement.getBoundingClientRect();
this.popupDiv.html.style.left = rect.left + "px";
this.popupDiv.html.style.top = rect.top - 30 + "px"; // 30 is the height;
document.body.appendChild(this.popupDiv.html);
this.popupDiv.hideTimeout = setTimeout(() => {
this.popupDiv.html.style.opacity = 0;
}, 1500);
this.popupDiv.deleteTimeout = setTimeout(() => {
this._removePopup();
}, 1800);
}
}
/**
* make a checkbox for boolean options.
*
* @param {number} defaultValue
* @param {number} value
* @param {Array} path | where to look for the actual option
* @private
*/
_makeCheckbox(defaultValue, value, path) {
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "vis-configuration vis-config-checkbox";
checkbox.checked = defaultValue;
if (value !== undefined) {
checkbox.checked = value;
if (value !== defaultValue) {
if (typeof defaultValue === "object") {
if (value !== defaultValue.enabled) {
this.changedOptions.push({
path: path,
value: value
});
}
} else {
this.changedOptions.push({
path: path,
value: value
});
}
}
}
const me = this;
checkbox.onchange = function () {
me._update(this.checked, path);
};
const label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, checkbox);
}
/**
* make a text input field for string options.
*
* @param {number} defaultValue
* @param {number} value
* @param {Array} path | where to look for the actual option
* @private
*/
_makeTextInput(defaultValue, value, path) {
const checkbox = document.createElement("input");
checkbox.type = "text";
checkbox.className = "vis-configuration vis-config-text";
checkbox.value = value;
if (value !== defaultValue) {
this.changedOptions.push({
path: path,
value: value
});
}
const me = this;
checkbox.onchange = function () {
me._update(this.value, path);
};
const label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, checkbox);
}
/**
* make a color field with a color picker for color fields
*
* @param {Array.<number>} arr
* @param {number} value
* @param {Array} path | where to look for the actual option
* @private
*/
_makeColorField(arr, value, path) {
const defaultColor = arr[1];
const div = document.createElement("div");
value = value === undefined ? defaultColor : value;
if (value !== "none") {
div.className = "vis-configuration vis-config-colorBlock";
div.style.backgroundColor = value;
} else {
div.className = "vis-configuration vis-config-colorBlock none";
}
value = value === undefined ? defaultColor : value;
div.onclick = () => {
this._showColorPicker(value, div, path);
};
const label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, div);
}
/**
* used by the color buttons to call the color picker.
*
* @param {number} value
* @param {HTMLElement} div
* @param {Array} path | where to look for the actual option
* @private
*/
_showColorPicker(value, div, path) {
// clear the callback from this div
div.onclick = function () {};
this.colorPicker.insertTo(div);
this.colorPicker.show();
this.colorPicker.setColor(value);
this.colorPicker.setUpdateCallback(color => {
const colorString = "rgba(" + color.r + "," + color.g + "," + color.b + "," + color.a + ")";
div.style.backgroundColor = colorString;
this._update(colorString, path);
});
// on close of the colorpicker, restore the callback.
this.colorPicker.setCloseCallback(() => {
div.onclick = () => {
this._showColorPicker(value, div, path);
};
});
}
/**
* parse an object and draw the correct items
*
* @param {object} obj
* @param {Array} [path=[]] | where to look for the actual option
* @param {boolean} [checkOnly=false]
* @returns {boolean}
* @private
*/
_handleObject(obj, path = [], checkOnly = false) {
let show = false;
const filter = this.options.filter;
let visibleInSet = false;
for (const subObj in obj) {
if (Object.prototype.hasOwnProperty.call(obj, subObj)) {
show = true;
const item = obj[subObj];
const newPath = copyAndExtendArray(path, subObj);
if (typeof filter === "function") {
show = filter(subObj, path);
// if needed we must go deeper into the object.
if (show === false) {
if (!Array.isArray(item) && typeof item !== "string" && typeof item !== "boolean" && item instanceof Object) {
this.allowCreation = false;
show = this._handleObject(item, newPath, true);
this.allowCreation = checkOnly === false;
}
}
}
if (show !== false) {
visibleInSet = true;
const value = this._getValue(newPath);
if (Array.isArray(item)) {
this._handleArray(item, value, newPath);
} else if (typeof item === "string") {
this._makeTextInput(item, value, newPath);
} else if (typeof item === "boolean") {
this._makeCheckbox(item, value, newPath);
} else if (item instanceof Object) {
// skip the options that are not enabled
if (!this.hideOption(path, subObj, this.moduleOptions)) {
// initially collapse options with an disabled enabled option.
if (item.enabled !== undefined) {
const enabledPath = copyAndExtendArray(newPath, "enabled");
const enabledValue = this._getValue(enabledPath);
if (enabledValue === true) {
const label = this._makeLabel(subObj, newPath, true);
this._makeItem(newPath, label);
visibleInSet = this._handleObject(item, newPath) || visibleInSet;
} else {
this._makeCheckbox(item, enabledValue, newPath);
}
} else {
const label = this._makeLabel(subObj, newPath, true);
this._makeItem(newPath, label);
visibleInSet = this._handleObject(item, newPath) || visibleInSet;
}
}
} else {
console.error("dont know how to handle", item, subObj, newPath);
}
}
}
}
return visibleInSet;
}
/**
* handle the array type of option
*
* @param {Array.<number>} arr
* @param {number} value
* @param {Array} path | where to look for the actual option
* @private
*/
_handleArray(arr, value, path) {
if (typeof arr[0] === "string" && arr[0] === "color") {
this._makeColorField(arr, value, path);
if (arr[1] !== value) {
this.changedOptions.push({
path: path,
value: value
});
}
} else if (typeof arr[0] === "string") {
this._makeDropdown(arr, value, path);
if (arr[0] !== value) {
this.changedOptions.push({
path: path,
value: value
});
}
} else if (typeof arr[0] === "number") {
this._makeRange(arr, value, path);
if (arr[0] !== value) {
this.changedOptions.push({
path: path,
value: Number(value)
});
}
}
}
/**
* called to update the network with the new settings.
*
* @param {number} value
* @param {Array} path | where to look for the actual option
* @private
*/
_update(value, path) {
const options = this._constructOptions(value, path);
if (this.parent.body && this.parent.body.emitter && this.parent.body.emitter.emit) {
this.parent.body.emitter.emit("configChange", options);
}
this.initialized = true;
this.parent.setOptions(options);
}
/**
*
* @param {string | boolean} value
* @param {Array.<string>} path
* @param {{}} optionsObj
* @returns {{}}
* @private
*/
_constructOptions(value, path, optionsObj = {}) {
let pointer = optionsObj;
// when dropdown boxes can be string or boolean, we typecast it into correct types
value = value === "true" ? true : value;
value = value === "false" ? false : value;
for (let i = 0; i < path.length; i++) {
if (path[i] !== "global") {
if (pointer[path[i]] === undefined) {
pointer[path[i]] = {};
}
if (i !== path.length - 1) {
pointer = pointer[path[i]];
} else {
pointer[path[i]] = value;
}
}
}
return optionsObj;
}
/**
* @private
*/
_printOptions() {
const options = this.getOptions();
while (this.optionsContainer.firstChild) {
this.optionsContainer.removeChild(this.optionsContainer.firstChild);
}
this.optionsContainer.appendChild(wrapInTag("pre", "const options = " + JSON.stringify(options, null, 2)));
}
/**
*
* @returns {{}} options
*/
getOptions() {
const options = {};
for (let i = 0; i < this.changedOptions.length; i++) {
this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options);
}
return options;
}
};
/**
* Popup is a class to create a popup window with some text
*/
let Popup$1 = class Popup {
/**
* @param {Element} container The container object.
* @param {string} overflowMethod How the popup should act to overflowing ('flip' or 'cap')
*/
constructor(container, overflowMethod) {
this.container = container;
this.overflowMethod = overflowMethod || "cap";
this.x = 0;
this.y = 0;
this.padding = 5;
this.hidden = false;
// create the frame
this.frame = document.createElement("div");
this.frame.className = "vis-tooltip";
this.container.appendChild(this.frame);
}
/**
* @param {number} x Horizontal position of the popup window
* @param {number} y Vertical position of the popup window
*/
setPosition(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
}
/**
* Set the content for the popup window. This can be HTML code or text.
*
* @param {string | Element} content
*/
setText(content) {
if (content instanceof Element) {
while (this.frame.firstChild) {
this.frame.removeChild(this.frame.firstChild);
}
this.frame.appendChild(content);
} else {
// String containing literal text, element has to be used for HTML due to
// XSS risks associated with innerHTML (i.e. prevent XSS by accident).
this.frame.innerText = content;
}
}
/**
* Show the popup window
*
* @param {boolean} [doShow] Show or hide the window
*/
show(doShow) {
if (doShow === undefined) {
doShow = true;
}
if (doShow === true) {
const height = this.frame.clientHeight;
const width = this.frame.clientWidth;
const maxHeight = this.frame.parentNode.clientHeight;
const maxWidth = this.frame.parentNode.clientWidth;
let left = 0,
top = 0;
if (this.overflowMethod == "flip") {
let isLeft = false,
isTop = true; // Where around the position it's located
if (this.y - height < this.padding) {
isTop = false;
}
if (this.x + width > maxWidth - this.padding) {
isLeft = true;
}
if (isLeft) {
left = this.x - width;
} else {
left = this.x;
}
if (isTop) {
top = this.y - height;
} else {
top = this.y;
}
} else {
top = this.y - height;
if (top + height + this.padding > maxHeight) {
top = maxHeight - height - this.padding;
}
if (top < this.padding) {
top = this.padding;
}
left = this.x;
if (left + width + this.padding > maxWidth) {
left = maxWidth - width - this.padding;
}
if (left < this.padding) {
left = this.padding;
}
}
this.frame.style.left = left + "px";
this.frame.style.top = top + "px";
this.frame.style.visibility = "visible";
this.hidden = false;
} else {
this.hide();
}
}
/**
* Hide the popup window
*/
hide() {
this.hidden = true;
this.frame.style.left = "0";
this.frame.style.top = "0";
this.frame.style.visibility = "hidden";
}
/**
* Remove the popup window
*/
destroy() {
this.frame.parentNode.removeChild(this.frame); // Remove element from DOM
}
};
let errorFound$1 = false;
let allOptions$4;
const VALIDATOR_PRINT_STYLE$1 = "background: #FFeeee; color: #dd0000";
/**
* Used to validate options.
*/
let Validator$1 = class Validator {
/**
* Main function to be called
*
* @param {object} options
* @param {object} referenceOptions
* @param {object} subObject
* @returns {boolean}
* @static
*/
static validate(options, referenceOptions, subObject) {
errorFound$1 = false;
allOptions$4 = referenceOptions;
let usedOptions = referenceOptions;
if (subObject !== undefined) {
usedOptions = referenceOptions[subObject];
}
Validator.parse(options, usedOptions, []);
return errorFound$1;
}
/**
* Will traverse an object recursively and check every value
*
* @param {object} options
* @param {object} referenceOptions
* @param {Array} path | where to look for the actual option
* @static
*/
static parse(options, referenceOptions, path) {
for (const option in options) {
if (Object.prototype.hasOwnProperty.call(options, option)) {
Validator.check(option, options, referenceOptions, path);
}
}
}
/**
* Check every value. If the value is an object, call the parse function on that object.
*
* @param {string} option
* @param {object} options
* @param {object} referenceOptions
* @param {Array} path | where to look for the actual option
* @static
*/
static check(option, options, referenceOptions, path) {
if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) {
Validator.getSuggestion(option, referenceOptions, path);
return;
}
let referenceOption = option;
let is_object = true;
if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) {
// NOTE: This only triggers if the __any__ is in the top level of the options object.
// THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
// TODO: Examine if needed, remove if possible
// __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
referenceOption = "__any__";
// if the any-subgroup is not a predefined object in the configurator,
// we do not look deeper into the object.
is_object = Validator.getType(options[option]) === "object";
}
let refOptionObj = referenceOptions[referenceOption];
if (is_object && refOptionObj.__type__ !== undefined) {
refOptionObj = refOptionObj.__type__;
}
Validator.checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path);
}
/**
*
* @param {string} option | the option property
* @param {object} options | The supplied options object
* @param {object} referenceOptions | The reference options containing all options and their allowed formats
* @param {string} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
* @param {string} refOptionObj | This is the type object from the reference options
* @param {Array} path | where in the object is the option
* @static
*/
static checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) {
const log = function (message) {
console.error("%c" + message + Validator.printLocation(path, option), VALIDATOR_PRINT_STYLE$1);
};
const optionType = Validator.getType(options[option]);
const refOptionType = refOptionObj[optionType];
if (refOptionType !== undefined) {
// if the type is correct, we check if it is supposed to be one of a few select values
if (Validator.getType(refOptionType) === "array" && refOptionType.indexOf(options[option]) === -1) {
log('Invalid option detected in "' + option + '".' + " Allowed values are:" + Validator.print(refOptionType) + ' not "' + options[option] + '". ');
errorFound$1 = true;
} else if (optionType === "object" && referenceOption !== "__any__") {
path = copyAndExtendArray(path, option);
Validator.parse(options[option], referenceOptions[referenceOption], path);
}
} else if (refOptionObj["any"] === undefined) {
// type of the field is incorrect and the field cannot be any
log('Invalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + ". Received [" + optionType + '] "' + options[option] + '"');
errorFound$1 = true;
}
}
/**
*
* @param {object | boolean | number | string | Array.<number> | Date | Node | Moment | undefined | null} object
* @returns {string}
* @static
*/
static getType(object) {
const type = typeof object;
if (type === "object") {
if (object === null) {
return "null";
}
if (object instanceof Boolean) {
return "boolean";
}
if (object instanceof Number) {
return "number";
}
if (object instanceof String) {
return "string";
}
if (Array.isArray(object)) {
return "array";
}
if (object instanceof Date) {
return "date";
}
if (object.nodeType !== undefined) {
return "dom";
}
if (object._isAMomentObject === true) {
return "moment";
}
return "object";
} else if (type === "number") {
return "number";
} else if (type === "boolean") {
return "boolean";
} else if (type === "string") {
return "string";
} else if (type === undefined) {
return "undefined";
}
return type;
}
/**
* @param {string} option
* @param {object} options
* @param {Array.<string>} path
* @static
*/
static getSuggestion(option, options, path) {
const localSearch = Validator.findInOptions(option, options, path, false);
const globalSearch = Validator.findInOptions(option, allOptions$4, [], true);
const localSearchThreshold = 8;
const globalSearchThreshold = 4;
let msg;
if (localSearch.indexMatch !== undefined) {
msg = " in " + Validator.printLocation(localSearch.path, option, "") + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n';
} else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) {
msg = " in " + Validator.printLocation(localSearch.path, option, "") + "Perhaps it was misplaced? Matching option found at: " + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, "");
} else if (localSearch.distance <= localSearchThreshold) {
msg = '. Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option);
} else {
msg = ". Did you mean one of these: " + Validator.print(Object.keys(options)) + Validator.printLocation(path, option);
}
console.error('%cUnknown option detected: "' + option + '"' + msg, VALIDATOR_PRINT_STYLE$1);
errorFound$1 = true;
}
/**
* traverse the options in search for a match.
*
* @param {string} option
* @param {object} options
* @param {Array} path | where to look for the actual option
* @param {boolean} [recursive=false]
* @returns {{closestMatch: string, path: Array, distance: number}}
* @static
*/
static findInOptions(option, options, path, recursive = false) {
let min = 1e9;
let closestMatch = "";
let closestMatchPath = [];
const lowerCaseOption = option.toLowerCase();
let indexMatch = undefined;
for (const op in options) {
let distance;
if (options[op].__type__ !== undefined && recursive === true) {
const result = Validator.findInOptions(option, options[op], copyAndExtendArray(path, op));
if (min > result.distance) {
closestMatch = result.closestMatch;
closestMatchPath = result.path;
min = result.distance;
indexMatch = result.indexMatch;
}
} else {
if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
indexMatch = op;
}
distance = Validator.levenshteinDistance(option, op);
if (min > distance) {
closestMatch = op;
closestMatchPath = copyArray(path);
min = distance;
}
}
}
return {
closestMatch: closestMatch,
path: closestMatchPath,
distance: min,
indexMatch: indexMatch
};
}
/**
* @param {Array.<string>} path
* @param {object} option
* @param {string} prefix
* @returns {string}
* @static
*/
static printLocation(path, option, prefix = "Problem value found at: \n") {
let str = "\n\n" + prefix + "options = {\n";
for (let i = 0; i < path.length; i++) {
for (let j = 0; j < i + 1; j++) {
str += " ";
}
str += path[i] + ": {\n";
}
for (let j = 0; j < path.length + 1; j++) {
str += " ";
}
str += option + "\n";
for (let i = 0; i < path.length + 1; i++) {
for (let j = 0; j < path.length - i; j++) {
str += " ";
}
str += "}\n";
}
return str + "\n\n";
}
/**
* @param {object} options
* @returns {string}
* @static
*/
static print(options) {
return JSON.stringify(options).replace(/(")|(\[)|(\])|(,"__type__")/g, "").replace(/(,)/g, ", ");
}
/**
* Compute the edit distance between the two given strings
* http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
*
* Copyright (c) 2011 Andrei Mackenzie
*
* 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.
*
* @param {string} a
* @param {string} b
* @returns {Array.<Array.<number>>}}
* @static
*/
static levenshteinDistance(a, b) {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
const matrix = [];
// increment along the first column of each row
let i;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
// increment each column in the first row
let j;
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Fill in the rest of the matrix
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) == a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1,
// substitution
Math.min(matrix[i][j - 1] + 1,
// insertion
matrix[i - 1][j] + 1)); // deletion
}
}
}
return matrix[b.length][a.length];
}
};
const Activator$2 = Activator$1;
const ColorPicker$2 = ColorPicker$1;
const Configurator$2 = Configurator$1;
const Hammer$2 = Hammer$1;
const Popup$2 = Popup$1;
const VALIDATOR_PRINT_STYLE = VALIDATOR_PRINT_STYLE$1;
const Validator$2 = Validator$1;
var util$2 = /*#__PURE__*/Object.freeze({
__proto__: null,
Activator: Activator$2,
Alea: Alea,
ColorPicker: ColorPicker$2,
Configurator: Configurator$2,
DELETE: DELETE,
HSVToHex: HSVToHex,
HSVToRGB: HSVToRGB,
Hammer: Hammer$2,
Popup: Popup$2,
RGBToHSV: RGBToHSV,
RGBToHex: RGBToHex,
VALIDATOR_PRINT_STYLE: VALIDATOR_PRINT_STYLE,
Validator: Validator$2,
addClassName: addClassName,
addCssText: addCssText,
binarySearchCustom: binarySearchCustom,
binarySearchValue: binarySearchValue,
bridgeObject: bridgeObject,
copyAndExtendArray: copyAndExtendArray,
copyArray: copyArray,
deepExtend: deepExtend,
deepObjectAssign: deepObjectAssign,
easingFunctions: easingFunctions,
equalArray: equalArray,
extend: extend,
fillIfDefined: fillIfDefined,
forEach: forEach,
getAbsoluteLeft: getAbsoluteLeft,
getAbsoluteRight: getAbsoluteRight,
getAbsoluteTop: getAbsoluteTop,
getScrollBarWidth: getScrollBarWidth,
getTarget: getTarget,
getType: getType,
hasParent: hasParent,
hexToHSV: hexToHSV,
hexToRGB: hexToRGB,
insertSort: insertSort,
isDate: isDate,
isNumber: isNumber,
isObject: isObject,
isString: isString,
isValidHex: isValidHex,
isValidRGB: isValidRGB,
isValidRGBA: isValidRGBA,
mergeOptions: mergeOptions,
option: option,
overrideOpacity: overrideOpacity,
parseColor: parseColor,
preventDefault: preventDefault,
pureDeepObjectAssign: pureDeepObjectAssign,
recursiveDOMDelete: recursiveDOMDelete,
removeClassName: removeClassName,
removeCssText: removeCssText,
selectiveBridgeObject: selectiveBridgeObject,
selectiveDeepExtend: selectiveDeepExtend,
selectiveExtend: selectiveExtend,
selectiveNotDeepExtend: selectiveNotDeepExtend,
throttle: throttle,
toArray: toArray,
topMost: topMost,
updateProperty: updateProperty
});
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
// lazy load so that environments that need to polyfill have a chance to do so
if (!getRandomValues) {
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
}
return getRandomValues(rnds8);
}
var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
function validate(uuid) {
return typeof uuid === 'string' && REGEX.test(uuid);
}
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i$1 = 0; i$1 < 256; ++i$1) {
byteToHex.push((i$1 + 0x100).toString(16).substr(1));
}
function stringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!validate(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
function v4(options, buf, offset) {
options = options || {};
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return stringify(rnds);
}
/**
* vis-data
* http://visjs.org/
*
* Manage unstructured data using DataSet. Add, update, and remove data, and listen for changes in the data.
*
* @version 7.1.9
* @date 2023-11-24T17:53:34.179Z
*
* @copyright (c) 2011-2017 Almende B.V, http://almende.com
* @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
*
* @license
* vis.js is dual licensed under both
*
* 1. The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* 2. The MIT License
* http://opensource.org/licenses/MIT
*
* vis.js may be distributed under either license.
*/
/**
* Create new data pipe.
*
* @param from - The source data set or data view.
* @remarks
* Example usage:
* ```typescript
* interface AppItem {
* whoami: string;
* appData: unknown;
* visData: VisItem;
* }
* interface VisItem {
* id: number;
* label: string;
* color: string;
* x: number;
* y: number;
* }
*
* const ds1 = new DataSet<AppItem, "whoami">([], { fieldId: "whoami" });
* const ds2 = new DataSet<VisItem, "id">();
*
* const pipe = createNewDataPipeFrom(ds1)
* .filter((item): boolean => item.enabled === true)
* .map<VisItem, "id">((item): VisItem => item.visData)
* .to(ds2);
*
* pipe.start();
* ```
* @returns A factory whose methods can be used to configure the pipe.
*/
function createNewDataPipeFrom(from) {
return new DataPipeUnderConstruction(from);
}
/**
* Internal implementation of the pipe. This should be accessible only through
* `createNewDataPipeFrom` from the outside.
*
* @typeParam SI - Source item type.
* @typeParam SP - Source item type's id property name.
* @typeParam TI - Target item type.
* @typeParam TP - Target item type's id property name.
*/
class SimpleDataPipe {
_source;
_transformers;
_target;
/**
* Bound listeners for use with `DataInterface['on' | 'off']`.
*/
_listeners = {
add: this._add.bind(this),
remove: this._remove.bind(this),
update: this._update.bind(this)
};
/**
* Create a new data pipe.
*
* @param _source - The data set or data view that will be observed.
* @param _transformers - An array of transforming functions to be used to
* filter or transform the items in the pipe.
* @param _target - The data set or data view that will receive the items.
*/
constructor(_source, _transformers, _target) {
this._source = _source;
this._transformers = _transformers;
this._target = _target;
}
/** @inheritDoc */
all() {
this._target.update(this._transformItems(this._source.get()));
return this;
}
/** @inheritDoc */
start() {
this._source.on("add", this._listeners.add);
this._source.on("remove", this._listeners.remove);
this._source.on("update", this._listeners.update);
return this;
}
/** @inheritDoc */
stop() {
this._source.off("add", this._listeners.add);
this._source.off("remove", this._listeners.remove);
this._source.off("update", this._listeners.update);
return this;
}
/**
* Apply the transformers to the items.
*
* @param items - The items to be transformed.
* @returns The transformed items.
*/
_transformItems(items) {
return this._transformers.reduce((items, transform) => {
return transform(items);
}, items);
}
/**
* Handle an add event.
*
* @param _name - Ignored.
* @param payload - The payload containing the ids of the added items.
*/
_add(_name, payload) {
if (payload == null) {
return;
}
this._target.add(this._transformItems(this._source.get(payload.items)));
}
/**
* Handle an update event.
*
* @param _name - Ignored.
* @param payload - The payload containing the ids of the updated items.
*/
_update(_name, payload) {
if (payload == null) {
return;
}
this._target.update(this._transformItems(this._source.get(payload.items)));
}
/**
* Handle a remove event.
*
* @param _name - Ignored.
* @param payload - The payload containing the data of the removed items.
*/
_remove(_name, payload) {
if (payload == null) {
return;
}
this._target.remove(this._transformItems(payload.oldData));
}
}
/**
* Internal implementation of the pipe factory. This should be accessible
* only through `createNewDataPipeFrom` from the outside.
*
* @typeParam TI - Target item type.
* @typeParam TP - Target item type's id property name.
*/
class DataPipeUnderConstruction {
_source;
/**
* Array transformers used to transform items within the pipe. This is typed
* as any for the sake of simplicity.
*/
_transformers = [];
/**
* Create a new data pipe factory. This is an internal constructor that
* should never be called from outside of this file.
*
* @param _source - The source data set or data view for this pipe.
*/
constructor(_source) {
this._source = _source;
}
/**
* Filter the items.
*
* @param callback - A filtering function that returns true if given item
* should be piped and false if not.
* @returns This factory for further configuration.
*/
filter(callback) {
this._transformers.push(input => input.filter(callback));
return this;
}
/**
* Map each source item to a new type.
*
* @param callback - A mapping function that takes a source item and returns
* corresponding mapped item.
* @typeParam TI - Target item type.
* @typeParam TP - Target item type's id property name.
* @returns This factory for further configuration.
*/
map(callback) {
this._transformers.push(input => input.map(callback));
return this;
}
/**
* Map each source item to zero or more items of a new type.
*
* @param callback - A mapping function that takes a source item and returns
* an array of corresponding mapped items.
* @typeParam TI - Target item type.
* @typeParam TP - Target item type's id property name.
* @returns This factory for further configuration.
*/
flatMap(callback) {
this._transformers.push(input => input.flatMap(callback));
return this;
}
/**
* Connect this pipe to given data set.
*
* @param target - The data set that will receive the items from this pipe.
* @returns The pipe connected between given data sets and performing
* configured transformation on the processed items.
*/
to(target) {
return new SimpleDataPipe(this._source, this._transformers, target);
}
}
/**
* Determine whether a value can be used as an id.
*
* @param value - Input value of unknown type.
* @returns True if the value is valid id, false otherwise.
*/
function isId(value) {
return typeof value === "string" || typeof value === "number";
}
/**
* A queue.
*
* @typeParam T - The type of method names to be replaced by queued versions.
*/
class Queue {
/** Delay in milliseconds. If defined the queue will be periodically flushed. */
delay;
/** Maximum number of entries in the queue before it will be flushed. */
max;
_queue = [];
_timeout = null;
_extended = null;
/**
* Construct a new Queue.
*
* @param options - Queue configuration.
*/
constructor(options) {
// options
this.delay = null;
this.max = Infinity;
this.setOptions(options);
}
/**
* Update the configuration of the queue.
*
* @param options - Queue configuration.
*/
setOptions(options) {
if (options && typeof options.delay !== "undefined") {
this.delay = options.delay;
}
if (options && typeof options.max !== "undefined") {
this.max = options.max;
}
this._flushIfNeeded();
}
/**
* Extend an object with queuing functionality.
* The object will be extended with a function flush, and the methods provided in options.replace will be replaced with queued ones.
*
* @param object - The object to be extended.
* @param options - Additional options.
* @returns The created queue.
*/
static extend(object, options) {
const queue = new Queue(options);
if (object.flush !== undefined) {
throw new Error("Target object already has a property flush");
}
object.flush = () => {
queue.flush();
};
const methods = [{
name: "flush",
original: undefined
}];
if (options && options.replace) {
for (let i = 0; i < options.replace.length; i++) {
const name = options.replace[i];
methods.push({
name: name,
// @TODO: better solution?
original: object[name]
});
// @TODO: better solution?
queue.replace(object, name);
}
}
queue._extended = {
object: object,
methods: methods
};
return queue;
}
/**
* Destroy the queue. The queue will first flush all queued actions, and in case it has extended an object, will restore the original object.
*/
destroy() {
this.flush();
if (this._extended) {
const object = this._extended.object;
const methods = this._extended.methods;
for (let i = 0; i < methods.length; i++) {
const method = methods[i];
if (method.original) {
// @TODO: better solution?
object[method.name] = method.original;
} else {
// @TODO: better solution?
delete object[method.name];
}
}
this._extended = null;
}
}
/**
* Replace a method on an object with a queued version.
*
* @param object - Object having the method.
* @param method - The method name.
*/
replace(object, method) {
/* eslint-disable-next-line @typescript-eslint/no-this-alias -- Function this is necessary in the function bellow, so class this has to be saved into a variable here. */
const me = this;
const original = object[method];
if (!original) {
throw new Error("Method " + method + " undefined");
}
object[method] = function (...args) {
// add this call to the queue
me.queue({
args: args,
fn: original,
context: this
});
};
}
/**
* Queue a call.
*
* @param entry - The function or entry to be queued.
*/
queue(entry) {
if (typeof entry === "function") {
this._queue.push({
fn: entry
});
} else {
this._queue.push(entry);
}
this._flushIfNeeded();
}
/**
* Check whether the queue needs to be flushed.
*/
_flushIfNeeded() {
// flush when the maximum is exceeded.
if (this._queue.length > this.max) {
this.flush();
}
// flush after a period of inactivity when a delay is configured
if (this._timeout != null) {
clearTimeout(this._timeout);
this._timeout = null;
}
if (this.queue.length > 0 && typeof this.delay === "number") {
this._timeout = setTimeout(() => {
this.flush();
}, this.delay);
}
}
/**
* Flush all queued calls
*/
flush() {
this._queue.splice(0).forEach(entry => {
entry.fn.apply(entry.context || entry.fn, entry.args || []);
});
}
}
/**
* {@link DataSet} code that can be reused in {@link DataView} or other similar implementations of {@link DataInterface}.
*
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
*/
class DataSetPart {
_subscribers = {
"*": [],
add: [],
remove: [],
update: []
};
/**
* Trigger an event
*
* @param event - Event name.
* @param payload - Event payload.
* @param senderId - Id of the sender.
*/
_trigger(event, payload, senderId) {
if (event === "*") {
throw new Error("Cannot trigger event *");
}
[...this._subscribers[event], ...this._subscribers["*"]].forEach(subscriber => {
subscriber(event, payload, senderId != null ? senderId : null);
});
}
/**
* Subscribe to an event, add an event listener.
*
* @remarks Non-function callbacks are ignored.
* @param event - Event name.
* @param callback - Callback method.
*/
on(event, callback) {
if (typeof callback === "function") {
this._subscribers[event].push(callback);
}
// @TODO: Maybe throw for invalid callbacks?
}
/**
* Unsubscribe from an event, remove an event listener.
*
* @remarks If the same callback was subscribed more than once **all** occurences will be removed.
* @param event - Event name.
* @param callback - Callback method.
*/
off(event, callback) {
this._subscribers[event] = this._subscribers[event].filter(subscriber => subscriber !== callback);
}
/**
* @deprecated Use on instead (PS: DataView.subscribe === DataView.on).
*/
subscribe = DataSetPart.prototype.on;
/**
* @deprecated Use off instead (PS: DataView.unsubscribe === DataView.off).
*/
unsubscribe = DataSetPart.prototype.off;
}
/**
* Data stream
*
* @remarks
* {@link DataStream} offers an always up to date stream of items from a {@link DataSet} or {@link DataView}.
* That means that the stream is evaluated at the time of iteration, conversion to another data type or when {@link cache} is called, not when the {@link DataStream} was created.
* Multiple invocations of for example {@link toItemArray} may yield different results (if the data source like for example {@link DataSet} gets modified).
* @typeParam Item - The item type this stream is going to work with.
*/
class DataStream {
_pairs;
/**
* Create a new data stream.
*
* @param pairs - The id, item pairs.
*/
constructor(pairs) {
this._pairs = pairs;
}
/**
* Return an iterable of key, value pairs for every entry in the stream.
*/
*[Symbol.iterator]() {
for (const [id, item] of this._pairs) {
yield [id, item];
}
}
/**
* Return an iterable of key, value pairs for every entry in the stream.
*/
*entries() {
for (const [id, item] of this._pairs) {
yield [id, item];
}
}
/**
* Return an iterable of keys in the stream.
*/
*keys() {
for (const [id] of this._pairs) {
yield id;
}
}
/**
* Return an iterable of values in the stream.
*/
*values() {
for (const [, item] of this._pairs) {
yield item;
}
}
/**
* Return an array containing all the ids in this stream.
*
* @remarks
* The array may contain duplicities.
* @returns The array with all ids from this stream.
*/
toIdArray() {
return [...this._pairs].map(pair => pair[0]);
}
/**
* Return an array containing all the items in this stream.
*
* @remarks
* The array may contain duplicities.
* @returns The array with all items from this stream.
*/
toItemArray() {
return [...this._pairs].map(pair => pair[1]);
}
/**
* Return an array containing all the entries in this stream.
*
* @remarks
* The array may contain duplicities.
* @returns The array with all entries from this stream.
*/
toEntryArray() {
return [...this._pairs];
}
/**
* Return an object map containing all the items in this stream accessible by ids.
*
* @remarks
* In case of duplicate ids (coerced to string so `7 == '7'`) the last encoutered appears in the returned object.
* @returns The object map of all id → item pairs from this stream.
*/
toObjectMap() {
const map = Object.create(null);
for (const [id, item] of this._pairs) {
map[id] = item;
}
return map;
}
/**
* Return a map containing all the items in this stream accessible by ids.
*
* @returns The map of all id → item pairs from this stream.
*/
toMap() {
return new Map(this._pairs);
}
/**
* Return a set containing all the (unique) ids in this stream.
*
* @returns The set of all ids from this stream.
*/
toIdSet() {
return new Set(this.toIdArray());
}
/**
* Return a set containing all the (unique) items in this stream.
*
* @returns The set of all items from this stream.
*/
toItemSet() {
return new Set(this.toItemArray());
}
/**
* Cache the items from this stream.
*
* @remarks
* This method allows for items to be fetched immediatelly and used (possibly multiple times) later.
* It can also be used to optimize performance as {@link DataStream} would otherwise reevaluate everything upon each iteration.
*
* ## Example
* ```javascript
* const ds = new DataSet([…])
*
* const cachedStream = ds.stream()
* .filter(…)
* .sort(…)
* .map(…)
* .cached(…) // Data are fetched, processed and cached here.
*
* ds.clear()
* chachedStream // Still has all the items.
* ```
* @returns A new {@link DataStream} with cached items (detached from the original {@link DataSet}).
*/
cache() {
return new DataStream([...this._pairs]);
}
/**
* Get the distinct values of given property.
*
* @param callback - The function that picks and possibly converts the property.
* @typeParam T - The type of the distinct value.
* @returns A set of all distinct properties.
*/
distinct(callback) {
const set = new Set();
for (const [id, item] of this._pairs) {
set.add(callback(item, id));
}
return set;
}
/**
* Filter the items of the stream.
*
* @param callback - The function that decides whether an item will be included.
* @returns A new data stream with the filtered items.
*/
filter(callback) {
const pairs = this._pairs;
return new DataStream({
*[Symbol.iterator]() {
for (const [id, item] of pairs) {
if (callback(item, id)) {
yield [id, item];
}
}
}
});
}
/**
* Execute a callback for each item of the stream.
*
* @param callback - The function that will be invoked for each item.
*/
forEach(callback) {
for (const [id, item] of this._pairs) {
callback(item, id);
}
}
/**
* Map the items into a different type.
*
* @param callback - The function that does the conversion.
* @typeParam Mapped - The type of the item after mapping.
* @returns A new data stream with the mapped items.
*/
map(callback) {
const pairs = this._pairs;
return new DataStream({
*[Symbol.iterator]() {
for (const [id, item] of pairs) {
yield [id, callback(item, id)];
}
}
});
}
/**
* Get the item with the maximum value of given property.
*
* @param callback - The function that picks and possibly converts the property.
* @returns The item with the maximum if found otherwise null.
*/
max(callback) {
const iter = this._pairs[Symbol.iterator]();
let curr = iter.next();
if (curr.done) {
return null;
}
let maxItem = curr.value[1];
let maxValue = callback(curr.value[1], curr.value[0]);
while (!(curr = iter.next()).done) {
const [id, item] = curr.value;
const value = callback(item, id);
if (value > maxValue) {
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
/**
* Get the item with the minimum value of given property.
*
* @param callback - The function that picks and possibly converts the property.
* @returns The item with the minimum if found otherwise null.
*/
min(callback) {
const iter = this._pairs[Symbol.iterator]();
let curr = iter.next();
if (curr.done) {
return null;
}
let minItem = curr.value[1];
let minValue = callback(curr.value[1], curr.value[0]);
while (!(curr = iter.next()).done) {
const [id, item] = curr.value;
const value = callback(item, id);
if (value < minValue) {
minValue = value;
minItem = item;
}
}
return minItem;
}
/**
* Reduce the items into a single value.
*
* @param callback - The function that does the reduction.
* @param accumulator - The initial value of the accumulator.
* @typeParam T - The type of the accumulated value.
* @returns The reduced value.
*/
reduce(callback, accumulator) {
for (const [id, item] of this._pairs) {
accumulator = callback(accumulator, item, id);
}
return accumulator;
}
/**
* Sort the items.
*
* @param callback - Item comparator.
* @returns A new stream with sorted items.
*/
sort(callback) {
return new DataStream({
[Symbol.iterator]: () => [...this._pairs].sort(([idA, itemA], [idB, itemB]) => callback(itemA, itemB, idA, idB))[Symbol.iterator]()
});
}
}
/**
* Add an id to given item if it doesn't have one already.
*
* @remarks
* The item will be modified.
* @param item - The item that will have an id after a call to this function.
* @param idProp - The key of the id property.
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
* @returns true
*/
function ensureFullItem(item, idProp) {
if (item[idProp] == null) {
// generate an id
item[idProp] = v4();
}
return item;
}
/**
* # DataSet
*
* Vis.js comes with a flexible DataSet, which can be used to hold and
* manipulate unstructured data and listen for changes in the data. The DataSet
* is key/value based. Data items can be added, updated and removed from the
* DataSet, and one can subscribe to changes in the DataSet. The data in the
* DataSet can be filtered and ordered. Data can be normalized when appending it
* to the DataSet as well.
*
* ## Example
*
* The following example shows how to use a DataSet.
*
* ```javascript
* // create a DataSet
* var options = {};
* var data = new vis.DataSet(options);
*
* // add items
* // note that the data items can contain different properties and data formats
* data.add([
* {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
* {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
* {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
* {id: 4, text: 'item 4'}
* ]);
*
* // subscribe to any change in the DataSet
* data.on('*', function (event, properties, senderId) {
* console.log('event', event, properties);
* });
*
* // update an existing item
* data.update({id: 2, group: 1});
*
* // remove an item
* data.remove(4);
*
* // get all ids
* var ids = data.getIds();
* console.log('ids', ids);
*
* // get a specific item
* var item1 = data.get(1);
* console.log('item1', item1);
*
* // retrieve a filtered subset of the data
* var items = data.get({
* filter: function (item) {
* return item.group == 1;
* }
* });
* console.log('filtered items', items);
* ```
*
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
*/
class DataSet extends DataSetPart {
/** Flush all queued calls. */
flush;
/** @inheritDoc */
length;
/** @inheritDoc */
get idProp() {
return this._idProp;
}
_options;
_data;
_idProp;
_queue = null;
/**
* Construct a new DataSet.
*
* @param data - Initial data or options.
* @param options - Options (type error if data is also options).
*/
constructor(data, options) {
super();
// correctly read optional arguments
if (data && !Array.isArray(data)) {
options = data;
data = [];
}
this._options = options || {};
this._data = new Map(); // map with data indexed by id
this.length = 0; // number of items in the DataSet
this._idProp = this._options.fieldId || "id"; // name of the field containing id
// add initial data when provided
if (data && data.length) {
this.add(data);
}
this.setOptions(options);
}
/**
* Set new options.
*
* @param options - The new options.
*/
setOptions(options) {
if (options && options.queue !== undefined) {
if (options.queue === false) {
// delete queue if loaded
if (this._queue) {
this._queue.destroy();
this._queue = null;
}
} else {
// create queue and update its options
if (!this._queue) {
this._queue = Queue.extend(this, {
replace: ["add", "update", "remove"]
});
}
if (options.queue && typeof options.queue === "object") {
this._queue.setOptions(options.queue);
}
}
}
}
/**
* Add a data item or an array with items.
*
* After the items are added to the DataSet, the DataSet will trigger an event `add`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
*
* ```javascript
* // create a DataSet
* const data = new vis.DataSet()
*
* // add items
* const ids = data.add([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { text: 'item without an id' }
* ])
*
* console.log(ids) // [1, 2, '<UUIDv4>']
* ```
*
* @param data - Items to be added (ids will be generated if missing).
* @param senderId - Sender id.
* @returns addedIds - Array with the ids (generated if not present) of the added items.
* @throws When an item with the same id as any of the added items already exists.
*/
add(data, senderId) {
const addedIds = [];
let id;
if (Array.isArray(data)) {
// Array
const idsToAdd = data.map(d => d[this._idProp]);
if (idsToAdd.some(id => this._data.has(id))) {
throw new Error("A duplicate id was found in the parameter array.");
}
for (let i = 0, len = data.length; i < len; i++) {
id = this._addItem(data[i]);
addedIds.push(id);
}
} else if (data && typeof data === "object") {
// Single item
id = this._addItem(data);
addedIds.push(id);
} else {
throw new Error("Unknown dataType");
}
if (addedIds.length) {
this._trigger("add", {
items: addedIds
}, senderId);
}
return addedIds;
}
/**
* Update existing items. When an item does not exist, it will be created.
*
* @remarks
* The provided properties will be merged in the existing item. When an item does not exist, it will be created.
*
* After the items are updated, the DataSet will trigger an event `add` for the added items, and an event `update`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
*
* ```javascript
* // create a DataSet
* const data = new vis.DataSet([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { id: 3, text: 'item 3' }
* ])
*
* // update items
* const ids = data.update([
* { id: 2, text: 'item 2 (updated)' },
* { id: 4, text: 'item 4 (new)' }
* ])
*
* console.log(ids) // [2, 4]
* ```
*
* ## Warning for TypeScript users
* This method may introduce partial items into the data set. Use add or updateOnly instead for better type safety.
* @param data - Items to be updated (if the id is already present) or added (if the id is missing).
* @param senderId - Sender id.
* @returns updatedIds - The ids of the added (these may be newly generated if there was no id in the item from the data) or updated items.
* @throws When the supplied data is neither an item nor an array of items.
*/
update(data, senderId) {
const addedIds = [];
const updatedIds = [];
const oldData = [];
const updatedData = [];
const idProp = this._idProp;
const addOrUpdate = item => {
const origId = item[idProp];
if (origId != null && this._data.has(origId)) {
const fullItem = item; // it has an id, therefore it is a fullitem
const oldItem = Object.assign({}, this._data.get(origId));
// update item
const id = this._updateItem(fullItem);
updatedIds.push(id);
updatedData.push(fullItem);
oldData.push(oldItem);
} else {
// add new item
const id = this._addItem(item);
addedIds.push(id);
}
};
if (Array.isArray(data)) {
// Array
for (let i = 0, len = data.length; i < len; i++) {
if (data[i] && typeof data[i] === "object") {
addOrUpdate(data[i]);
} else {
console.warn("Ignoring input item, which is not an object at index " + i);
}
}
} else if (data && typeof data === "object") {
// Single item
addOrUpdate(data);
} else {
throw new Error("Unknown dataType");
}
if (addedIds.length) {
this._trigger("add", {
items: addedIds
}, senderId);
}
if (updatedIds.length) {
const props = {
items: updatedIds,
oldData: oldData,
data: updatedData
};
// TODO: remove deprecated property 'data' some day
//Object.defineProperty(props, 'data', {
// 'get': (function() {
// console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
// return updatedData;
// }).bind(this)
//});
this._trigger("update", props, senderId);
}
return addedIds.concat(updatedIds);
}
/**
* Update existing items. When an item does not exist, an error will be thrown.
*
* @remarks
* The provided properties will be deeply merged into the existing item.
* When an item does not exist (id not present in the data set or absent), an error will be thrown and nothing will be changed.
*
* After the items are updated, the DataSet will trigger an event `update`.
* When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
*
* ```javascript
* // create a DataSet
* const data = new vis.DataSet([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { id: 3, text: 'item 3' },
* ])
*
* // update items
* const ids = data.update([
* { id: 2, text: 'item 2 (updated)' }, // works
* // { id: 4, text: 'item 4 (new)' }, // would throw
* // { text: 'item 4 (new)' }, // would also throw
* ])
*
* console.log(ids) // [2]
* ```
* @param data - Updates (the id and optionally other props) to the items in this data set.
* @param senderId - Sender id.
* @returns updatedIds - The ids of the updated items.
* @throws When the supplied data is neither an item nor an array of items, when the ids are missing.
*/
updateOnly(data, senderId) {
if (!Array.isArray(data)) {
data = [data];
}
const updateEventData = data.map(update => {
const oldData = this._data.get(update[this._idProp]);
if (oldData == null) {
throw new Error("Updating non-existent items is not allowed.");
}
return {
oldData,
update
};
}).map(({
oldData,
update
}) => {
const id = oldData[this._idProp];
const updatedData = pureDeepObjectAssign(oldData, update);
this._data.set(id, updatedData);
return {
id,
oldData: oldData,
updatedData
};
});
if (updateEventData.length) {
const props = {
items: updateEventData.map(value => value.id),
oldData: updateEventData.map(value => value.oldData),
data: updateEventData.map(value => value.updatedData)
};
// TODO: remove deprecated property 'data' some day
//Object.defineProperty(props, 'data', {
// 'get': (function() {
// console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
// return updatedData;
// }).bind(this)
//});
this._trigger("update", props, senderId);
return props.items;
} else {
return [];
}
}
/** @inheritDoc */
get(first, second) {
// @TODO: Woudn't it be better to split this into multiple methods?
// parse the arguments
let id = undefined;
let ids = undefined;
let options = undefined;
if (isId(first)) {
// get(id [, options])
id = first;
options = second;
} else if (Array.isArray(first)) {
// get(ids [, options])
ids = first;
options = second;
} else {
// get([, options])
options = first;
}
// determine the return type
const returnType = options && options.returnType === "Object" ? "Object" : "Array";
// @TODO: WTF is this? Or am I missing something?
// var returnType
// if (options && options.returnType) {
// var allowedValues = ['Array', 'Object']
// returnType =
// allowedValues.indexOf(options.returnType) == -1
// ? 'Array'
// : options.returnType
// } else {
// returnType = 'Array'
// }
// build options
const filter = options && options.filter;
const items = [];
let item = undefined;
let itemIds = undefined;
let itemId = undefined;
// convert items
if (id != null) {
// return a single item
item = this._data.get(id);
if (item && filter && !filter(item)) {
item = undefined;
}
} else if (ids != null) {
// return a subset of items
for (let i = 0, len = ids.length; i < len; i++) {
item = this._data.get(ids[i]);
if (item != null && (!filter || filter(item))) {
items.push(item);
}
}
} else {
// return all items
itemIds = [...this._data.keys()];
for (let i = 0, len = itemIds.length; i < len; i++) {
itemId = itemIds[i];
item = this._data.get(itemId);
if (item != null && (!filter || filter(item))) {
items.push(item);
}
}
}
// order the results
if (options && options.order && id == undefined) {
this._sort(items, options.order);
}
// filter fields of the items
if (options && options.fields) {
const fields = options.fields;
if (id != undefined && item != null) {
item = this._filterFields(item, fields);
} else {
for (let i = 0, len = items.length; i < len; i++) {
items[i] = this._filterFields(items[i], fields);
}
}
}
// return the results
if (returnType == "Object") {
const result = {};
for (let i = 0, len = items.length; i < len; i++) {
const resultant = items[i];
// @TODO: Shoudn't this be this._fieldId?
// result[resultant.id] = resultant
const id = resultant[this._idProp];
result[id] = resultant;
}
return result;
} else {
if (id != null) {
var _item;
// a single item
return (_item = item) !== null && _item !== void 0 ? _item : null;
} else {
// just return our array
return items;
}
}
}
/** @inheritDoc */
getIds(options) {
const data = this._data;
const filter = options && options.filter;
const order = options && options.order;
const itemIds = [...data.keys()];
const ids = [];
if (filter) {
// get filtered items
if (order) {
// create ordered list
const items = [];
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && filter(item)) {
items.push(item);
}
}
this._sort(items, order);
for (let i = 0, len = items.length; i < len; i++) {
ids.push(items[i][this._idProp]);
}
} else {
// create unordered list
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && filter(item)) {
ids.push(item[this._idProp]);
}
}
}
} else {
// get all items
if (order) {
// create an ordered list
const items = [];
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
items.push(data.get(id));
}
this._sort(items, order);
for (let i = 0, len = items.length; i < len; i++) {
ids.push(items[i][this._idProp]);
}
} else {
// create unordered list
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = data.get(id);
if (item != null) {
ids.push(item[this._idProp]);
}
}
}
}
return ids;
}
/** @inheritDoc */
getDataSet() {
return this;
}
/** @inheritDoc */
forEach(callback, options) {
const filter = options && options.filter;
const data = this._data;
const itemIds = [...data.keys()];
if (options && options.order) {
// execute forEach on ordered list
const items = this.get(options);
for (let i = 0, len = items.length; i < len; i++) {
const item = items[i];
const id = item[this._idProp];
callback(item, id);
}
} else {
// unordered
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && (!filter || filter(item))) {
callback(item, id);
}
}
}
}
/** @inheritDoc */
map(callback, options) {
const filter = options && options.filter;
const mappedItems = [];
const data = this._data;
const itemIds = [...data.keys()];
// convert and filter items
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && (!filter || filter(item))) {
mappedItems.push(callback(item, id));
}
}
// order items
if (options && options.order) {
this._sort(mappedItems, options.order);
}
return mappedItems;
}
/**
* Filter the fields of an item.
*
* @param item - The item whose fields should be filtered.
* @param fields - The names of the fields that will be kept.
* @typeParam K - Field name type.
* @returns The item without any additional fields.
*/
_filterFields(item, fields) {
if (!item) {
// item is null
return item;
}
return (Array.isArray(fields) ?
// Use the supplied array
fields :
// Use the keys of the supplied object
Object.keys(fields)).reduce((filteredItem, field) => {
filteredItem[field] = item[field];
return filteredItem;
}, {});
}
/**
* Sort the provided array with items.
*
* @param items - Items to be sorted in place.
* @param order - A field name or custom sort function.
* @typeParam T - The type of the items in the items array.
*/
_sort(items, order) {
if (typeof order === "string") {
// order by provided field name
const name = order; // field name
items.sort((a, b) => {
// @TODO: How to treat missing properties?
const av = a[name];
const bv = b[name];
return av > bv ? 1 : av < bv ? -1 : 0;
});
} else if (typeof order === "function") {
// order by sort function
items.sort(order);
} else {
// TODO: extend order by an Object {field:string, direction:string}
// where direction can be 'asc' or 'desc'
throw new TypeError("Order must be a function or a string");
}
}
/**
* Remove an item or multiple items by “reference” (only the id is used) or by id.
*
* The method ignores removal of non-existing items, and returns an array containing the ids of the items which are actually removed from the DataSet.
*
* After the items are removed, the DataSet will trigger an event `remove` for the removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
* ```javascript
* // create a DataSet
* const data = new vis.DataSet([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { id: 3, text: 'item 3' }
* ])
*
* // remove items
* const ids = data.remove([2, { id: 3 }, 4])
*
* console.log(ids) // [2, 3]
* ```
*
* @param id - One or more items or ids of items to be removed.
* @param senderId - Sender id.
* @returns The ids of the removed items.
*/
remove(id, senderId) {
const removedIds = [];
const removedItems = [];
// force everything to be an array for simplicity
const ids = Array.isArray(id) ? id : [id];
for (let i = 0, len = ids.length; i < len; i++) {
const item = this._remove(ids[i]);
if (item) {
const itemId = item[this._idProp];
if (itemId != null) {
removedIds.push(itemId);
removedItems.push(item);
}
}
}
if (removedIds.length) {
this._trigger("remove", {
items: removedIds,
oldData: removedItems
}, senderId);
}
return removedIds;
}
/**
* Remove an item by its id or reference.
*
* @param id - Id of an item or the item itself.
* @returns The removed item if removed, null otherwise.
*/
_remove(id) {
// @TODO: It origianlly returned the item although the docs say id.
// The code expects the item, so probably an error in the docs.
let ident;
// confirm the id to use based on the args type
if (isId(id)) {
ident = id;
} else if (id && typeof id === "object") {
ident = id[this._idProp]; // look for the identifier field using ._idProp
}
// do the removing if the item is found
if (ident != null && this._data.has(ident)) {
const item = this._data.get(ident) || null;
this._data.delete(ident);
--this.length;
return item;
}
return null;
}
/**
* Clear the entire data set.
*
* After the items are removed, the {@link DataSet} will trigger an event `remove` for all removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* @param senderId - Sender id.
* @returns removedIds - The ids of all removed items.
*/
clear(senderId) {
const ids = [...this._data.keys()];
const items = [];
for (let i = 0, len = ids.length; i < len; i++) {
items.push(this._data.get(ids[i]));
}
this._data.clear();
this.length = 0;
this._trigger("remove", {
items: ids,
oldData: items
}, senderId);
return ids;
}
/**
* Find the item with maximum value of a specified field.
*
* @param field - Name of the property that should be searched for max value.
* @returns Item containing max value, or null if no items.
*/
max(field) {
let max = null;
let maxField = null;
for (const item of this._data.values()) {
const itemField = item[field];
if (typeof itemField === "number" && (maxField == null || itemField > maxField)) {
max = item;
maxField = itemField;
}
}
return max || null;
}
/**
* Find the item with minimum value of a specified field.
*
* @param field - Name of the property that should be searched for min value.
* @returns Item containing min value, or null if no items.
*/
min(field) {
let min = null;
let minField = null;
for (const item of this._data.values()) {
const itemField = item[field];
if (typeof itemField === "number" && (minField == null || itemField < minField)) {
min = item;
minField = itemField;
}
}
return min || null;
}
/**
* Find all distinct values of a specified field
*
* @param prop - The property name whose distinct values should be returned.
* @returns Unordered array containing all distinct values. Items without specified property are ignored.
*/
distinct(prop) {
const data = this._data;
const itemIds = [...data.keys()];
const values = [];
let count = 0;
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = data.get(id);
const value = item[prop];
let exists = false;
for (let j = 0; j < count; j++) {
if (values[j] == value) {
exists = true;
break;
}
}
if (!exists && value !== undefined) {
values[count] = value;
count++;
}
}
return values;
}
/**
* Add a single item. Will fail when an item with the same id already exists.
*
* @param item - A new item to be added.
* @returns Added item's id. An id is generated when it is not present in the item.
*/
_addItem(item) {
const fullItem = ensureFullItem(item, this._idProp);
const id = fullItem[this._idProp];
// check whether this id is already taken
if (this._data.has(id)) {
// item already exists
throw new Error("Cannot add item: item with id " + id + " already exists");
}
this._data.set(id, fullItem);
++this.length;
return id;
}
/**
* Update a single item: merge with existing item.
* Will fail when the item has no id, or when there does not exist an item with the same id.
*
* @param update - The new item
* @returns The id of the updated item.
*/
_updateItem(update) {
const id = update[this._idProp];
if (id == null) {
throw new Error("Cannot update item: item has no id (item: " + JSON.stringify(update) + ")");
}
const item = this._data.get(id);
if (!item) {
// item doesn't exist
throw new Error("Cannot update item: no item with id " + id + " found");
}
this._data.set(id, {
...item,
...update
});
return id;
}
/** @inheritDoc */
stream(ids) {
if (ids) {
const data = this._data;
return new DataStream({
*[Symbol.iterator]() {
for (const id of ids) {
const item = data.get(id);
if (item != null) {
yield [id, item];
}
}
}
});
} else {
return new DataStream({
[Symbol.iterator]: this._data.entries.bind(this._data)
});
}
}
}
/**
* DataView
*
* A DataView offers a filtered and/or formatted view on a DataSet. One can subscribe to changes in a DataView, and easily get filtered or formatted data without having to specify filters and field types all the time.
*
* ## Example
* ```javascript
* // create a DataSet
* var data = new vis.DataSet();
* data.add([
* {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
* {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
* {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
* {id: 4, text: 'item 4'}
* ]);
*
* // create a DataView
* // the view will only contain items having a property group with value 1,
* // and will only output fields id, text, and date.
* var view = new vis.DataView(data, {
* filter: function (item) {
* return (item.group == 1);
* },
* fields: ['id', 'text', 'date']
* });
*
* // subscribe to any change in the DataView
* view.on('*', function (event, properties, senderId) {
* console.log('event', event, properties);
* });
*
* // update an item in the data set
* data.update({id: 2, group: 1});
*
* // get all ids in the view
* var ids = view.getIds();
* console.log('ids', ids); // will output [1, 2]
*
* // get all items in the view
* var items = view.get();
* ```
*
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
*/
class DataView extends DataSetPart {
/** @inheritDoc */
length = 0;
/** @inheritDoc */
get idProp() {
return this.getDataSet().idProp;
}
_listener;
_data; // constructor → setData
_ids = new Set(); // ids of the items currently in memory (just contains a boolean true)
_options;
/**
* Create a DataView.
*
* @param data - The instance containing data (directly or indirectly).
* @param options - Options to configure this data view.
*/
constructor(data, options) {
super();
this._options = options || {};
this._listener = this._onEvent.bind(this);
this.setData(data);
}
// TODO: implement a function .config() to dynamically update things like configured filter
// and trigger changes accordingly
/**
* Set a data source for the view.
*
* @param data - The instance containing data (directly or indirectly).
* @remarks
* Note that when the data view is bound to a data set it won't be garbage
* collected unless the data set is too. Use `dataView.setData(null)` or
* `dataView.dispose()` to enable garbage collection before you lose the last
* reference.
*/
setData(data) {
if (this._data) {
// unsubscribe from current dataset
if (this._data.off) {
this._data.off("*", this._listener);
}
// trigger a remove of all items in memory
const ids = this._data.getIds({
filter: this._options.filter
});
const items = this._data.get(ids);
this._ids.clear();
this.length = 0;
this._trigger("remove", {
items: ids,
oldData: items
});
}
if (data != null) {
this._data = data;
// trigger an add of all added items
const ids = this._data.getIds({
filter: this._options.filter
});
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
this._ids.add(id);
}
this.length = ids.length;
this._trigger("add", {
items: ids
});
} else {
this._data = new DataSet();
}
// subscribe to new dataset
if (this._data.on) {
this._data.on("*", this._listener);
}
}
/**
* Refresh the DataView.
* Useful when the DataView has a filter function containing a variable parameter.
*/
refresh() {
const ids = this._data.getIds({
filter: this._options.filter
});
const oldIds = [...this._ids];
const newIds = {};
const addedIds = [];
const removedIds = [];
const removedItems = [];
// check for additions
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
newIds[id] = true;
if (!this._ids.has(id)) {
addedIds.push(id);
this._ids.add(id);
}
}
// check for removals
for (let i = 0, len = oldIds.length; i < len; i++) {
const id = oldIds[i];
const item = this._data.get(id);
if (item == null) {
// @TODO: Investigate.
// Doesn't happen during tests or examples.
// Is it really impossible or could it eventually happen?
// How to handle it if it does? The types guarantee non-nullable items.
console.error("If you see this, report it please.");
} else if (!newIds[id]) {
removedIds.push(id);
removedItems.push(item);
this._ids.delete(id);
}
}
this.length += addedIds.length - removedIds.length;
// trigger events
if (addedIds.length) {
this._trigger("add", {
items: addedIds
});
}
if (removedIds.length) {
this._trigger("remove", {
items: removedIds,
oldData: removedItems
});
}
}
/** @inheritDoc */
get(first, second) {
if (this._data == null) {
return null;
}
// parse the arguments
let ids = null;
let options;
if (isId(first) || Array.isArray(first)) {
ids = first;
options = second;
} else {
options = first;
}
// extend the options with the default options and provided options
const viewOptions = Object.assign({}, this._options, options);
// create a combined filter method when needed
const thisFilter = this._options.filter;
const optionsFilter = options && options.filter;
if (thisFilter && optionsFilter) {
viewOptions.filter = item => {
return thisFilter(item) && optionsFilter(item);
};
}
if (ids == null) {
return this._data.get(viewOptions);
} else {
return this._data.get(ids, viewOptions);
}
}
/** @inheritDoc */
getIds(options) {
if (this._data.length) {
const defaultFilter = this._options.filter;
const optionsFilter = options != null ? options.filter : null;
let filter;
if (optionsFilter) {
if (defaultFilter) {
filter = item => {
return defaultFilter(item) && optionsFilter(item);
};
} else {
filter = optionsFilter;
}
} else {
filter = defaultFilter;
}
return this._data.getIds({
filter: filter,
order: options && options.order
});
} else {
return [];
}
}
/** @inheritDoc */
forEach(callback, options) {
if (this._data) {
const defaultFilter = this._options.filter;
const optionsFilter = options && options.filter;
let filter;
if (optionsFilter) {
if (defaultFilter) {
filter = function (item) {
return defaultFilter(item) && optionsFilter(item);
};
} else {
filter = optionsFilter;
}
} else {
filter = defaultFilter;
}
this._data.forEach(callback, {
filter: filter,
order: options && options.order
});
}
}
/** @inheritDoc */
map(callback, options) {
if (this._data) {
const defaultFilter = this._options.filter;
const optionsFilter = options && options.filter;
let filter;
if (optionsFilter) {
if (defaultFilter) {
filter = item => {
return defaultFilter(item) && optionsFilter(item);
};
} else {
filter = optionsFilter;
}
} else {
filter = defaultFilter;
}
return this._data.map(callback, {
filter: filter,
order: options && options.order
});
} else {
return [];
}
}
/** @inheritDoc */
getDataSet() {
return this._data.getDataSet();
}
/** @inheritDoc */
stream(ids) {
return this._data.stream(ids || {
[Symbol.iterator]: this._ids.keys.bind(this._ids)
});
}
/**
* Render the instance unusable prior to garbage collection.
*
* @remarks
* The intention of this method is to help discover scenarios where the data
* view is being used when the programmer thinks it has been garbage collected
* already. It's stricter version of `dataView.setData(null)`.
*/
dispose() {
var _this$_data;
if ((_this$_data = this._data) !== null && _this$_data !== void 0 && _this$_data.off) {
this._data.off("*", this._listener);
}
const message = "This data view has already been disposed of.";
const replacement = {
get: () => {
throw new Error(message);
},
set: () => {
throw new Error(message);
},
configurable: false
};
for (const key of Reflect.ownKeys(DataView.prototype)) {
Object.defineProperty(this, key, replacement);
}
}
/**
* Event listener. Will propagate all events from the connected data set to the subscribers of the DataView, but will filter the items and only trigger when there are changes in the filtered data set.
*
* @param event - The name of the event.
* @param params - Parameters of the event.
* @param senderId - Id supplied by the sender.
*/
_onEvent(event, params, senderId) {
if (!params || !params.items || !this._data) {
return;
}
const ids = params.items;
const addedIds = [];
const updatedIds = [];
const removedIds = [];
const oldItems = [];
const updatedItems = [];
const removedItems = [];
switch (event) {
case "add":
// filter the ids of the added items
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
const item = this.get(id);
if (item) {
this._ids.add(id);
addedIds.push(id);
}
}
break;
case "update":
// determine the event from the views viewpoint: an updated
// item can be added, updated, or removed from this view.
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
const item = this.get(id);
if (item) {
if (this._ids.has(id)) {
updatedIds.push(id);
updatedItems.push(params.data[i]);
oldItems.push(params.oldData[i]);
} else {
this._ids.add(id);
addedIds.push(id);
}
} else {
if (this._ids.has(id)) {
this._ids.delete(id);
removedIds.push(id);
removedItems.push(params.oldData[i]);
}
}
}
break;
case "remove":
// filter the ids of the removed items
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
if (this._ids.has(id)) {
this._ids.delete(id);
removedIds.push(id);
removedItems.push(params.oldData[i]);
}
}
break;
}
this.length += addedIds.length - removedIds.length;
if (addedIds.length) {
this._trigger("add", {
items: addedIds
}, senderId);
}
if (updatedIds.length) {
this._trigger("update", {
items: updatedIds,
oldData: oldItems,
data: updatedItems
}, senderId);
}
if (removedIds.length) {
this._trigger("remove", {
items: removedIds,
oldData: removedItems
}, senderId);
}
}
}
/**
* Check that given value is compatible with Vis Data Set interface.
*
* @param idProp - The expected property to contain item id.
* @param v - The value to be tested.
* @returns True if all expected values and methods match, false otherwise.
*/
function isDataSetLike(idProp, v) {
return typeof v === "object" && v !== null && idProp === v.idProp && typeof v.add === "function" && typeof v.clear === "function" && typeof v.distinct === "function" && typeof v.forEach === "function" && typeof v.get === "function" && typeof v.getDataSet === "function" && typeof v.getIds === "function" && typeof v.length === "number" && typeof v.map === "function" && typeof v.max === "function" && typeof v.min === "function" && typeof v.off === "function" && typeof v.on === "function" && typeof v.remove === "function" && typeof v.setOptions === "function" && typeof v.stream === "function" && typeof v.update === "function" && typeof v.updateOnly === "function";
}
/**
* Check that given value is compatible with Vis Data View interface.
*
* @param idProp - The expected property to contain item id.
* @param v - The value to be tested.
* @returns True if all expected values and methods match, false otherwise.
*/
function isDataViewLike$1(idProp, v) {
return typeof v === "object" && v !== null && idProp === v.idProp && typeof v.forEach === "function" && typeof v.get === "function" && typeof v.getDataSet === "function" && typeof v.getIds === "function" && typeof v.length === "number" && typeof v.map === "function" && typeof v.off === "function" && typeof v.on === "function" && typeof v.stream === "function" && isDataSetLike(idProp, v.getDataSet());
}
/**
* cssfilter
*
* @author 老雷<leizongmin@gmail.com>
*/
function getDefaultWhiteList$1() {
// 白名单值说明:
// true: 允许该属性
// Function: function (val) { } 返回true表示允许该属性,其他值均表示不允许
// RegExp: regexp.test(val) 返回true表示允许该属性,其他值均表示不允许
// 除上面列出的值外均表示不允许
var whiteList = {};
whiteList['align-content'] = false; // default: auto
whiteList['align-items'] = false; // default: auto
whiteList['align-self'] = false; // default: auto
whiteList['alignment-adjust'] = false; // default: auto
whiteList['alignment-baseline'] = false; // default: baseline
whiteList['all'] = false; // default: depending on individual properties
whiteList['anchor-point'] = false; // default: none
whiteList['animation'] = false; // default: depending on individual properties
whiteList['animation-delay'] = false; // default: 0
whiteList['animation-direction'] = false; // default: normal
whiteList['animation-duration'] = false; // default: 0
whiteList['animation-fill-mode'] = false; // default: none
whiteList['animation-iteration-count'] = false; // default: 1
whiteList['animation-name'] = false; // default: none
whiteList['animation-play-state'] = false; // default: running
whiteList['animation-timing-function'] = false; // default: ease
whiteList['azimuth'] = false; // default: center
whiteList['backface-visibility'] = false; // default: visible
whiteList['background'] = true; // default: depending on individual properties
whiteList['background-attachment'] = true; // default: scroll
whiteList['background-clip'] = true; // default: border-box
whiteList['background-color'] = true; // default: transparent
whiteList['background-image'] = true; // default: none
whiteList['background-origin'] = true; // default: padding-box
whiteList['background-position'] = true; // default: 0% 0%
whiteList['background-repeat'] = true; // default: repeat
whiteList['background-size'] = true; // default: auto
whiteList['baseline-shift'] = false; // default: baseline
whiteList['binding'] = false; // default: none
whiteList['bleed'] = false; // default: 6pt
whiteList['bookmark-label'] = false; // default: content()
whiteList['bookmark-level'] = false; // default: none
whiteList['bookmark-state'] = false; // default: open
whiteList['border'] = true; // default: depending on individual properties
whiteList['border-bottom'] = true; // default: depending on individual properties
whiteList['border-bottom-color'] = true; // default: current color
whiteList['border-bottom-left-radius'] = true; // default: 0
whiteList['border-bottom-right-radius'] = true; // default: 0
whiteList['border-bottom-style'] = true; // default: none
whiteList['border-bottom-width'] = true; // default: medium
whiteList['border-collapse'] = true; // default: separate
whiteList['border-color'] = true; // default: depending on individual properties
whiteList['border-image'] = true; // default: none
whiteList['border-image-outset'] = true; // default: 0
whiteList['border-image-repeat'] = true; // default: stretch
whiteList['border-image-slice'] = true; // default: 100%
whiteList['border-image-source'] = true; // default: none
whiteList['border-image-width'] = true; // default: 1
whiteList['border-left'] = true; // default: depending on individual properties
whiteList['border-left-color'] = true; // default: current color
whiteList['border-left-style'] = true; // default: none
whiteList['border-left-width'] = true; // default: medium
whiteList['border-radius'] = true; // default: 0
whiteList['border-right'] = true; // default: depending on individual properties
whiteList['border-right-color'] = true; // default: current color
whiteList['border-right-style'] = true; // default: none
whiteList['border-right-width'] = true; // default: medium
whiteList['border-spacing'] = true; // default: 0
whiteList['border-style'] = true; // default: depending on individual properties
whiteList['border-top'] = true; // default: depending on individual properties
whiteList['border-top-color'] = true; // default: current color
whiteList['border-top-left-radius'] = true; // default: 0
whiteList['border-top-right-radius'] = true; // default: 0
whiteList['border-top-style'] = true; // default: none
whiteList['border-top-width'] = true; // default: medium
whiteList['border-width'] = true; // default: depending on individual properties
whiteList['bottom'] = false; // default: auto
whiteList['box-decoration-break'] = true; // default: slice
whiteList['box-shadow'] = true; // default: none
whiteList['box-sizing'] = true; // default: content-box
whiteList['box-snap'] = true; // default: none
whiteList['box-suppress'] = true; // default: show
whiteList['break-after'] = true; // default: auto
whiteList['break-before'] = true; // default: auto
whiteList['break-inside'] = true; // default: auto
whiteList['caption-side'] = false; // default: top
whiteList['chains'] = false; // default: none
whiteList['clear'] = true; // default: none
whiteList['clip'] = false; // default: auto
whiteList['clip-path'] = false; // default: none
whiteList['clip-rule'] = false; // default: nonzero
whiteList['color'] = true; // default: implementation dependent
whiteList['color-interpolation-filters'] = true; // default: auto
whiteList['column-count'] = false; // default: auto
whiteList['column-fill'] = false; // default: balance
whiteList['column-gap'] = false; // default: normal
whiteList['column-rule'] = false; // default: depending on individual properties
whiteList['column-rule-color'] = false; // default: current color
whiteList['column-rule-style'] = false; // default: medium
whiteList['column-rule-width'] = false; // default: medium
whiteList['column-span'] = false; // default: none
whiteList['column-width'] = false; // default: auto
whiteList['columns'] = false; // default: depending on individual properties
whiteList['contain'] = false; // default: none
whiteList['content'] = false; // default: normal
whiteList['counter-increment'] = false; // default: none
whiteList['counter-reset'] = false; // default: none
whiteList['counter-set'] = false; // default: none
whiteList['crop'] = false; // default: auto
whiteList['cue'] = false; // default: depending on individual properties
whiteList['cue-after'] = false; // default: none
whiteList['cue-before'] = false; // default: none
whiteList['cursor'] = false; // default: auto
whiteList['direction'] = false; // default: ltr
whiteList['display'] = true; // default: depending on individual properties
whiteList['display-inside'] = true; // default: auto
whiteList['display-list'] = true; // default: none
whiteList['display-outside'] = true; // default: inline-level
whiteList['dominant-baseline'] = false; // default: auto
whiteList['elevation'] = false; // default: level
whiteList['empty-cells'] = false; // default: show
whiteList['filter'] = false; // default: none
whiteList['flex'] = false; // default: depending on individual properties
whiteList['flex-basis'] = false; // default: auto
whiteList['flex-direction'] = false; // default: row
whiteList['flex-flow'] = false; // default: depending on individual properties
whiteList['flex-grow'] = false; // default: 0
whiteList['flex-shrink'] = false; // default: 1
whiteList['flex-wrap'] = false; // default: nowrap
whiteList['float'] = false; // default: none
whiteList['float-offset'] = false; // default: 0 0
whiteList['flood-color'] = false; // default: black
whiteList['flood-opacity'] = false; // default: 1
whiteList['flow-from'] = false; // default: none
whiteList['flow-into'] = false; // default: none
whiteList['font'] = true; // default: depending on individual properties
whiteList['font-family'] = true; // default: implementation dependent
whiteList['font-feature-settings'] = true; // default: normal
whiteList['font-kerning'] = true; // default: auto
whiteList['font-language-override'] = true; // default: normal
whiteList['font-size'] = true; // default: medium
whiteList['font-size-adjust'] = true; // default: none
whiteList['font-stretch'] = true; // default: normal
whiteList['font-style'] = true; // default: normal
whiteList['font-synthesis'] = true; // default: weight style
whiteList['font-variant'] = true; // default: normal
whiteList['font-variant-alternates'] = true; // default: normal
whiteList['font-variant-caps'] = true; // default: normal
whiteList['font-variant-east-asian'] = true; // default: normal
whiteList['font-variant-ligatures'] = true; // default: normal
whiteList['font-variant-numeric'] = true; // default: normal
whiteList['font-variant-position'] = true; // default: normal
whiteList['font-weight'] = true; // default: normal
whiteList['grid'] = false; // default: depending on individual properties
whiteList['grid-area'] = false; // default: depending on individual properties
whiteList['grid-auto-columns'] = false; // default: auto
whiteList['grid-auto-flow'] = false; // default: none
whiteList['grid-auto-rows'] = false; // default: auto
whiteList['grid-column'] = false; // default: depending on individual properties
whiteList['grid-column-end'] = false; // default: auto
whiteList['grid-column-start'] = false; // default: auto
whiteList['grid-row'] = false; // default: depending on individual properties
whiteList['grid-row-end'] = false; // default: auto
whiteList['grid-row-start'] = false; // default: auto
whiteList['grid-template'] = false; // default: depending on individual properties
whiteList['grid-template-areas'] = false; // default: none
whiteList['grid-template-columns'] = false; // default: none
whiteList['grid-template-rows'] = false; // default: none
whiteList['hanging-punctuation'] = false; // default: none
whiteList['height'] = true; // default: auto
whiteList['hyphens'] = false; // default: manual
whiteList['icon'] = false; // default: auto
whiteList['image-orientation'] = false; // default: auto
whiteList['image-resolution'] = false; // default: normal
whiteList['ime-mode'] = false; // default: auto
whiteList['initial-letters'] = false; // default: normal
whiteList['inline-box-align'] = false; // default: last
whiteList['justify-content'] = false; // default: auto
whiteList['justify-items'] = false; // default: auto
whiteList['justify-self'] = false; // default: auto
whiteList['left'] = false; // default: auto
whiteList['letter-spacing'] = true; // default: normal
whiteList['lighting-color'] = true; // default: white
whiteList['line-box-contain'] = false; // default: block inline replaced
whiteList['line-break'] = false; // default: auto
whiteList['line-grid'] = false; // default: match-parent
whiteList['line-height'] = false; // default: normal
whiteList['line-snap'] = false; // default: none
whiteList['line-stacking'] = false; // default: depending on individual properties
whiteList['line-stacking-ruby'] = false; // default: exclude-ruby
whiteList['line-stacking-shift'] = false; // default: consider-shifts
whiteList['line-stacking-strategy'] = false; // default: inline-line-height
whiteList['list-style'] = true; // default: depending on individual properties
whiteList['list-style-image'] = true; // default: none
whiteList['list-style-position'] = true; // default: outside
whiteList['list-style-type'] = true; // default: disc
whiteList['margin'] = true; // default: depending on individual properties
whiteList['margin-bottom'] = true; // default: 0
whiteList['margin-left'] = true; // default: 0
whiteList['margin-right'] = true; // default: 0
whiteList['margin-top'] = true; // default: 0
whiteList['marker-offset'] = false; // default: auto
whiteList['marker-side'] = false; // default: list-item
whiteList['marks'] = false; // default: none
whiteList['mask'] = false; // default: border-box
whiteList['mask-box'] = false; // default: see individual properties
whiteList['mask-box-outset'] = false; // default: 0
whiteList['mask-box-repeat'] = false; // default: stretch
whiteList['mask-box-slice'] = false; // default: 0 fill
whiteList['mask-box-source'] = false; // default: none
whiteList['mask-box-width'] = false; // default: auto
whiteList['mask-clip'] = false; // default: border-box
whiteList['mask-image'] = false; // default: none
whiteList['mask-origin'] = false; // default: border-box
whiteList['mask-position'] = false; // default: center
whiteList['mask-repeat'] = false; // default: no-repeat
whiteList['mask-size'] = false; // default: border-box
whiteList['mask-source-type'] = false; // default: auto
whiteList['mask-type'] = false; // default: luminance
whiteList['max-height'] = true; // default: none
whiteList['max-lines'] = false; // default: none
whiteList['max-width'] = true; // default: none
whiteList['min-height'] = true; // default: 0
whiteList['min-width'] = true; // default: 0
whiteList['move-to'] = false; // default: normal
whiteList['nav-down'] = false; // default: auto
whiteList['nav-index'] = false; // default: auto
whiteList['nav-left'] = false; // default: auto
whiteList['nav-right'] = false; // default: auto
whiteList['nav-up'] = false; // default: auto
whiteList['object-fit'] = false; // default: fill
whiteList['object-position'] = false; // default: 50% 50%
whiteList['opacity'] = false; // default: 1
whiteList['order'] = false; // default: 0
whiteList['orphans'] = false; // default: 2
whiteList['outline'] = false; // default: depending on individual properties
whiteList['outline-color'] = false; // default: invert
whiteList['outline-offset'] = false; // default: 0
whiteList['outline-style'] = false; // default: none
whiteList['outline-width'] = false; // default: medium
whiteList['overflow'] = false; // default: depending on individual properties
whiteList['overflow-wrap'] = false; // default: normal
whiteList['overflow-x'] = false; // default: visible
whiteList['overflow-y'] = false; // default: visible
whiteList['padding'] = true; // default: depending on individual properties
whiteList['padding-bottom'] = true; // default: 0
whiteList['padding-left'] = true; // default: 0
whiteList['padding-right'] = true; // default: 0
whiteList['padding-top'] = true; // default: 0
whiteList['page'] = false; // default: auto
whiteList['page-break-after'] = false; // default: auto
whiteList['page-break-before'] = false; // default: auto
whiteList['page-break-inside'] = false; // default: auto
whiteList['page-policy'] = false; // default: start
whiteList['pause'] = false; // default: implementation dependent
whiteList['pause-after'] = false; // default: implementation dependent
whiteList['pause-before'] = false; // default: implementation dependent
whiteList['perspective'] = false; // default: none
whiteList['perspective-origin'] = false; // default: 50% 50%
whiteList['pitch'] = false; // default: medium
whiteList['pitch-range'] = false; // default: 50
whiteList['play-during'] = false; // default: auto
whiteList['position'] = false; // default: static
whiteList['presentation-level'] = false; // default: 0
whiteList['quotes'] = false; // default: text
whiteList['region-fragment'] = false; // default: auto
whiteList['resize'] = false; // default: none
whiteList['rest'] = false; // default: depending on individual properties
whiteList['rest-after'] = false; // default: none
whiteList['rest-before'] = false; // default: none
whiteList['richness'] = false; // default: 50
whiteList['right'] = false; // default: auto
whiteList['rotation'] = false; // default: 0
whiteList['rotation-point'] = false; // default: 50% 50%
whiteList['ruby-align'] = false; // default: auto
whiteList['ruby-merge'] = false; // default: separate
whiteList['ruby-position'] = false; // default: before
whiteList['shape-image-threshold'] = false; // default: 0.0
whiteList['shape-outside'] = false; // default: none
whiteList['shape-margin'] = false; // default: 0
whiteList['size'] = false; // default: auto
whiteList['speak'] = false; // default: auto
whiteList['speak-as'] = false; // default: normal
whiteList['speak-header'] = false; // default: once
whiteList['speak-numeral'] = false; // default: continuous
whiteList['speak-punctuation'] = false; // default: none
whiteList['speech-rate'] = false; // default: medium
whiteList['stress'] = false; // default: 50
whiteList['string-set'] = false; // default: none
whiteList['tab-size'] = false; // default: 8
whiteList['table-layout'] = false; // default: auto
whiteList['text-align'] = true; // default: start
whiteList['text-align-last'] = true; // default: auto
whiteList['text-combine-upright'] = true; // default: none
whiteList['text-decoration'] = true; // default: none
whiteList['text-decoration-color'] = true; // default: currentColor
whiteList['text-decoration-line'] = true; // default: none
whiteList['text-decoration-skip'] = true; // default: objects
whiteList['text-decoration-style'] = true; // default: solid
whiteList['text-emphasis'] = true; // default: depending on individual properties
whiteList['text-emphasis-color'] = true; // default: currentColor
whiteList['text-emphasis-position'] = true; // default: over right
whiteList['text-emphasis-style'] = true; // default: none
whiteList['text-height'] = true; // default: auto
whiteList['text-indent'] = true; // default: 0
whiteList['text-justify'] = true; // default: auto
whiteList['text-orientation'] = true; // default: mixed
whiteList['text-overflow'] = true; // default: clip
whiteList['text-shadow'] = true; // default: none
whiteList['text-space-collapse'] = true; // default: collapse
whiteList['text-transform'] = true; // default: none
whiteList['text-underline-position'] = true; // default: auto
whiteList['text-wrap'] = true; // default: normal
whiteList['top'] = false; // default: auto
whiteList['transform'] = false; // default: none
whiteList['transform-origin'] = false; // default: 50% 50% 0
whiteList['transform-style'] = false; // default: flat
whiteList['transition'] = false; // default: depending on individual properties
whiteList['transition-delay'] = false; // default: 0s
whiteList['transition-duration'] = false; // default: 0s
whiteList['transition-property'] = false; // default: all
whiteList['transition-timing-function'] = false; // default: ease
whiteList['unicode-bidi'] = false; // default: normal
whiteList['vertical-align'] = false; // default: baseline
whiteList['visibility'] = false; // default: visible
whiteList['voice-balance'] = false; // default: center
whiteList['voice-duration'] = false; // default: auto
whiteList['voice-family'] = false; // default: implementation dependent
whiteList['voice-pitch'] = false; // default: medium
whiteList['voice-range'] = false; // default: medium
whiteList['voice-rate'] = false; // default: normal
whiteList['voice-stress'] = false; // default: normal
whiteList['voice-volume'] = false; // default: medium
whiteList['volume'] = false; // default: medium
whiteList['white-space'] = false; // default: normal
whiteList['widows'] = false; // default: 2
whiteList['width'] = true; // default: auto
whiteList['will-change'] = false; // default: auto
whiteList['word-break'] = true; // default: normal
whiteList['word-spacing'] = true; // default: normal
whiteList['word-wrap'] = true; // default: normal
whiteList['wrap-flow'] = false; // default: auto
whiteList['wrap-through'] = false; // default: wrap
whiteList['writing-mode'] = false; // default: horizontal-tb
whiteList['z-index'] = false; // default: auto
return whiteList;
}
/**
* 匹配到白名单上的一个属性时
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {String}
*/
function onAttr(name, value, options) {
// do nothing
}
/**
* 匹配到不在白名单上的一个属性时
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {String}
*/
function onIgnoreAttr(name, value, options) {
// do nothing
}
var REGEXP_URL_JAVASCRIPT = /javascript\s*\:/img;
/**
* 过滤属性值
*
* @param {String} name
* @param {String} value
* @return {String}
*/
function safeAttrValue$1(name, value) {
if (REGEXP_URL_JAVASCRIPT.test(value)) return '';
return value;
}
var whiteList$1 = getDefaultWhiteList$1();
var getDefaultWhiteList_1$1 = getDefaultWhiteList$1;
var onAttr_1 = onAttr;
var onIgnoreAttr_1 = onIgnoreAttr;
var safeAttrValue_1$1 = safeAttrValue$1;
var _default$1 = {
whiteList: whiteList$1,
getDefaultWhiteList: getDefaultWhiteList_1$1,
onAttr: onAttr_1,
onIgnoreAttr: onIgnoreAttr_1,
safeAttrValue: safeAttrValue_1$1
};
var util$1 = {
indexOf: function (arr, item) {
var i, j;
if (Array.prototype.indexOf) {
return arr.indexOf(item);
}
for (i = 0, j = arr.length; i < j; i++) {
if (arr[i] === item) {
return i;
}
}
return -1;
},
forEach: function (arr, fn, scope) {
var i, j;
if (Array.prototype.forEach) {
return arr.forEach(fn, scope);
}
for (i = 0, j = arr.length; i < j; i++) {
fn.call(scope, arr[i], i, arr);
}
},
trim: function (str) {
if (String.prototype.trim) {
return str.trim();
}
return str.replace(/(^\s*)|(\s*$)/g, '');
},
trimRight: function (str) {
if (String.prototype.trimRight) {
return str.trimRight();
}
return str.replace(/(\s*$)/g, '');
}
};
/**
* cssfilter
*
* @author 老雷<leizongmin@gmail.com>
*/
/**
* 解析style
*
* @param {String} css
* @param {Function} onAttr 处理属性的函数
* 参数格式: function (sourcePosition, position, name, value, source)
* @return {String}
*/
function parseStyle(css, onAttr) {
css = util$1.trimRight(css);
if (css[css.length - 1] !== ';') css += ';';
var cssLength = css.length;
var isParenthesisOpen = false;
var lastPos = 0;
var i = 0;
var retCSS = '';
function addNewAttr() {
// 如果没有正常的闭合圆括号,则直接忽略当前属性
if (!isParenthesisOpen) {
var source = util$1.trim(css.slice(lastPos, i));
var j = source.indexOf(':');
if (j !== -1) {
var name = util$1.trim(source.slice(0, j));
var value = util$1.trim(source.slice(j + 1));
// 必须有属性名称
if (name) {
var ret = onAttr(lastPos, retCSS.length, name, value, source);
if (ret) retCSS += ret + '; ';
}
}
}
lastPos = i + 1;
}
for (; i < cssLength; i++) {
var c = css[i];
if (c === '/' && css[i + 1] === '*') {
// 备注开始
var j = css.indexOf('*/', i + 2);
// 如果没有正常的备注结束,则后面的部分全部跳过
if (j === -1) break;
// 直接将当前位置调到备注结尾,并且初始化状态
i = j + 1;
lastPos = i + 1;
isParenthesisOpen = false;
} else if (c === '(') {
isParenthesisOpen = true;
} else if (c === ')') {
isParenthesisOpen = false;
} else if (c === ';') {
if (isParenthesisOpen) ; else {
addNewAttr();
}
} else if (c === '\n') {
addNewAttr();
}
}
return util$1.trim(retCSS);
}
var parser$1 = parseStyle;
/**
* cssfilter
*
* @author 老雷<leizongmin@gmail.com>
*/
/**
* 返回值是否为空
*
* @param {Object} obj
* @return {Boolean}
*/
function isNull$1(obj) {
return obj === undefined || obj === null;
}
/**
* 浅拷贝对象
*
* @param {Object} obj
* @return {Object}
*/
function shallowCopyObject$1(obj) {
var ret = {};
for (var i in obj) {
ret[i] = obj[i];
}
return ret;
}
/**
* 创建CSS过滤器
*
* @param {Object} options
* - {Object} whiteList
* - {Function} onAttr
* - {Function} onIgnoreAttr
* - {Function} safeAttrValue
*/
function FilterCSS$2(options) {
options = shallowCopyObject$1(options || {});
options.whiteList = options.whiteList || _default$1.whiteList;
options.onAttr = options.onAttr || _default$1.onAttr;
options.onIgnoreAttr = options.onIgnoreAttr || _default$1.onIgnoreAttr;
options.safeAttrValue = options.safeAttrValue || _default$1.safeAttrValue;
this.options = options;
}
FilterCSS$2.prototype.process = function (css) {
// 兼容各种奇葩输入
css = css || '';
css = css.toString();
if (!css) return '';
var me = this;
var options = me.options;
var whiteList = options.whiteList;
var onAttr = options.onAttr;
var onIgnoreAttr = options.onIgnoreAttr;
var safeAttrValue = options.safeAttrValue;
var retCSS = parser$1(css, function (sourcePosition, position, name, value, source) {
var check = whiteList[name];
var isWhite = false;
if (check === true) isWhite = check;else if (typeof check === 'function') isWhite = check(value);else if (check instanceof RegExp) isWhite = check.test(value);
if (isWhite !== true) isWhite = false;
// 如果过滤后 value 为空则直接忽略
value = safeAttrValue(name, value);
if (!value) return;
var opts = {
position: position,
sourcePosition: sourcePosition,
source: source,
isWhite: isWhite
};
if (isWhite) {
var ret = onAttr(name, value, opts);
if (isNull$1(ret)) {
return name + ':' + value;
} else {
return ret;
}
} else {
var ret = onIgnoreAttr(name, value, opts);
if (!isNull$1(ret)) {
return ret;
}
}
});
return retCSS;
};
var css = FilterCSS$2;
/**
* cssfilter
*
* @author 老雷<leizongmin@gmail.com>
*/
var lib$1 = createCommonjsModule(function (module, exports) {
/**
* XSS过滤
*
* @param {String} css 要过滤的CSS代码
* @param {Object} options 选项:whiteList, onAttr, onIgnoreAttr
* @return {String}
*/
function filterCSS(html, options) {
var xss = new css(options);
return xss.process(html);
}
// 输出
exports = module.exports = filterCSS;
exports.FilterCSS = css;
for (var i in _default$1) exports[i] = _default$1[i];
// 在浏览器端使用
if (typeof window !== 'undefined') {
window.filterCSS = module.exports;
}
});
var util = {
indexOf: function (arr, item) {
var i, j;
if (Array.prototype.indexOf) {
return arr.indexOf(item);
}
for (i = 0, j = arr.length; i < j; i++) {
if (arr[i] === item) {
return i;
}
}
return -1;
},
forEach: function (arr, fn, scope) {
var i, j;
if (Array.prototype.forEach) {
return arr.forEach(fn, scope);
}
for (i = 0, j = arr.length; i < j; i++) {
fn.call(scope, arr[i], i, arr);
}
},
trim: function (str) {
if (String.prototype.trim) {
return str.trim();
}
return str.replace(/(^\s*)|(\s*$)/g, "");
},
spaceIndex: function (str) {
var reg = /\s|\n|\t/;
var match = reg.exec(str);
return match ? match.index : -1;
}
};
/**
* default settings
*
* @author Zongmin Lei<leizongmin@gmail.com>
*/
var FilterCSS$1 = lib$1.FilterCSS;
var getDefaultCSSWhiteList = lib$1.getDefaultWhiteList;
function getDefaultWhiteList() {
return {
a: ["target", "href", "title"],
abbr: ["title"],
address: [],
area: ["shape", "coords", "href", "alt"],
article: [],
aside: [],
audio: ["autoplay", "controls", "crossorigin", "loop", "muted", "preload", "src"],
b: [],
bdi: ["dir"],
bdo: ["dir"],
big: [],
blockquote: ["cite"],
br: [],
caption: [],
center: [],
cite: [],
code: [],
col: ["align", "valign", "span", "width"],
colgroup: ["align", "valign", "span", "width"],
dd: [],
del: ["datetime"],
details: ["open"],
div: [],
dl: [],
dt: [],
em: [],
figcaption: [],
figure: [],
font: ["color", "size", "face"],
footer: [],
h1: [],
h2: [],
h3: [],
h4: [],
h5: [],
h6: [],
header: [],
hr: [],
i: [],
img: ["src", "alt", "title", "width", "height"],
ins: ["datetime"],
li: [],
mark: [],
nav: [],
ol: [],
p: [],
pre: [],
s: [],
section: [],
small: [],
span: [],
sub: [],
summary: [],
sup: [],
strong: [],
strike: [],
table: ["width", "border", "align", "valign"],
tbody: ["align", "valign"],
td: ["width", "rowspan", "colspan", "align", "valign"],
tfoot: ["align", "valign"],
th: ["width", "rowspan", "colspan", "align", "valign"],
thead: ["align", "valign"],
tr: ["rowspan", "align", "valign"],
tt: [],
u: [],
ul: [],
video: ["autoplay", "controls", "crossorigin", "loop", "muted", "playsinline", "poster", "preload", "src", "height", "width"]
};
}
var defaultCSSFilter = new FilterCSS$1();
/**
* default onTag function
*
* @param {String} tag
* @param {String} html
* @param {Object} options
* @return {String}
*/
function onTag(tag, html, options) {
// do nothing
}
/**
* default onIgnoreTag function
*
* @param {String} tag
* @param {String} html
* @param {Object} options
* @return {String}
*/
function onIgnoreTag(tag, html, options) {
// do nothing
}
/**
* default onTagAttr function
*
* @param {String} tag
* @param {String} name
* @param {String} value
* @return {String}
*/
function onTagAttr(tag, name, value) {
// do nothing
}
/**
* default onIgnoreTagAttr function
*
* @param {String} tag
* @param {String} name
* @param {String} value
* @return {String}
*/
function onIgnoreTagAttr(tag, name, value) {
// do nothing
}
/**
* default escapeHtml function
*
* @param {String} html
*/
function escapeHtml(html) {
return html.replace(REGEXP_LT, "<").replace(REGEXP_GT, ">");
}
/**
* default safeAttrValue function
*
* @param {String} tag
* @param {String} name
* @param {String} value
* @param {Object} cssFilter
* @return {String}
*/
function safeAttrValue(tag, name, value, cssFilter) {
// unescape attribute value firstly
value = friendlyAttrValue(value);
if (name === "href" || name === "src") {
// filter `href` and `src` attribute
// only allow the value that starts with `http://` | `https://` | `mailto:` | `/` | `#`
value = util.trim(value);
if (value === "#") return "#";
if (!(value.substr(0, 7) === "http://" || value.substr(0, 8) === "https://" || value.substr(0, 7) === "mailto:" || value.substr(0, 4) === "tel:" || value.substr(0, 11) === "data:image/" || value.substr(0, 6) === "ftp://" || value.substr(0, 2) === "./" || value.substr(0, 3) === "../" || value[0] === "#" || value[0] === "/")) {
return "";
}
} else if (name === "background") {
// filter `background` attribute (maybe no use)
// `javascript:`
REGEXP_DEFAULT_ON_TAG_ATTR_4.lastIndex = 0;
if (REGEXP_DEFAULT_ON_TAG_ATTR_4.test(value)) {
return "";
}
} else if (name === "style") {
// `expression()`
REGEXP_DEFAULT_ON_TAG_ATTR_7.lastIndex = 0;
if (REGEXP_DEFAULT_ON_TAG_ATTR_7.test(value)) {
return "";
}
// `url()`
REGEXP_DEFAULT_ON_TAG_ATTR_8.lastIndex = 0;
if (REGEXP_DEFAULT_ON_TAG_ATTR_8.test(value)) {
REGEXP_DEFAULT_ON_TAG_ATTR_4.lastIndex = 0;
if (REGEXP_DEFAULT_ON_TAG_ATTR_4.test(value)) {
return "";
}
}
if (cssFilter !== false) {
cssFilter = cssFilter || defaultCSSFilter;
value = cssFilter.process(value);
}
}
// escape `<>"` before returns
value = escapeAttrValue(value);
return value;
}
// RegExp list
var REGEXP_LT = /</g;
var REGEXP_GT = />/g;
var REGEXP_QUOTE = /"/g;
var REGEXP_QUOTE_2 = /"/g;
var REGEXP_ATTR_VALUE_1 = /&#([a-zA-Z0-9]*);?/gim;
var REGEXP_ATTR_VALUE_COLON = /:?/gim;
var REGEXP_ATTR_VALUE_NEWLINE = /&newline;?/gim;
// var REGEXP_DEFAULT_ON_TAG_ATTR_3 = /\/\*|\*\//gm;
var REGEXP_DEFAULT_ON_TAG_ATTR_4 = /((j\s*a\s*v\s*a|v\s*b|l\s*i\s*v\s*e)\s*s\s*c\s*r\s*i\s*p\s*t\s*|m\s*o\s*c\s*h\s*a):/gi;
// var REGEXP_DEFAULT_ON_TAG_ATTR_5 = /^[\s"'`]*(d\s*a\s*t\s*a\s*)\:/gi;
// var REGEXP_DEFAULT_ON_TAG_ATTR_6 = /^[\s"'`]*(d\s*a\s*t\s*a\s*)\:\s*image\//gi;
var REGEXP_DEFAULT_ON_TAG_ATTR_7 = /e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n\s*\(.*/gi;
var REGEXP_DEFAULT_ON_TAG_ATTR_8 = /u\s*r\s*l\s*\(.*/gi;
/**
* escape double quote
*
* @param {String} str
* @return {String} str
*/
function escapeQuote(str) {
return str.replace(REGEXP_QUOTE, """);
}
/**
* unescape double quote
*
* @param {String} str
* @return {String} str
*/
function unescapeQuote(str) {
return str.replace(REGEXP_QUOTE_2, '"');
}
/**
* escape html entities
*
* @param {String} str
* @return {String}
*/
function escapeHtmlEntities(str) {
return str.replace(REGEXP_ATTR_VALUE_1, function replaceUnicode(str, code) {
return code[0] === "x" || code[0] === "X" ? String.fromCharCode(parseInt(code.substr(1), 16)) : String.fromCharCode(parseInt(code, 10));
});
}
/**
* escape html5 new danger entities
*
* @param {String} str
* @return {String}
*/
function escapeDangerHtml5Entities(str) {
return str.replace(REGEXP_ATTR_VALUE_COLON, ":").replace(REGEXP_ATTR_VALUE_NEWLINE, " ");
}
/**
* clear nonprintable characters
*
* @param {String} str
* @return {String}
*/
function clearNonPrintableCharacter(str) {
var str2 = "";
for (var i = 0, len = str.length; i < len; i++) {
str2 += str.charCodeAt(i) < 32 ? " " : str.charAt(i);
}
return util.trim(str2);
}
/**
* get friendly attribute value
*
* @param {String} str
* @return {String}
*/
function friendlyAttrValue(str) {
str = unescapeQuote(str);
str = escapeHtmlEntities(str);
str = escapeDangerHtml5Entities(str);
str = clearNonPrintableCharacter(str);
return str;
}
/**
* unescape attribute value
*
* @param {String} str
* @return {String}
*/
function escapeAttrValue(str) {
str = escapeQuote(str);
str = escapeHtml(str);
return str;
}
/**
* `onIgnoreTag` function for removing all the tags that are not in whitelist
*/
function onIgnoreTagStripAll() {
return "";
}
/**
* remove tag body
* specify a `tags` list, if the tag is not in the `tags` list then process by the specify function (optional)
*
* @param {array} tags
* @param {function} next
*/
function StripTagBody(tags, next) {
if (typeof next !== "function") {
next = function () {};
}
var isRemoveAllTag = !Array.isArray(tags);
function isRemoveTag(tag) {
if (isRemoveAllTag) return true;
return util.indexOf(tags, tag) !== -1;
}
var removeList = [];
var posStart = false;
return {
onIgnoreTag: function (tag, html, options) {
if (isRemoveTag(tag)) {
if (options.isClosing) {
var ret = "[/removed]";
var end = options.position + ret.length;
removeList.push([posStart !== false ? posStart : options.position, end]);
posStart = false;
return ret;
} else {
if (!posStart) {
posStart = options.position;
}
return "[removed]";
}
} else {
return next(tag, html, options);
}
},
remove: function (html) {
var rethtml = "";
var lastPos = 0;
util.forEach(removeList, function (pos) {
rethtml += html.slice(lastPos, pos[0]);
lastPos = pos[1];
});
rethtml += html.slice(lastPos);
return rethtml;
}
};
}
/**
* remove html comments
*
* @param {String} html
* @return {String}
*/
function stripCommentTag(html) {
var retHtml = "";
var lastPos = 0;
while (lastPos < html.length) {
var i = html.indexOf("<!--", lastPos);
if (i === -1) {
retHtml += html.slice(lastPos);
break;
}
retHtml += html.slice(lastPos, i);
var j = html.indexOf("-->", i);
if (j === -1) {
break;
}
lastPos = j + 3;
}
return retHtml;
}
/**
* remove invisible characters
*
* @param {String} html
* @return {String}
*/
function stripBlankChar(html) {
var chars = html.split("");
chars = chars.filter(function (char) {
var c = char.charCodeAt(0);
if (c === 127) return false;
if (c <= 31) {
if (c === 10 || c === 13) return true;
return false;
}
return true;
});
return chars.join("");
}
var whiteList = getDefaultWhiteList();
var getDefaultWhiteList_1 = getDefaultWhiteList;
var onTag_1 = onTag;
var onIgnoreTag_1 = onIgnoreTag;
var onTagAttr_1 = onTagAttr;
var onIgnoreTagAttr_1 = onIgnoreTagAttr;
var safeAttrValue_1 = safeAttrValue;
var escapeHtml_1 = escapeHtml;
var escapeQuote_1 = escapeQuote;
var unescapeQuote_1 = unescapeQuote;
var escapeHtmlEntities_1 = escapeHtmlEntities;
var escapeDangerHtml5Entities_1 = escapeDangerHtml5Entities;
var clearNonPrintableCharacter_1 = clearNonPrintableCharacter;
var friendlyAttrValue_1 = friendlyAttrValue;
var escapeAttrValue_1 = escapeAttrValue;
var onIgnoreTagStripAll_1 = onIgnoreTagStripAll;
var StripTagBody_1 = StripTagBody;
var stripCommentTag_1 = stripCommentTag;
var stripBlankChar_1 = stripBlankChar;
var cssFilter = defaultCSSFilter;
var getDefaultCSSWhiteList_1 = getDefaultCSSWhiteList;
var _default = {
whiteList: whiteList,
getDefaultWhiteList: getDefaultWhiteList_1,
onTag: onTag_1,
onIgnoreTag: onIgnoreTag_1,
onTagAttr: onTagAttr_1,
onIgnoreTagAttr: onIgnoreTagAttr_1,
safeAttrValue: safeAttrValue_1,
escapeHtml: escapeHtml_1,
escapeQuote: escapeQuote_1,
unescapeQuote: unescapeQuote_1,
escapeHtmlEntities: escapeHtmlEntities_1,
escapeDangerHtml5Entities: escapeDangerHtml5Entities_1,
clearNonPrintableCharacter: clearNonPrintableCharacter_1,
friendlyAttrValue: friendlyAttrValue_1,
escapeAttrValue: escapeAttrValue_1,
onIgnoreTagStripAll: onIgnoreTagStripAll_1,
StripTagBody: StripTagBody_1,
stripCommentTag: stripCommentTag_1,
stripBlankChar: stripBlankChar_1,
cssFilter: cssFilter,
getDefaultCSSWhiteList: getDefaultCSSWhiteList_1
};
/**
* Simple HTML Parser
*
* @author Zongmin Lei<leizongmin@gmail.com>
*/
/**
* get tag name
*
* @param {String} html e.g. '<a hef="#">'
* @return {String}
*/
function getTagName(html) {
var i = util.spaceIndex(html);
var tagName;
if (i === -1) {
tagName = html.slice(1, -1);
} else {
tagName = html.slice(1, i + 1);
}
tagName = util.trim(tagName).toLowerCase();
if (tagName.slice(0, 1) === "/") tagName = tagName.slice(1);
if (tagName.slice(-1) === "/") tagName = tagName.slice(0, -1);
return tagName;
}
/**
* is close tag?
*
* @param {String} html 如:'<a hef="#">'
* @return {Boolean}
*/
function isClosing(html) {
return html.slice(0, 2) === "</";
}
/**
* parse input html and returns processed html
*
* @param {String} html
* @param {Function} onTag e.g. function (sourcePosition, position, tag, html, isClosing)
* @param {Function} escapeHtml
* @return {String}
*/
function parseTag$1(html, onTag, escapeHtml) {
var rethtml = "";
var lastPos = 0;
var tagStart = false;
var quoteStart = false;
var currentPos = 0;
var len = html.length;
var currentTagName = "";
var currentHtml = "";
chariterator: for (currentPos = 0; currentPos < len; currentPos++) {
var c = html.charAt(currentPos);
if (tagStart === false) {
if (c === "<") {
tagStart = currentPos;
continue;
}
} else {
if (quoteStart === false) {
if (c === "<") {
rethtml += escapeHtml(html.slice(lastPos, currentPos));
tagStart = currentPos;
lastPos = currentPos;
continue;
}
if (c === ">" || currentPos === len - 1) {
rethtml += escapeHtml(html.slice(lastPos, tagStart));
currentHtml = html.slice(tagStart, currentPos + 1);
currentTagName = getTagName(currentHtml);
rethtml += onTag(tagStart, rethtml.length, currentTagName, currentHtml, isClosing(currentHtml));
lastPos = currentPos + 1;
tagStart = false;
continue;
}
if (c === '"' || c === "'") {
var i = 1;
var ic = html.charAt(currentPos - i);
while (ic.trim() === "" || ic === "=") {
if (ic === "=") {
quoteStart = c;
continue chariterator;
}
ic = html.charAt(currentPos - ++i);
}
}
} else {
if (c === quoteStart) {
quoteStart = false;
continue;
}
}
}
}
if (lastPos < len) {
rethtml += escapeHtml(html.substr(lastPos));
}
return rethtml;
}
var REGEXP_ILLEGAL_ATTR_NAME = /[^a-zA-Z0-9\\_:.-]/gim;
/**
* parse input attributes and returns processed attributes
*
* @param {String} html e.g. `href="#" target="_blank"`
* @param {Function} onAttr e.g. `function (name, value)`
* @return {String}
*/
function parseAttr$1(html, onAttr) {
var lastPos = 0;
var lastMarkPos = 0;
var retAttrs = [];
var tmpName = false;
var len = html.length;
function addAttr(name, value) {
name = util.trim(name);
name = name.replace(REGEXP_ILLEGAL_ATTR_NAME, "").toLowerCase();
if (name.length < 1) return;
var ret = onAttr(name, value || "");
if (ret) retAttrs.push(ret);
}
// 逐个分析字符
for (var i = 0; i < len; i++) {
var c = html.charAt(i);
var v, j;
if (tmpName === false && c === "=") {
tmpName = html.slice(lastPos, i);
lastPos = i + 1;
lastMarkPos = html.charAt(lastPos) === '"' || html.charAt(lastPos) === "'" ? lastPos : findNextQuotationMark(html, i + 1);
continue;
}
if (tmpName !== false) {
if (i === lastMarkPos) {
j = html.indexOf(c, i + 1);
if (j === -1) {
break;
} else {
v = util.trim(html.slice(lastMarkPos + 1, j));
addAttr(tmpName, v);
tmpName = false;
i = j;
lastPos = i + 1;
continue;
}
}
}
if (/\s|\n|\t/.test(c)) {
html = html.replace(/\s|\n|\t/g, " ");
if (tmpName === false) {
j = findNextEqual(html, i);
if (j === -1) {
v = util.trim(html.slice(lastPos, i));
addAttr(v);
tmpName = false;
lastPos = i + 1;
continue;
} else {
i = j - 1;
continue;
}
} else {
j = findBeforeEqual(html, i - 1);
if (j === -1) {
v = util.trim(html.slice(lastPos, i));
v = stripQuoteWrap(v);
addAttr(tmpName, v);
tmpName = false;
lastPos = i + 1;
continue;
} else {
continue;
}
}
}
}
if (lastPos < html.length) {
if (tmpName === false) {
addAttr(html.slice(lastPos));
} else {
addAttr(tmpName, stripQuoteWrap(util.trim(html.slice(lastPos))));
}
}
return util.trim(retAttrs.join(" "));
}
function findNextEqual(str, i) {
for (; i < str.length; i++) {
var c = str[i];
if (c === " ") continue;
if (c === "=") return i;
return -1;
}
}
function findNextQuotationMark(str, i) {
for (; i < str.length; i++) {
var c = str[i];
if (c === " ") continue;
if (c === "'" || c === '"') return i;
return -1;
}
}
function findBeforeEqual(str, i) {
for (; i > 0; i--) {
var c = str[i];
if (c === " ") continue;
if (c === "=") return i;
return -1;
}
}
function isQuoteWrapString(text) {
if (text[0] === '"' && text[text.length - 1] === '"' || text[0] === "'" && text[text.length - 1] === "'") {
return true;
} else {
return false;
}
}
function stripQuoteWrap(text) {
if (isQuoteWrapString(text)) {
return text.substr(1, text.length - 2);
} else {
return text;
}
}
var parseTag_1 = parseTag$1;
var parseAttr_1 = parseAttr$1;
var parser = {
parseTag: parseTag_1,
parseAttr: parseAttr_1
};
/**
* filter xss
*
* @author Zongmin Lei<leizongmin@gmail.com>
*/
var FilterCSS = lib$1.FilterCSS;
var parseTag = parser.parseTag;
var parseAttr = parser.parseAttr;
/**
* returns `true` if the input value is `undefined` or `null`
*
* @param {Object} obj
* @return {Boolean}
*/
function isNull(obj) {
return obj === undefined || obj === null;
}
/**
* get attributes for a tag
*
* @param {String} html
* @return {Object}
* - {String} html
* - {Boolean} closing
*/
function getAttrs(html) {
var i = util.spaceIndex(html);
if (i === -1) {
return {
html: "",
closing: html[html.length - 2] === "/"
};
}
html = util.trim(html.slice(i + 1, -1));
var isClosing = html[html.length - 1] === "/";
if (isClosing) html = util.trim(html.slice(0, -1));
return {
html: html,
closing: isClosing
};
}
/**
* shallow copy
*
* @param {Object} obj
* @return {Object}
*/
function shallowCopyObject(obj) {
var ret = {};
for (var i in obj) {
ret[i] = obj[i];
}
return ret;
}
function keysToLowerCase(obj) {
var ret = {};
for (var i in obj) {
if (Array.isArray(obj[i])) {
ret[i.toLowerCase()] = obj[i].map(function (item) {
return item.toLowerCase();
});
} else {
ret[i.toLowerCase()] = obj[i];
}
}
return ret;
}
/**
* FilterXSS class
*
* @param {Object} options
* whiteList (or allowList), onTag, onTagAttr, onIgnoreTag,
* onIgnoreTagAttr, safeAttrValue, escapeHtml
* stripIgnoreTagBody, allowCommentTag, stripBlankChar
* css{whiteList, onAttr, onIgnoreAttr} `css=false` means don't use `cssfilter`
*/
function FilterXSS(options) {
options = shallowCopyObject(options || {});
if (options.stripIgnoreTag) {
if (options.onIgnoreTag) {
console.error('Notes: cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time');
}
options.onIgnoreTag = _default.onIgnoreTagStripAll;
}
if (options.whiteList || options.allowList) {
options.whiteList = keysToLowerCase(options.whiteList || options.allowList);
} else {
options.whiteList = _default.whiteList;
}
options.onTag = options.onTag || _default.onTag;
options.onTagAttr = options.onTagAttr || _default.onTagAttr;
options.onIgnoreTag = options.onIgnoreTag || _default.onIgnoreTag;
options.onIgnoreTagAttr = options.onIgnoreTagAttr || _default.onIgnoreTagAttr;
options.safeAttrValue = options.safeAttrValue || _default.safeAttrValue;
options.escapeHtml = options.escapeHtml || _default.escapeHtml;
this.options = options;
if (options.css === false) {
this.cssFilter = false;
} else {
options.css = options.css || {};
this.cssFilter = new FilterCSS(options.css);
}
}
/**
* start process and returns result
*
* @param {String} html
* @return {String}
*/
FilterXSS.prototype.process = function (html) {
// compatible with the input
html = html || "";
html = html.toString();
if (!html) return "";
var me = this;
var options = me.options;
var whiteList = options.whiteList;
var onTag = options.onTag;
var onIgnoreTag = options.onIgnoreTag;
var onTagAttr = options.onTagAttr;
var onIgnoreTagAttr = options.onIgnoreTagAttr;
var safeAttrValue = options.safeAttrValue;
var escapeHtml = options.escapeHtml;
var cssFilter = me.cssFilter;
// remove invisible characters
if (options.stripBlankChar) {
html = _default.stripBlankChar(html);
}
// remove html comments
if (!options.allowCommentTag) {
html = _default.stripCommentTag(html);
}
// if enable stripIgnoreTagBody
var stripIgnoreTagBody = false;
if (options.stripIgnoreTagBody) {
stripIgnoreTagBody = _default.StripTagBody(options.stripIgnoreTagBody, onIgnoreTag);
onIgnoreTag = stripIgnoreTagBody.onIgnoreTag;
}
var retHtml = parseTag(html, function (sourcePosition, position, tag, html, isClosing) {
var info = {
sourcePosition: sourcePosition,
position: position,
isClosing: isClosing,
isWhite: Object.prototype.hasOwnProperty.call(whiteList, tag)
};
// call `onTag()`
var ret = onTag(tag, html, info);
if (!isNull(ret)) return ret;
if (info.isWhite) {
if (info.isClosing) {
return "</" + tag + ">";
}
var attrs = getAttrs(html);
var whiteAttrList = whiteList[tag];
var attrsHtml = parseAttr(attrs.html, function (name, value) {
// call `onTagAttr()`
var isWhiteAttr = util.indexOf(whiteAttrList, name) !== -1;
var ret = onTagAttr(tag, name, value, isWhiteAttr);
if (!isNull(ret)) return ret;
if (isWhiteAttr) {
// call `safeAttrValue()`
value = safeAttrValue(tag, name, value, cssFilter);
if (value) {
return name + '="' + value + '"';
} else {
return name;
}
} else {
// call `onIgnoreTagAttr()`
ret = onIgnoreTagAttr(tag, name, value, isWhiteAttr);
if (!isNull(ret)) return ret;
return;
}
});
// build new tag html
html = "<" + tag;
if (attrsHtml) html += " " + attrsHtml;
if (attrs.closing) html += " /";
html += ">";
return html;
} else {
// call `onIgnoreTag()`
ret = onIgnoreTag(tag, html, info);
if (!isNull(ret)) return ret;
return escapeHtml(html);
}
}, escapeHtml);
// if enable stripIgnoreTagBody
if (stripIgnoreTagBody) {
retHtml = stripIgnoreTagBody.remove(retHtml);
}
return retHtml;
};
var xss = FilterXSS;
/**
* xss
*
* @author Zongmin Lei<leizongmin@gmail.com>
*/
var lib = createCommonjsModule(function (module, exports) {
/**
* filter xss function
*
* @param {String} html
* @param {Object} options { whiteList, onTag, onTagAttr, onIgnoreTag, onIgnoreTagAttr, safeAttrValue, escapeHtml }
* @return {String}
*/
function filterXSS(html, options) {
var xss$1 = new xss(options);
return xss$1.process(html);
}
exports = module.exports = filterXSS;
exports.filterXSS = filterXSS;
exports.FilterXSS = xss;
(function () {
for (var i in _default) {
exports[i] = _default[i];
}
for (var j in parser) {
exports[j] = parser[j];
}
})();
// using `xss` on the browser, output `filterXSS` to the globals
if (typeof window !== "undefined") {
window.filterXSS = module.exports;
}
// using `xss` on the WebWorker, output `filterXSS` to the globals
function isWorkerEnv() {
return typeof self !== "undefined" && typeof DedicatedWorkerGlobalScope !== "undefined" && self instanceof DedicatedWorkerGlobalScope;
}
if (isWorkerEnv()) {
self.filterXSS = module.exports;
}
});
var _firstTarget = null; // singleton, will contain the target element where the touch event started
/**
* Extend an Hammer.js instance with event propagation.
*
* Features:
* - Events emitted by hammer will propagate in order from child to parent
* elements.
* - Events are extended with a function `event.stopPropagation()` to stop
* propagation to parent elements.
* - An option `preventDefault` to stop all default browser behavior.
*
* Usage:
* var hammer = propagatingHammer(new Hammer(element));
* var hammer = propagatingHammer(new Hammer(element), {preventDefault: true});
*
* @param {Hammer.Manager} hammer An hammer instance.
* @param {Object} [options] Available options:
* - `preventDefault: true | false | 'mouse' | 'touch' | 'pen'`.
* Enforce preventing the default browser behavior.
* Cannot be set to `false`.
* @return {Hammer.Manager} Returns the same hammer instance with extended
* functionality
*/
function propagating(hammer, options) {
var _options = options || {
preventDefault: false
};
if (hammer.Manager) {
// This looks like the Hammer constructor.
// Overload the constructors with our own.
var Hammer = hammer;
var PropagatingHammer = function (element, options) {
var o = Object.create(_options);
if (options) Hammer.assign(o, options);
return propagating(new Hammer(element, o), o);
};
Hammer.assign(PropagatingHammer, Hammer);
PropagatingHammer.Manager = function (element, options) {
var o = Object.create(_options);
if (options) Hammer.assign(o, options);
return propagating(new Hammer.Manager(element, o), o);
};
return PropagatingHammer;
}
// create a wrapper object which will override the functions
// `on`, `off`, `destroy`, and `emit` of the hammer instance
var wrapper = Object.create(hammer);
// attach to DOM element
var element = hammer.element;
if (!element.hammer) element.hammer = [];
element.hammer.push(wrapper);
// register an event to catch the start of a gesture and store the
// target in a singleton
hammer.on('hammer.input', function (event) {
if (_options.preventDefault === true || _options.preventDefault === event.pointerType) {
event.preventDefault();
}
if (event.isFirst) {
_firstTarget = event.target;
}
});
/** @type {Object.<String, Array.<function>>} */
wrapper._handlers = {};
/**
* Register a handler for one or multiple events
* @param {String} events A space separated string with events
* @param {function} handler A callback function, called as handler(event)
* @returns {Hammer.Manager} Returns the hammer instance
*/
wrapper.on = function (events, handler) {
// register the handler
split(events).forEach(function (event) {
var _handlers = wrapper._handlers[event];
if (!_handlers) {
wrapper._handlers[event] = _handlers = [];
// register the static, propagated handler
hammer.on(event, propagatedHandler);
}
_handlers.push(handler);
});
return wrapper;
};
/**
* Unregister a handler for one or multiple events
* @param {String} events A space separated string with events
* @param {function} [handler] Optional. The registered handler. If not
* provided, all handlers for given events
* are removed.
* @returns {Hammer.Manager} Returns the hammer instance
*/
wrapper.off = function (events, handler) {
// unregister the handler
split(events).forEach(function (event) {
var _handlers = wrapper._handlers[event];
if (_handlers) {
_handlers = handler ? _handlers.filter(function (h) {
return h !== handler;
}) : [];
if (_handlers.length > 0) {
wrapper._handlers[event] = _handlers;
} else {
// remove static, propagated handler
hammer.off(event, propagatedHandler);
delete wrapper._handlers[event];
}
}
});
return wrapper;
};
/**
* Emit to the event listeners
* @param {string} eventType
* @param {Event} event
*/
wrapper.emit = function (eventType, event) {
_firstTarget = event.target;
hammer.emit(eventType, event);
};
wrapper.destroy = function () {
// Detach from DOM element
var hammers = hammer.element.hammer;
var idx = hammers.indexOf(wrapper);
if (idx !== -1) hammers.splice(idx, 1);
if (!hammers.length) delete hammer.element.hammer;
// clear all handlers
wrapper._handlers = {};
// call original hammer destroy
hammer.destroy();
};
// split a string with space separated words
function split(events) {
return events.match(/[^ ]+/g);
}
/**
* A static event handler, applying event propagation.
* @param {Object} event
*/
function propagatedHandler(event) {
// let only a single hammer instance handle this event
if (event.type !== 'hammer.input') {
// it is possible that the same srcEvent is used with multiple hammer events,
// we keep track on which events are handled in an object _handled
if (!event.srcEvent._handled) {
event.srcEvent._handled = {};
}
if (event.srcEvent._handled[event.type]) {
return;
} else {
event.srcEvent._handled[event.type] = true;
}
}
// attach a stopPropagation function to the event
var stopped = false;
event.stopPropagation = function () {
stopped = true;
};
//wrap the srcEvent's stopPropagation to also stop hammer propagation:
var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
if (typeof srcStop == "function") {
event.srcEvent.stopPropagation = function () {
srcStop();
event.stopPropagation();
};
}
// attach firstTarget property to the event
event.firstTarget = _firstTarget;
// propagate over all elements (until stopped)
var elem = _firstTarget;
while (elem && !stopped) {
var elemHammer = elem.hammer;
if (elemHammer) {
var _handlers;
for (var k = 0; k < elemHammer.length; k++) {
_handlers = elemHammer[k]._handlers[event.type];
if (_handlers) for (var i = 0; i < _handlers.length && !stopped; i++) {
_handlers[i](event);
}
}
}
elem = elem.parentNode;
}
}
return wrapper;
}
var keycharm = createCommonjsModule(function (module, exports) {
/**
* Created by Alex on 11/6/2014.
*/
// https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
// if the module has no dependencies, the above pattern can be simplified to
(function (root, factory) {
{
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
}
})(commonjsGlobal, function () {
function keycharm(options) {
var preventDefault = options && options.preventDefault || false;
var container = options && options.container || window;
var _exportFunctions = {};
var _bound = {
keydown: {},
keyup: {}
};
var _keys = {};
var i;
// a - z
for (i = 97; i <= 122; i++) {
_keys[String.fromCharCode(i)] = {
code: 65 + (i - 97),
shift: false
};
}
// A - Z
for (i = 65; i <= 90; i++) {
_keys[String.fromCharCode(i)] = {
code: i,
shift: true
};
}
// 0 - 9
for (i = 0; i <= 9; i++) {
_keys['' + i] = {
code: 48 + i,
shift: false
};
}
// F1 - F12
for (i = 1; i <= 12; i++) {
_keys['F' + i] = {
code: 111 + i,
shift: false
};
}
// num0 - num9
for (i = 0; i <= 9; i++) {
_keys['num' + i] = {
code: 96 + i,
shift: false
};
}
// numpad misc
_keys['num*'] = {
code: 106,
shift: false
};
_keys['num+'] = {
code: 107,
shift: false
};
_keys['num-'] = {
code: 109,
shift: false
};
_keys['num/'] = {
code: 111,
shift: false
};
_keys['num.'] = {
code: 110,
shift: false
};
// arrows
_keys['left'] = {
code: 37,
shift: false
};
_keys['up'] = {
code: 38,
shift: false
};
_keys['right'] = {
code: 39,
shift: false
};
_keys['down'] = {
code: 40,
shift: false
};
// extra keys
_keys['space'] = {
code: 32,
shift: false
};
_keys['enter'] = {
code: 13,
shift: false
};
_keys['shift'] = {
code: 16,
shift: undefined
};
_keys['esc'] = {
code: 27,
shift: false
};
_keys['backspace'] = {
code: 8,
shift: false
};
_keys['tab'] = {
code: 9,
shift: false
};
_keys['ctrl'] = {
code: 17,
shift: false
};
_keys['alt'] = {
code: 18,
shift: false
};
_keys['delete'] = {
code: 46,
shift: false
};
_keys['pageup'] = {
code: 33,
shift: false
};
_keys['pagedown'] = {
code: 34,
shift: false
};
// symbols
_keys['='] = {
code: 187,
shift: false
};
_keys['-'] = {
code: 189,
shift: false
};
_keys[']'] = {
code: 221,
shift: false
};
_keys['['] = {
code: 219,
shift: false
};
var down = function (event) {
handleEvent(event, 'keydown');
};
var up = function (event) {
handleEvent(event, 'keyup');
};
// handle the actualy bound key with the event
var handleEvent = function (event, type) {
if (_bound[type][event.keyCode] !== undefined) {
var bound = _bound[type][event.keyCode];
for (var i = 0; i < bound.length; i++) {
if (bound[i].shift === undefined) {
bound[i].fn(event);
} else if (bound[i].shift == true && event.shiftKey == true) {
bound[i].fn(event);
} else if (bound[i].shift == false && event.shiftKey == false) {
bound[i].fn(event);
}
}
if (preventDefault == true) {
event.preventDefault();
}
}
};
// bind a key to a callback
_exportFunctions.bind = function (key, callback, type) {
if (type === undefined) {
type = 'keydown';
}
if (_keys[key] === undefined) {
throw new Error("unsupported key: " + key);
}
if (_bound[type][_keys[key].code] === undefined) {
_bound[type][_keys[key].code] = [];
}
_bound[type][_keys[key].code].push({
fn: callback,
shift: _keys[key].shift
});
};
// bind all keys to a call back (demo purposes)
_exportFunctions.bindAll = function (callback, type) {
if (type === undefined) {
type = 'keydown';
}
for (var key in _keys) {
if (_keys.hasOwnProperty(key)) {
_exportFunctions.bind(key, callback, type);
}
}
};
// get the key label from an event
_exportFunctions.getKey = function (event) {
for (var key in _keys) {
if (_keys.hasOwnProperty(key)) {
if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
return key;
} else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
return key;
} else if (event.keyCode == _keys[key].code && key == 'shift') {
return key;
}
}
}
return "unknown key, currently not supported";
};
// unbind either a specific callback from a key or all of them (by leaving callback undefined)
_exportFunctions.unbind = function (key, callback, type) {
if (type === undefined) {
type = 'keydown';
}
if (_keys[key] === undefined) {
throw new Error("unsupported key: " + key);
}
if (callback !== undefined) {
var newBindings = [];
var bound = _bound[type][_keys[key].code];
if (bound !== undefined) {
for (var i = 0; i < bound.length; i++) {
if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
newBindings.push(_bound[type][_keys[key].code][i]);
}
}
}
_bound[type][_keys[key].code] = newBindings;
} else {
_bound[type][_keys[key].code] = [];
}
};
// reset all bound variables.
_exportFunctions.reset = function () {
_bound = {
keydown: {},
keyup: {}
};
};
// unbind all listeners and reset all variables.
_exportFunctions.destroy = function () {
_bound = {
keydown: {},
keyup: {}
};
container.removeEventListener('keydown', down, true);
container.removeEventListener('keyup', up, true);
};
// create listeners.
container.addEventListener('keydown', down, true);
container.addEventListener('keyup', up, true);
// return the public functions.
return _exportFunctions;
}
return keycharm;
});
});
function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x;}// first check if moment.js is already loaded in the browser window, if so,
// use this instance. Else, load via commonjs.
//
// Note: This doesn't work in ESM.
var moment$2=typeof window!=='undefined'&&window['moment']||moment$4;var moment$3=/*@__PURE__*/getDefaultExportFromCjs(moment$2);// utility functions
/**
* Test if an object implements the DataView interface from vis-data.
* Uses the idProp property instead of expecting a hardcoded id field "id".
*/function isDataViewLike(obj){var _obj$idProp;if(!obj){return false;}let idProp=(_obj$idProp=obj.idProp)!==null&&_obj$idProp!==void 0?_obj$idProp:obj._idProp;if(!idProp){return false;}return isDataViewLike$1(idProp,obj);}// parse ASP.Net Date pattern,
// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
// code from http://momentjs.com/
const ASPDateRegex=/^\/?Date\((-?\d+)/i;const NumericRegex=/^\d+$/;/**
* Convert an object into another type
*
* @param object - Value of unknown type.
* @param type - Name of the desired type.
*
* @returns Object in the desired type.
* @throws Error
*/function convert(object,type){let match;if(object===undefined){return undefined;}if(object===null){return null;}if(!type){return object;}if(!(typeof type==="string")&&!(type instanceof String)){throw new Error("Type must be a string");}//noinspection FallthroughInSwitchStatementJS
switch(type){case"boolean":case"Boolean":return Boolean(object);case"number":case"Number":if(isString(object)&&!isNaN(Date.parse(object))){return moment$4(object).valueOf();}else {// @TODO: I don't think that Number and String constructors are a good idea.
// This could also fail if the object doesn't have valueOf method or if it's redefined.
// For example: Object.create(null) or { valueOf: 7 }.
return Number(object.valueOf());}case"string":case"String":return String(object);case"Date":try{return convert(object,"Moment").toDate();}catch(e){if(e instanceof TypeError){throw new TypeError("Cannot convert object of type "+getType(object)+" to type "+type);}else {throw e;}}case"Moment":if(isNumber(object)){return moment$4(object);}if(object instanceof Date){return moment$4(object.valueOf());}else if(moment$4.isMoment(object)){return moment$4(object);}if(isString(object)){match=ASPDateRegex.exec(object);if(match){// object is an ASP date
return moment$4(Number(match[1]));// parse number
}match=NumericRegex.exec(object);if(match){return moment$4(Number(object));}return moment$4(object);// parse string
}else {throw new TypeError("Cannot convert object of type "+getType(object)+" to type "+type);}case"ISODate":if(isNumber(object)){return new Date(object);}else if(object instanceof Date){return object.toISOString();}else if(moment$4.isMoment(object)){return object.toDate().toISOString();}else if(isString(object)){match=ASPDateRegex.exec(object);if(match){// object is an ASP date
return new Date(Number(match[1])).toISOString();// parse number
}else {return moment$4(object).format();// ISO 8601
}}else {throw new Error("Cannot convert object of type "+getType(object)+" to type ISODate");}case"ASPDate":if(isNumber(object)){return "/Date("+object+")/";}else if(object instanceof Date||moment$4.isMoment(object)){return "/Date("+object.valueOf()+")/";}else if(isString(object)){match=ASPDateRegex.exec(object);let value;if(match){// object is an ASP date
value=new Date(Number(match[1])).valueOf();// parse number
}else {value=new Date(object).valueOf();// parse string
}return "/Date("+value+")/";}else {throw new Error("Cannot convert object of type "+getType(object)+" to type ASPDate");}default:throw new Error(`Unknown type ${type}`);}}/**
* Create a Data Set like wrapper to seamlessly coerce data types.
*
* @param rawDS - The Data Set with raw uncoerced data.
* @param type - A record assigning a data type to property name.
*
* @remarks
* The write operations (`add`, `remove`, `update` and `updateOnly`) write into
* the raw (uncoerced) data set. These values are then picked up by a pipe
* which coerces the values using the [[convert]] function and feeds them into
* the coerced data set. When querying (`forEach`, `get`, `getIds`, `off` and
* `on`) the values are then fetched from the coerced data set and already have
* the required data types. The values are coerced only once when inserted and
* then the same value is returned each time until it is updated or deleted.
*
* For example: `typeCoercedDataSet.add({ id: 7, start: "2020-01-21" })` would
* result in `typeCoercedDataSet.get(7)` returning `{ id: 7, start: moment(new
* Date("2020-01-21")).toDate() }`.
*
* Use the dispose method prior to throwing a reference to this away. Otherwise
* the pipe connecting the two Data Sets will keep the unaccessible coerced
* Data Set alive and updated as long as the raw Data Set exists.
*
* @returns A Data Set like object that saves data into the raw Data Set and
* retrieves them from the coerced Data Set.
*/function typeCoerceDataSet(rawDS,type={start:"Date",end:"Date"}){const idProp=rawDS._idProp;const coercedDS=new DataSet({fieldId:idProp});const pipe=createNewDataPipeFrom(rawDS).map(item=>Object.keys(item).reduce((acc,key)=>{acc[key]=convert(item[key],type[key]);return acc;},{})).to(coercedDS);pipe.all().start();return {// Write only.
add:(...args)=>rawDS.getDataSet().add(...args),remove:(...args)=>rawDS.getDataSet().remove(...args),update:(...args)=>rawDS.getDataSet().update(...args),updateOnly:(...args)=>rawDS.getDataSet().updateOnly(...args),clear:(...args)=>rawDS.getDataSet().clear(...args),// Read only.
forEach:coercedDS.forEach.bind(coercedDS),get:coercedDS.get.bind(coercedDS),getIds:coercedDS.getIds.bind(coercedDS),off:coercedDS.off.bind(coercedDS),on:coercedDS.on.bind(coercedDS),get length(){return coercedDS.length;},// Non standard.
idProp,type,rawDS,coercedDS,dispose:()=>pipe.stop()};}// Configure XSS protection
const setupXSSCleaner=options=>{const customXSS=new lib.FilterXSS(options);return string=>customXSS.process(string);};const setupNoOpCleaner=string=>string;// when nothing else is configured: filter XSS with the lib's default options
let configuredXSSProtection=setupXSSCleaner();const setupXSSProtection=options=>{// No options? Do nothing.
if(!options){return;}// Disable XSS protection completely on request
if(options.disabled===true){configuredXSSProtection=setupNoOpCleaner;console.warn('You disabled XSS protection for vis-Timeline. I sure hope you know what you\'re doing!');}else {// Configure XSS protection with some custom options.
// For a list of valid options check the lib's documentation:
// https://github.com/leizongmin/js-xss#custom-filter-rules
if(options.filterOptions){configuredXSSProtection=setupXSSCleaner(options.filterOptions);}}};const availableUtils={...util$2,convert,setupXSSProtection};Object.defineProperty(availableUtils,'xss',{get:function(){return configuredXSSProtection;}});/** Prototype for visual components */class Component{/**
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
* @param {Object} [options]
*/constructor(body,options){// eslint-disable-line no-unused-vars
this.options=null;this.props=null;}/**
* Set options for the component. The new options will be merged into the
* current options.
* @param {Object} options
*/setOptions(options){if(options){availableUtils.extend(this.options,options);}}/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/redraw(){// should be implemented by the component
return false;}/**
* Destroy the component. Cleanup DOM and event listeners
*/destroy(){// should be implemented by the component
}/**
* Test whether the component is resized since the last time _isResized() was
* called.
* @return {Boolean} Returns true if the component is resized
* @protected
*/_isResized(){const resized=this.props._previousWidth!==this.props.width||this.props._previousHeight!==this.props.height;this.props._previousWidth=this.props.width;this.props._previousHeight=this.props.height;return resized;}}/**
* used in Core to convert the options into a volatile variable
*
* @param {function} moment
* @param {Object} body
* @param {Array | Object} hiddenDates
* @returns {number}
*/function convertHiddenOptions(moment,body,hiddenDates){if(hiddenDates&&!Array.isArray(hiddenDates)){return convertHiddenOptions(moment,body,[hiddenDates]);}body.hiddenDates=[];if(hiddenDates){if(Array.isArray(hiddenDates)==true){for(let i=0;i<hiddenDates.length;i++){if(hiddenDates[i].repeat===undefined){const dateItem={};dateItem.start=moment(hiddenDates[i].start).toDate().valueOf();dateItem.end=moment(hiddenDates[i].end).toDate().valueOf();body.hiddenDates.push(dateItem);}}body.hiddenDates.sort((a,b)=>a.start-b.start);// sort by start time
}}}/**
* create new entrees for the repeating hidden dates
*
* @param {function} moment
* @param {Object} body
* @param {Array | Object} hiddenDates
* @returns {null}
*/function updateHiddenDates(moment,body,hiddenDates){if(hiddenDates&&!Array.isArray(hiddenDates)){return updateHiddenDates(moment,body,[hiddenDates]);}if(hiddenDates&&body.domProps.centerContainer.width!==undefined){convertHiddenOptions(moment,body,hiddenDates);const start=moment(body.range.start);const end=moment(body.range.end);const totalRange=body.range.end-body.range.start;const pixelTime=totalRange/body.domProps.centerContainer.width;for(let i=0;i<hiddenDates.length;i++){if(hiddenDates[i].repeat!==undefined){const startDate=moment(hiddenDates[i].start);let endDate=moment(hiddenDates[i].end);if(startDate._d=="Invalid Date"){throw new Error(`Supplied start date is not valid: ${hiddenDates[i].start}`);}if(endDate._d=="Invalid Date"){throw new Error(`Supplied end date is not valid: ${hiddenDates[i].end}`);}const duration=endDate-startDate;if(duration>=4*pixelTime){let offset=0;const runUntil=end.clone();switch(hiddenDates[i].repeat){case"daily":// case of time
if(startDate.day()!=endDate.day()){offset=1;}startDate.dayOfYear(start.dayOfYear());startDate.year(start.year());startDate.subtract(7,'days');endDate.dayOfYear(start.dayOfYear());endDate.year(start.year());endDate.subtract(7-offset,'days');runUntil.add(1,'weeks');break;case"weekly":{const dayOffset=endDate.diff(startDate,'days');const day=startDate.day();// set the start date to the range.start
startDate.date(start.date());startDate.month(start.month());startDate.year(start.year());endDate=startDate.clone();// force
startDate.day(day);endDate.day(day);endDate.add(dayOffset,'days');startDate.subtract(1,'weeks');endDate.subtract(1,'weeks');runUntil.add(1,'weeks');break;}case"monthly":if(startDate.month()!=endDate.month()){offset=1;}startDate.month(start.month());startDate.year(start.year());startDate.subtract(1,'months');endDate.month(start.month());endDate.year(start.year());endDate.subtract(1,'months');endDate.add(offset,'months');runUntil.add(1,'months');break;case"yearly":if(startDate.year()!=endDate.year()){offset=1;}startDate.year(start.year());startDate.subtract(1,'years');endDate.year(start.year());endDate.subtract(1,'years');endDate.add(offset,'years');runUntil.add(1,'years');break;default:console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:",hiddenDates[i].repeat);return;}while(startDate<runUntil){body.hiddenDates.push({start:startDate.valueOf(),end:endDate.valueOf()});switch(hiddenDates[i].repeat){case"daily":startDate.add(1,'days');endDate.add(1,'days');break;case"weekly":startDate.add(1,'weeks');endDate.add(1,'weeks');break;case"monthly":startDate.add(1,'months');endDate.add(1,'months');break;case"yearly":startDate.add(1,'y');endDate.add(1,'y');break;default:console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:",hiddenDates[i].repeat);return;}}body.hiddenDates.push({start:startDate.valueOf(),end:endDate.valueOf()});}}}// remove duplicates, merge where possible
removeDuplicates(body);// ensure the new positions are not on hidden dates
const startHidden=getIsHidden(body.range.start,body.hiddenDates);const endHidden=getIsHidden(body.range.end,body.hiddenDates);let rangeStart=body.range.start;let rangeEnd=body.range.end;if(startHidden.hidden==true){rangeStart=body.range.startToFront==true?startHidden.startDate-1:startHidden.endDate+1;}if(endHidden.hidden==true){rangeEnd=body.range.endToFront==true?endHidden.startDate-1:endHidden.endDate+1;}if(startHidden.hidden==true||endHidden.hidden==true){body.range._applyRange(rangeStart,rangeEnd);}}}/**
* remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
* Scales with N^2
*
* @param {Object} body
*/function removeDuplicates(body){const hiddenDates=body.hiddenDates;const safeDates=[];for(var i=0;i<hiddenDates.length;i++){for(let j=0;j<hiddenDates.length;j++){if(i!=j&&hiddenDates[j].remove!=true&&hiddenDates[i].remove!=true){// j inside i
if(hiddenDates[j].start>=hiddenDates[i].start&&hiddenDates[j].end<=hiddenDates[i].end){hiddenDates[j].remove=true;}// j start inside i
else if(hiddenDates[j].start>=hiddenDates[i].start&&hiddenDates[j].start<=hiddenDates[i].end){hiddenDates[i].end=hiddenDates[j].end;hiddenDates[j].remove=true;}// j end inside i
else if(hiddenDates[j].end>=hiddenDates[i].start&&hiddenDates[j].end<=hiddenDates[i].end){hiddenDates[i].start=hiddenDates[j].start;hiddenDates[j].remove=true;}}}}for(i=0;i<hiddenDates.length;i++){if(hiddenDates[i].remove!==true){safeDates.push(hiddenDates[i]);}}body.hiddenDates=safeDates;body.hiddenDates.sort((a,b)=>a.start-b.start);// sort by start time
}/**
* Used in TimeStep to avoid the hidden times.
* @param {function} moment
* @param {TimeStep} timeStep
* @param {Date} previousTime
*/function stepOverHiddenDates(moment,timeStep,previousTime){let stepInHidden=false;const currentValue=timeStep.current.valueOf();for(let i=0;i<timeStep.hiddenDates.length;i++){const startDate=timeStep.hiddenDates[i].start;var endDate=timeStep.hiddenDates[i].end;if(currentValue>=startDate&¤tValue<endDate){stepInHidden=true;break;}}if(stepInHidden==true&¤tValue<timeStep._end.valueOf()&¤tValue!=previousTime){const prevValue=moment(previousTime);const newValue=moment(endDate);//check if the next step should be major
if(prevValue.year()!=newValue.year()){timeStep.switchedYear=true;}else if(prevValue.month()!=newValue.month()){timeStep.switchedMonth=true;}else if(prevValue.dayOfYear()!=newValue.dayOfYear()){timeStep.switchedDay=true;}timeStep.current=newValue;}}///**
// * Used in TimeStep to avoid the hidden times.
// * @param timeStep
// * @param previousTime
// */
//checkFirstStep = function(timeStep) {
// var stepInHidden = false;
// var currentValue = timeStep.current.valueOf();
// for (var i = 0; i < timeStep.hiddenDates.length; i++) {
// var startDate = timeStep.hiddenDates[i].start;
// var endDate = timeStep.hiddenDates[i].end;
// if (currentValue >= startDate && currentValue < endDate) {
// stepInHidden = true;
// break;
// }
// }
//
// if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
// var newValue = moment(endDate);
// timeStep.current = newValue.toDate();
// }
//};
/**
* replaces the Core toScreen methods
*
* @param {timeline.Core} Core
* @param {Date} time
* @param {number} width
* @returns {number}
*/function toScreen(Core,time,width){let conversion;if(Core.body.hiddenDates.length==0){conversion=Core.range.conversion(width);return (time.valueOf()-conversion.offset)*conversion.scale;}else {const hidden=getIsHidden(time,Core.body.hiddenDates);if(hidden.hidden==true){time=hidden.startDate;}const duration=getHiddenDurationBetween(Core.body.hiddenDates,Core.range.start,Core.range.end);if(time<Core.range.start){conversion=Core.range.conversion(width,duration);const hiddenBeforeStart=getHiddenDurationBeforeStart(Core.body.hiddenDates,time,conversion.offset);time=Core.options.moment(time).toDate().valueOf();time=time+hiddenBeforeStart;return -(conversion.offset-time.valueOf())*conversion.scale;}else if(time>Core.range.end){const rangeAfterEnd={start:Core.range.start,end:time};time=correctTimeForHidden(Core.options.moment,Core.body.hiddenDates,rangeAfterEnd,time);conversion=Core.range.conversion(width,duration);return (time.valueOf()-conversion.offset)*conversion.scale;}else {time=correctTimeForHidden(Core.options.moment,Core.body.hiddenDates,Core.range,time);conversion=Core.range.conversion(width,duration);return (time.valueOf()-conversion.offset)*conversion.scale;}}}/**
* Replaces the core toTime methods
*
* @param {timeline.Core} Core
* @param {number} x
* @param {number} width
* @returns {Date}
*/function toTime(Core,x,width){if(Core.body.hiddenDates.length==0){const conversion=Core.range.conversion(width);return new Date(x/conversion.scale+conversion.offset);}else {const hiddenDuration=getHiddenDurationBetween(Core.body.hiddenDates,Core.range.start,Core.range.end);const totalDuration=Core.range.end-Core.range.start-hiddenDuration;const partialDuration=totalDuration*x/width;const accumulatedHiddenDuration=getAccumulatedHiddenDuration(Core.body.hiddenDates,Core.range,partialDuration);return new Date(accumulatedHiddenDuration+partialDuration+Core.range.start);}}/**
* Support function
*
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {number} start
* @param {number} end
* @returns {number}
*/function getHiddenDurationBetween(hiddenDates,start,end){let duration=0;for(let i=0;i<hiddenDates.length;i++){const startDate=hiddenDates[i].start;const endDate=hiddenDates[i].end;// if time after the cutout, and the
if(startDate>=start&&endDate<end){duration+=endDate-startDate;}}return duration;}/**
* Support function
*
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {number} start
* @param {number} end
* @returns {number}
*/function getHiddenDurationBeforeStart(hiddenDates,start,end){let duration=0;for(let i=0;i<hiddenDates.length;i++){const startDate=hiddenDates[i].start;const endDate=hiddenDates[i].end;if(startDate>=start&&endDate<=end){duration+=endDate-startDate;}}return duration;}/**
* Support function
* @param {function} moment
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {{start: number, end: number}} range
* @param {Date} time
* @returns {number}
*/function correctTimeForHidden(moment,hiddenDates,range,time){time=moment(time).toDate().valueOf();time-=getHiddenDurationBefore(moment,hiddenDates,range,time);return time;}/**
* Support function
* @param {function} moment
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {{start: number, end: number}} range
* @param {Date} time
* @returns {number}
*/function getHiddenDurationBefore(moment,hiddenDates,range,time){let timeOffset=0;time=moment(time).toDate().valueOf();for(let i=0;i<hiddenDates.length;i++){const startDate=hiddenDates[i].start;const endDate=hiddenDates[i].end;// if time after the cutout, and the
if(startDate>=range.start&&endDate<range.end){if(time>=endDate){timeOffset+=endDate-startDate;}}}return timeOffset;}/**
* sum the duration from start to finish, including the hidden duration,
* until the required amount has been reached, return the accumulated hidden duration
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {{start: number, end: number}} range
* @param {number} [requiredDuration=0]
* @returns {number}
*/function getAccumulatedHiddenDuration(hiddenDates,range,requiredDuration){let hiddenDuration=0;let duration=0;let previousPoint=range.start;//printDates(hiddenDates)
for(let i=0;i<hiddenDates.length;i++){const startDate=hiddenDates[i].start;const endDate=hiddenDates[i].end;// if time after the cutout, and the
if(startDate>=range.start&&endDate<range.end){duration+=startDate-previousPoint;previousPoint=endDate;if(duration>=requiredDuration){break;}else {hiddenDuration+=endDate-startDate;}}}return hiddenDuration;}/**
* used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {Date} time
* @param {number} direction
* @param {boolean} correctionEnabled
* @returns {Date|number}
*/function snapAwayFromHidden(hiddenDates,time,direction,correctionEnabled){const isHidden=getIsHidden(time,hiddenDates);if(isHidden.hidden==true){if(direction<0){if(correctionEnabled==true){return isHidden.startDate-(isHidden.endDate-time)-1;}else {return isHidden.startDate-1;}}else {if(correctionEnabled==true){return isHidden.endDate+(time-isHidden.startDate)+1;}else {return isHidden.endDate+1;}}}else {return time;}}/**
* Check if a time is hidden
*
* @param {Date} time
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
*/function getIsHidden(time,hiddenDates){for(let i=0;i<hiddenDates.length;i++){var startDate=hiddenDates[i].start;var endDate=hiddenDates[i].end;if(time>=startDate&&time<endDate){// if the start is entering a hidden zone
return {hidden:true,startDate,endDate};}}return {hidden:false,startDate,endDate};}/**
* A Range controls a numeric range with a start and end value.
* The Range adjusts the range based on mouse events or programmatic changes,
* and triggers events when the range is changing or has been changed.
*/class Range extends Component{/**
* @param {{dom: Object, domProps: Object, emitter: Emitter}} body
* @param {Object} [options] See description at Range.setOptions
* @constructor Range
* @extends Component
*/constructor(body,options){super();const now=moment$3().hours(0).minutes(0).seconds(0).milliseconds(0);const start=now.clone().add(-3,'days').valueOf();const end=now.clone().add(3,'days').valueOf();this.millisecondsPerPixelCache=undefined;if(options===undefined){this.start=start;this.end=end;}else {this.start=options.start||start;this.end=options.end||end;}this.rolling=false;this.body=body;this.deltaDifference=0;this.scaleOffset=0;this.startToFront=false;this.endToFront=true;// default options
this.defaultOptions={rtl:false,start:null,end:null,moment:moment$3,direction:'horizontal',// 'horizontal' or 'vertical'
moveable:true,zoomable:true,min:null,max:null,zoomMin:10,// milliseconds
zoomMax:1000*60*60*24*365*10000,// milliseconds
rollingMode:{follow:false,offset:0.5}};this.options=availableUtils.extend({},this.defaultOptions);this.props={touch:{}};this.animationTimer=null;// drag listeners for dragging
this.body.emitter.on('panstart',this._onDragStart.bind(this));this.body.emitter.on('panmove',this._onDrag.bind(this));this.body.emitter.on('panend',this._onDragEnd.bind(this));// mouse wheel for zooming
this.body.emitter.on('mousewheel',this._onMouseWheel.bind(this));// pinch to zoom
this.body.emitter.on('touch',this._onTouch.bind(this));this.body.emitter.on('pinch',this._onPinch.bind(this));// on click of rolling mode button
this.body.dom.rollingModeBtn.addEventListener('click',this.startRolling.bind(this));this.setOptions(options);}/**
* Set options for the range controller
* @param {Object} options Available options:
* {number | Date | String} start Start date for the range
* {number | Date | String} end End date for the range
* {number} min Minimum value for start
* {number} max Maximum value for end
* {number} zoomMin Set a minimum value for
* (end - start).
* {number} zoomMax Set a maximum value for
* (end - start).
* {boolean} moveable Enable moving of the range
* by dragging. True by default
* {boolean} zoomable Enable zooming of the range
* by pinching/scrolling. True by default
*/setOptions(options){if(options){// copy the options that we know
const fields=['animation','direction','min','max','zoomMin','zoomMax','moveable','zoomable','moment','activate','hiddenDates','zoomKey','zoomFriction','rtl','showCurrentTime','rollingMode','horizontalScroll'];availableUtils.selectiveExtend(fields,this.options,options);if(options.rollingMode&&options.rollingMode.follow){this.startRolling();}if('start'in options||'end'in options){// apply a new range. both start and end are optional
this.setRange(options.start,options.end);}}}/**
* Start auto refreshing the current time bar
*/startRolling(){const me=this;/**
* Updates the current time.
*/function update(){me.stopRolling();me.rolling=true;let interval=me.end-me.start;const t=availableUtils.convert(new Date(),'Date').valueOf();const rollingModeOffset=me.options.rollingMode&&me.options.rollingMode.offset||0.5;const start=t-interval*rollingModeOffset;const end=t+interval*(1-rollingModeOffset);const options={animation:false};me.setRange(start,end,options);// determine interval to refresh
const scale=me.conversion(me.body.domProps.center.width).scale;interval=1/scale/10;if(interval<30)interval=30;if(interval>1000)interval=1000;me.body.dom.rollingModeBtn.style.visibility="hidden";// start a renderTimer to adjust for the new time
me.currentTimeTimer=setTimeout(update,interval);}update();}/**
* Stop auto refreshing the current time bar
*/stopRolling(){if(this.currentTimeTimer!==undefined){clearTimeout(this.currentTimeTimer);this.rolling=false;this.body.dom.rollingModeBtn.style.visibility="visible";}}/**
* Set a new start and end range
* @param {Date | number | string} start
* @param {Date | number | string} end
* @param {Object} options Available options:
* {boolean | {duration: number, easingFunction: string}} [animation=false]
* If true, the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* {boolean} [byUser=false]
* {Event} event Mouse event
* @param {Function} callback a callback function to be executed at the end of this function
* @param {Function} frameCallback a callback function executed each frame of the range animation.
* The callback will be passed three parameters:
* {number} easeCoefficient an easing coefficent
* {boolean} willDraw If true the caller will redraw after the callback completes
* {boolean} done If true then animation is ending after the current frame
* @return {void}
*/setRange(start,end,options,callback,frameCallback){if(!options){options={};}if(options.byUser!==true){options.byUser=false;}const me=this;const finalStart=start!=undefined?availableUtils.convert(start,'Date').valueOf():null;const finalEnd=end!=undefined?availableUtils.convert(end,'Date').valueOf():null;this._cancelAnimation();this.millisecondsPerPixelCache=undefined;if(options.animation){// true or an Object
const initStart=this.start;const initEnd=this.end;const duration=typeof options.animation==='object'&&'duration'in options.animation?options.animation.duration:500;const easingName=typeof options.animation==='object'&&'easingFunction'in options.animation?options.animation.easingFunction:'easeInOutQuad';const easingFunction=availableUtils.easingFunctions[easingName];if(!easingFunction){throw new Error(`Unknown easing function ${JSON.stringify(easingName)}. Choose from: ${Object.keys(availableUtils.easingFunctions).join(', ')}`);}const initTime=Date.now();let anyChanged=false;const next=()=>{if(!me.props.touch.dragging){const now=Date.now();const time=now-initTime;const ease=easingFunction(time/duration);const done=time>duration;const s=done||finalStart===null?finalStart:initStart+(finalStart-initStart)*ease;const e=done||finalEnd===null?finalEnd:initEnd+(finalEnd-initEnd)*ease;changed=me._applyRange(s,e);updateHiddenDates(me.options.moment,me.body,me.options.hiddenDates);anyChanged=anyChanged||changed;const params={start:new Date(me.start),end:new Date(me.end),byUser:options.byUser,event:options.event};if(frameCallback){frameCallback(ease,changed,done);}if(changed){me.body.emitter.emit('rangechange',params);}if(done){if(anyChanged){me.body.emitter.emit('rangechanged',params);if(callback){return callback();}}}else {// animate with as high as possible frame rate, leave 20 ms in between
// each to prevent the browser from blocking
me.animationTimer=setTimeout(next,20);}}};return next();}else {var changed=this._applyRange(finalStart,finalEnd);updateHiddenDates(this.options.moment,this.body,this.options.hiddenDates);if(changed){const params={start:new Date(this.start),end:new Date(this.end),byUser:options.byUser,event:options.event};this.body.emitter.emit('rangechange',params);clearTimeout(me.timeoutID);me.timeoutID=setTimeout(()=>{me.body.emitter.emit('rangechanged',params);},200);if(callback){return callback();}}}}/**
* Get the number of milliseconds per pixel.
*
* @returns {undefined|number}
*/getMillisecondsPerPixel(){if(this.millisecondsPerPixelCache===undefined){this.millisecondsPerPixelCache=(this.end-this.start)/this.body.dom.center.clientWidth;}return this.millisecondsPerPixelCache;}/**
* Stop an animation
* @private
*/_cancelAnimation(){if(this.animationTimer){clearTimeout(this.animationTimer);this.animationTimer=null;}}/**
* Set a new start and end range. This method is the same as setRange, but
* does not trigger a range change and range changed event, and it returns
* true when the range is changed
* @param {number} [start]
* @param {number} [end]
* @return {boolean} changed
* @private
*/_applyRange(start,end){let newStart=start!=null?availableUtils.convert(start,'Date').valueOf():this.start;let newEnd=end!=null?availableUtils.convert(end,'Date').valueOf():this.end;const max=this.options.max!=null?availableUtils.convert(this.options.max,'Date').valueOf():null;const min=this.options.min!=null?availableUtils.convert(this.options.min,'Date').valueOf():null;let diff;// check for valid number
if(isNaN(newStart)||newStart===null){throw new Error(`Invalid start "${start}"`);}if(isNaN(newEnd)||newEnd===null){throw new Error(`Invalid end "${end}"`);}// prevent end < start
if(newEnd<newStart){newEnd=newStart;}// prevent start < min
if(min!==null){if(newStart<min){diff=min-newStart;newStart+=diff;newEnd+=diff;// prevent end > max
if(max!=null){if(newEnd>max){newEnd=max;}}}}// prevent end > max
if(max!==null){if(newEnd>max){diff=newEnd-max;newStart-=diff;newEnd-=diff;// prevent start < min
if(min!=null){if(newStart<min){newStart=min;}}}}// prevent (end-start) < zoomMin
if(this.options.zoomMin!==null){let zoomMin=parseFloat(this.options.zoomMin);if(zoomMin<0){zoomMin=0;}if(newEnd-newStart<zoomMin){// compensate for a scale of 0.5 ms
const compensation=0.5;if(this.end-this.start===zoomMin&&newStart>=this.start-compensation&&newEnd<=this.end){// ignore this action, we are already zoomed to the minimum
newStart=this.start;newEnd=this.end;}else {// zoom to the minimum
diff=zoomMin-(newEnd-newStart);newStart-=diff/2;newEnd+=diff/2;}}}// prevent (end-start) > zoomMax
if(this.options.zoomMax!==null){let zoomMax=parseFloat(this.options.zoomMax);if(zoomMax<0){zoomMax=0;}if(newEnd-newStart>zoomMax){if(this.end-this.start===zoomMax&&newStart<this.start&&newEnd>this.end){// ignore this action, we are already zoomed to the maximum
newStart=this.start;newEnd=this.end;}else {// zoom to the maximum
diff=newEnd-newStart-zoomMax;newStart+=diff/2;newEnd-=diff/2;}}}const changed=this.start!=newStart||this.end!=newEnd;// if the new range does NOT overlap with the old range, emit checkRangedItems to avoid not showing ranged items (ranged meaning has end time, not necessarily of type Range)
if(!(newStart>=this.start&&newStart<=this.end||newEnd>=this.start&&newEnd<=this.end)&&!(this.start>=newStart&&this.start<=newEnd||this.end>=newStart&&this.end<=newEnd)){this.body.emitter.emit('checkRangedItems');}this.start=newStart;this.end=newEnd;return changed;}/**
* Retrieve the current range.
* @return {Object} An object with start and end properties
*/getRange(){return {start:this.start,end:this.end};}/**
* Calculate the conversion offset and scale for current range, based on
* the provided width
* @param {number} width
* @param {number} [totalHidden=0]
* @returns {{offset: number, scale: number}} conversion
*/conversion(width,totalHidden){return Range.conversion(this.start,this.end,width,totalHidden);}/**
* Static method to calculate the conversion offset and scale for a range,
* based on the provided start, end, and width
* @param {number} start
* @param {number} end
* @param {number} width
* @param {number} [totalHidden=0]
* @returns {{offset: number, scale: number}} conversion
*/static conversion(start,end,width,totalHidden){if(totalHidden===undefined){totalHidden=0;}if(width!=0&&end-start!=0){return {offset:start,scale:width/(end-start-totalHidden)};}else {return {offset:0,scale:1};}}/**
* Start dragging horizontally or vertically
* @param {Event} event
* @private
*/_onDragStart(event){this.deltaDifference=0;this.previousDelta=0;// only allow dragging when configured as movable
if(!this.options.moveable)return;// only start dragging when the mouse is inside the current range
if(!this._isInsideRange(event))return;// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if(!this.props.touch.allowDragging)return;this.stopRolling();this.props.touch.start=this.start;this.props.touch.end=this.end;this.props.touch.dragging=true;if(this.body.dom.root){this.body.dom.root.style.cursor='move';}}/**
* Perform dragging operation
* @param {Event} event
* @private
*/_onDrag(event){if(!event)return;if(!this.props.touch.dragging)return;// only allow dragging when configured as movable
if(!this.options.moveable)return;// TODO: this may be redundant in hammerjs2
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if(!this.props.touch.allowDragging)return;const direction=this.options.direction;validateDirection(direction);let delta=direction=='horizontal'?event.deltaX:event.deltaY;delta-=this.deltaDifference;let interval=this.props.touch.end-this.props.touch.start;// normalize dragging speed if cutout is in between.
const duration=getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end);interval-=duration;const width=direction=='horizontal'?this.body.domProps.center.width:this.body.domProps.center.height;let diffRange;if(this.options.rtl){diffRange=delta/width*interval;}else {diffRange=-delta/width*interval;}const newStart=this.props.touch.start+diffRange;const newEnd=this.props.touch.end+diffRange;// snapping times away from hidden zones
const safeStart=snapAwayFromHidden(this.body.hiddenDates,newStart,this.previousDelta-delta,true);const safeEnd=snapAwayFromHidden(this.body.hiddenDates,newEnd,this.previousDelta-delta,true);if(safeStart!=newStart||safeEnd!=newEnd){this.deltaDifference+=delta;this.props.touch.start=safeStart;this.props.touch.end=safeEnd;this._onDrag(event);return;}this.previousDelta=delta;this._applyRange(newStart,newEnd);const startDate=new Date(this.start);const endDate=new Date(this.end);// fire a rangechange event
this.body.emitter.emit('rangechange',{start:startDate,end:endDate,byUser:true,event});// fire a panmove event
this.body.emitter.emit('panmove');}/**
* Stop dragging operation
* @param {event} event
* @private
*/_onDragEnd(event){if(!this.props.touch.dragging)return;// only allow dragging when configured as movable
if(!this.options.moveable)return;// TODO: this may be redundant in hammerjs2
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if(!this.props.touch.allowDragging)return;this.props.touch.dragging=false;if(this.body.dom.root){this.body.dom.root.style.cursor='auto';}// fire a rangechanged event
this.body.emitter.emit('rangechanged',{start:new Date(this.start),end:new Date(this.end),byUser:true,event});}/**
* Event handler for mouse wheel event, used to zoom
* Code from http://adomas.org/javascript-mouse-wheel/
* @param {Event} event
* @private
*/_onMouseWheel(event){// retrieve delta
let delta=0;if(event.wheelDelta){/* IE/Opera. */delta=event.wheelDelta/120;}else if(event.detail){/* Mozilla case. */ // In Mozilla, sign of delta is different than in IE.
// Also, delta is multiple of 3.
delta=-event.detail/3;}else if(event.deltaY){delta=-event.deltaY/3;}// don't allow zoom when the according key is pressed and the zoomKey option or not zoomable but movable
if(this.options.zoomKey&&!event[this.options.zoomKey]&&this.options.zoomable||!this.options.zoomable&&this.options.moveable){return;}// only allow zooming when configured as zoomable and moveable
if(!(this.options.zoomable&&this.options.moveable))return;// only zoom when the mouse is inside the current range
if(!this._isInsideRange(event))return;// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if(delta){// perform the zoom action. Delta is normally 1 or -1
// adjust a negative delta such that zooming in with delta 0.1
// equals zooming out with a delta -0.1
const zoomFriction=this.options.zoomFriction||5;let scale;if(delta<0){scale=1-delta/zoomFriction;}else {scale=1/(1+delta/zoomFriction);}// calculate center, the date to zoom around
let pointerDate;if(this.rolling){const rollingModeOffset=this.options.rollingMode&&this.options.rollingMode.offset||0.5;pointerDate=this.start+(this.end-this.start)*rollingModeOffset;}else {const pointer=this.getPointer({x:event.clientX,y:event.clientY},this.body.dom.center);pointerDate=this._pointerToDate(pointer);}this.zoom(scale,pointerDate,delta,event);// Prevent default actions caused by mouse wheel
// (else the page and timeline both scroll)
event.preventDefault();}}/**
* Start of a touch gesture
* @param {Event} event
* @private
*/_onTouch(event){// eslint-disable-line no-unused-vars
this.props.touch.start=this.start;this.props.touch.end=this.end;this.props.touch.allowDragging=true;this.props.touch.center=null;this.props.touch.centerDate=null;this.scaleOffset=0;this.deltaDifference=0;// Disable the browser default handling of this event.
availableUtils.preventDefault(event);}/**
* Handle pinch event
* @param {Event} event
* @private
*/_onPinch(event){// only allow zooming when configured as zoomable and moveable
if(!(this.options.zoomable&&this.options.moveable))return;// Disable the browser default handling of this event.
availableUtils.preventDefault(event);this.props.touch.allowDragging=false;if(!this.props.touch.center){this.props.touch.center=this.getPointer(event.center,this.body.dom.center);this.props.touch.centerDate=this._pointerToDate(this.props.touch.center);}this.stopRolling();const scale=1/(event.scale+this.scaleOffset);const centerDate=this.props.touch.centerDate;const hiddenDuration=getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end);const hiddenDurationBefore=getHiddenDurationBefore(this.options.moment,this.body.hiddenDates,this,centerDate);const hiddenDurationAfter=hiddenDuration-hiddenDurationBefore;// calculate new start and end
let newStart=centerDate-hiddenDurationBefore+(this.props.touch.start-(centerDate-hiddenDurationBefore))*scale;let newEnd=centerDate+hiddenDurationAfter+(this.props.touch.end-(centerDate+hiddenDurationAfter))*scale;// snapping times away from hidden zones
this.startToFront=1-scale<=0;// used to do the right auto correction with periodic hidden times
this.endToFront=scale-1<=0;// used to do the right auto correction with periodic hidden times
const safeStart=snapAwayFromHidden(this.body.hiddenDates,newStart,1-scale,true);const safeEnd=snapAwayFromHidden(this.body.hiddenDates,newEnd,scale-1,true);if(safeStart!=newStart||safeEnd!=newEnd){this.props.touch.start=safeStart;this.props.touch.end=safeEnd;this.scaleOffset=1-event.scale;newStart=safeStart;newEnd=safeEnd;}const options={animation:false,byUser:true,event};this.setRange(newStart,newEnd,options);this.startToFront=false;// revert to default
this.endToFront=true;// revert to default
}/**
* Test whether the mouse from a mouse event is inside the visible window,
* between the current start and end date
* @param {Object} event
* @return {boolean} Returns true when inside the visible window
* @private
*/_isInsideRange(event){// calculate the time where the mouse is, check whether inside
// and no scroll action should happen.
const clientX=event.center?event.center.x:event.clientX;const centerContainerRect=this.body.dom.centerContainer.getBoundingClientRect();const x=this.options.rtl?clientX-centerContainerRect.left:centerContainerRect.right-clientX;const time=this.body.util.toTime(x);return time>=this.start&&time<=this.end;}/**
* Helper function to calculate the center date for zooming
* @param {{x: number, y: number}} pointer
* @return {number} date
* @private
*/_pointerToDate(pointer){let conversion;const direction=this.options.direction;validateDirection(direction);if(direction=='horizontal'){return this.body.util.toTime(pointer.x).valueOf();}else {const height=this.body.domProps.center.height;conversion=this.conversion(height);return pointer.y/conversion.scale+conversion.offset;}}/**
* Get the pointer location relative to the location of the dom element
* @param {{x: number, y: number}} touch
* @param {Element} element HTML DOM element
* @return {{x: number, y: number}} pointer
* @private
*/getPointer(touch,element){const elementRect=element.getBoundingClientRect();if(this.options.rtl){return {x:elementRect.right-touch.x,y:touch.y-elementRect.top};}else {return {x:touch.x-elementRect.left,y:touch.y-elementRect.top};}}/**
* Zoom the range the given scale in or out. Start and end date will
* be adjusted, and the timeline will be redrawn. You can optionally give a
* date around which to zoom.
* For example, try scale = 0.9 or 1.1
* @param {number} scale Scaling factor. Values above 1 will zoom out,
* values below 1 will zoom in.
* @param {number} [center] Value representing a date around which will
* be zoomed.
* @param {number} delta
* @param {Event} event
*/zoom(scale,center,delta,event){// if centerDate is not provided, take it half between start Date and end Date
if(center==null){center=(this.start+this.end)/2;}const hiddenDuration=getHiddenDurationBetween(this.body.hiddenDates,this.start,this.end);const hiddenDurationBefore=getHiddenDurationBefore(this.options.moment,this.body.hiddenDates,this,center);const hiddenDurationAfter=hiddenDuration-hiddenDurationBefore;// calculate new start and end
let newStart=center-hiddenDurationBefore+(this.start-(center-hiddenDurationBefore))*scale;let newEnd=center+hiddenDurationAfter+(this.end-(center+hiddenDurationAfter))*scale;// snapping times away from hidden zones
this.startToFront=delta>0?false:true;// used to do the right autocorrection with periodic hidden times
this.endToFront=-delta>0?false:true;// used to do the right autocorrection with periodic hidden times
const safeStart=snapAwayFromHidden(this.body.hiddenDates,newStart,delta,true);const safeEnd=snapAwayFromHidden(this.body.hiddenDates,newEnd,-delta,true);if(safeStart!=newStart||safeEnd!=newEnd){newStart=safeStart;newEnd=safeEnd;}const options={animation:false,byUser:true,event};this.setRange(newStart,newEnd,options);this.startToFront=false;// revert to default
this.endToFront=true;// revert to default
}/**
* Move the range with a given delta to the left or right. Start and end
* value will be adjusted. For example, try delta = 0.1 or -0.1
* @param {number} delta Moving amount. Positive value will move right,
* negative value will move left
*/move(delta){// zoom start Date and end Date relative to the centerDate
const diff=this.end-this.start;// apply new values
const newStart=this.start+diff*delta;const newEnd=this.end+diff*delta;// TODO: reckon with min and max range
this.start=newStart;this.end=newEnd;}/**
* Move the range to a new center point
* @param {number} moveTo New center point of the range
*/moveTo(moveTo){const center=(this.start+this.end)/2;const diff=center-moveTo;// calculate new start and end
const newStart=this.start-diff;const newEnd=this.end-diff;const options={animation:false,byUser:true,event:null};this.setRange(newStart,newEnd,options);}/**
* Destroy the Range
*/destroy(){this.stopRolling();}}/**
* Test whether direction has a valid value
* @param {string} direction 'horizontal' or 'vertical'
*/function validateDirection(direction){if(direction!='horizontal'&&direction!='vertical'){throw new TypeError(`Unknown direction "${direction}". Choose "horizontal" or "vertical".`);}}/**
* Setup a mock hammer.js object, for unit testing.
*
* Inspiration: https://github.com/uber/deck.gl/pull/658
*
* @returns {{on: noop, off: noop, destroy: noop, emit: noop, get: get}}
*/function hammerMock(){const noop=()=>{};return {on:noop,off:noop,destroy:noop,emit:noop,get(m){//eslint-disable-line no-unused-vars
return {set:noop};}};}let modifiedHammer;if(typeof window!=='undefined'){const OurHammer=window['Hammer']||Hammer$1$1;modifiedHammer=propagating(OurHammer,{preventDefault:'mouse'});}else {modifiedHammer=()=>// hammer.js is only available in a browser, not in node.js. Replacing it with a mock object.
hammerMock();}var Hammer=modifiedHammer;/**
* Register a touch event, taking place before a gesture
* @param {Hammer} hammer A hammer instance
* @param {function} callback Callback, called as callback(event)
*/function onTouch$1(hammer,callback){callback.inputHandler=function(event){if(event.isFirst){callback(event);}};hammer.on('hammer.input',callback.inputHandler);}/**
* Register a release event, taking place after a gesture
* @param {Hammer} hammer A hammer instance
* @param {function} callback Callback, called as callback(event)
* @returns {*}
*/function onRelease$1(hammer,callback){callback.inputHandler=function(event){if(event.isFinal){callback(event);}};return hammer.on('hammer.input',callback.inputHandler);}/**
* Hack the PinchRecognizer such that it doesn't prevent default behavior
* for vertical panning.
*
* Yeah ... this is quite a hack ... see https://github.com/hammerjs/hammer.js/issues/932
*
* @param {Hammer.Pinch} pinchRecognizer
* @return {Hammer.Pinch} returns the pinchRecognizer
*/function disablePreventDefaultVertically(pinchRecognizer){const TOUCH_ACTION_PAN_Y='pan-y';pinchRecognizer.getTouchAction=function(){// default method returns [TOUCH_ACTION_NONE]
return [TOUCH_ACTION_PAN_Y];};return pinchRecognizer;}/**
* The class TimeStep is an iterator for dates. You provide a start date and an
* end date. The class itself determines the best scale (step size) based on the
* provided start Date, end Date, and minimumStep.
*
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
*
* Alternatively, you can set a scale by hand.
* After creation, you can initialize the class by executing first(). Then you
* can iterate from the start date to the end date via next(). You can check if
* the end date is reached with the function hasNext(). After each step, you can
* retrieve the current date via getCurrent().
* The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
* days, to years.
*
* Version: 1.2
*
*/class TimeStep{/**
* @param {Date} [start] The start date, for example new Date(2010, 9, 21)
* or new Date(2010, 9, 21, 23, 45, 00)
* @param {Date} [end] The end date
* @param {number} [minimumStep] Optional. Minimum step size in milliseconds
* @param {Date|Array.<Date>} [hiddenDates] Optional.
* @param {{showMajorLabels: boolean, showWeekScale: boolean}} [options] Optional.
* @constructor TimeStep
*/constructor(start,end,minimumStep,hiddenDates,options){this.moment=options&&options.moment||moment$3;this.options=options?options:{};// variables
this.current=this.moment();this._start=this.moment();this._end=this.moment();this.autoScale=true;this.scale='day';this.step=1;// initialize the range
this.setRange(start,end,minimumStep);// hidden Dates options
this.switchedDay=false;this.switchedMonth=false;this.switchedYear=false;if(Array.isArray(hiddenDates)){this.hiddenDates=hiddenDates;}else if(hiddenDates!=undefined){this.hiddenDates=[hiddenDates];}else {this.hiddenDates=[];}this.format=TimeStep.FORMAT;// default formatting
}/**
* Set custom constructor function for moment. Can be used to set dates
* to UTC or to set a utcOffset.
* @param {function} moment
*/setMoment(moment){this.moment=moment;// update the date properties, can have a new utcOffset
this.current=this.moment(this.current.valueOf());this._start=this.moment(this._start.valueOf());this._end=this.moment(this._end.valueOf());}/**
* Set custom formatting for the minor an major labels of the TimeStep.
* Both `minorLabels` and `majorLabels` are an Object with properties:
* 'millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'.
* @param {{minorLabels: Object, majorLabels: Object}} format
*/setFormat(format){const defaultFormat=availableUtils.deepExtend({},TimeStep.FORMAT);this.format=availableUtils.deepExtend(defaultFormat,format);}/**
* Set a new range
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
* @param {Date} [start] The start date and time.
* @param {Date} [end] The end date and time.
* @param {int} [minimumStep] Optional. Minimum step size in milliseconds
*/setRange(start,end,minimumStep){if(!(start instanceof Date)||!(end instanceof Date)){throw "No legal start or end date in method setRange";}this._start=start!=undefined?this.moment(start.valueOf()):Date.now();this._end=end!=undefined?this.moment(end.valueOf()):Date.now();if(this.autoScale){this.setMinimumStep(minimumStep);}}/**
* Set the range iterator to the start date.
*/start(){this.current=this._start.clone();this.roundToMinor();}/**
* Round the current date to the first minor date value
* This must be executed once when the current date is set to start Date
*/roundToMinor(){// round to floor
// to prevent year & month scales rounding down to the first day of week we perform this separately
if(this.scale=='week'){this.current.weekday(0);}// IMPORTANT: we have no breaks in this switch! (this is no bug)
// noinspection FallThroughInSwitchStatementJS
switch(this.scale){case'year':this.current.year(this.step*Math.floor(this.current.year()/this.step));this.current.month(0);// eslint-disable-line no-fallthrough
case'month':this.current.date(1);// eslint-disable-line no-fallthrough
case'week':// eslint-disable-line no-fallthrough
case'day':// eslint-disable-line no-fallthrough
case'weekday':this.current.hours(0);// eslint-disable-line no-fallthrough
case'hour':this.current.minutes(0);// eslint-disable-line no-fallthrough
case'minute':this.current.seconds(0);// eslint-disable-line no-fallthrough
case'second':this.current.milliseconds(0);// eslint-disable-line no-fallthrough
//case 'millisecond': // nothing to do for milliseconds
}if(this.step!=1){// round down to the first minor value that is a multiple of the current step size
let priorCurrent=this.current.clone();switch(this.scale){case'millisecond':this.current.subtract(this.current.milliseconds()%this.step,'milliseconds');break;case'second':this.current.subtract(this.current.seconds()%this.step,'seconds');break;case'minute':this.current.subtract(this.current.minutes()%this.step,'minutes');break;case'hour':this.current.subtract(this.current.hours()%this.step,'hours');break;case'weekday':// intentional fall through
case'day':this.current.subtract((this.current.date()-1)%this.step,'day');break;case'week':this.current.subtract(this.current.week()%this.step,'week');break;case'month':this.current.subtract(this.current.month()%this.step,'month');break;case'year':this.current.subtract(this.current.year()%this.step,'year');break;}if(!priorCurrent.isSame(this.current)){this.current=this.moment(snapAwayFromHidden(this.hiddenDates,this.current.valueOf(),-1,true));}}}/**
* Check if the there is a next step
* @return {boolean} true if the current date has not passed the end date
*/hasNext(){return this.current.valueOf()<=this._end.valueOf();}/**
* Do the next step
*/next(){const prev=this.current.valueOf();// Two cases, needed to prevent issues with switching daylight savings
// (end of March and end of October)
switch(this.scale){case'millisecond':this.current.add(this.step,'millisecond');break;case'second':this.current.add(this.step,'second');break;case'minute':this.current.add(this.step,'minute');break;case'hour':this.current.add(this.step,'hour');if(this.current.month()<6){this.current.subtract(this.current.hours()%this.step,'hour');}else {if(this.current.hours()%this.step!==0){this.current.add(this.step-this.current.hours()%this.step,'hour');}}break;case'weekday':// intentional fall through
case'day':this.current.add(this.step,'day');break;case'week':if(this.current.weekday()!==0){// we had a month break not correlating with a week's start before
this.current.weekday(0);// switch back to week cycles
this.current.add(this.step,'week');}else if(this.options.showMajorLabels===false){this.current.add(this.step,'week');// the default case
}else {// first day of the week
const nextWeek=this.current.clone();nextWeek.add(1,'week');if(nextWeek.isSame(this.current,'month')){// is the first day of the next week in the same month?
this.current.add(this.step,'week');// the default case
}else {// inject a step at each first day of the month
this.current.add(this.step,'week');this.current.date(1);}}break;case'month':this.current.add(this.step,'month');break;case'year':this.current.add(this.step,'year');break;}if(this.step!=1){// round down to the correct major value
switch(this.scale){case'millisecond':if(this.current.milliseconds()>0&&this.current.milliseconds()<this.step)this.current.milliseconds(0);break;case'second':if(this.current.seconds()>0&&this.current.seconds()<this.step)this.current.seconds(0);break;case'minute':if(this.current.minutes()>0&&this.current.minutes()<this.step)this.current.minutes(0);break;case'hour':if(this.current.hours()>0&&this.current.hours()<this.step)this.current.hours(0);break;case'weekday':// intentional fall through
case'day':if(this.current.date()<this.step+1)this.current.date(1);break;case'week':if(this.current.week()<this.step)this.current.week(1);break;// week numbering starts at 1, not 0
case'month':if(this.current.month()<this.step)this.current.month(0);break;}}// safety mechanism: if current time is still unchanged, move to the end
if(this.current.valueOf()==prev){this.current=this._end.clone();}// Reset switches for year, month and day. Will get set to true where appropriate in DateUtil.stepOverHiddenDates
this.switchedDay=false;this.switchedMonth=false;this.switchedYear=false;stepOverHiddenDates(this.moment,this,prev);}/**
* Get the current datetime
* @return {Moment} current The current date
*/getCurrent(){return this.current.clone();}/**
* Set a custom scale. Autoscaling will be disabled.
* For example setScale('minute', 5) will result
* in minor steps of 5 minutes, and major steps of an hour.
*
* @param {{scale: string, step: number}} params
* An object containing two properties:
* - A string 'scale'. Choose from 'millisecond', 'second',
* 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'.
* - A number 'step'. A step size, by default 1.
* Choose for example 1, 2, 5, or 10.
*/setScale(params){if(params&&typeof params.scale=='string'){this.scale=params.scale;this.step=params.step>0?params.step:1;this.autoScale=false;}}/**
* Enable or disable autoscaling
* @param {boolean} enable If true, autoascaling is set true
*/setAutoScale(enable){this.autoScale=enable;}/**
* Automatically determine the scale that bests fits the provided minimum step
* @param {number} [minimumStep] The minimum step size in milliseconds
*/setMinimumStep(minimumStep){if(minimumStep==undefined){return;}//var b = asc + ds;
const stepYear=1000*60*60*24*30*12;const stepMonth=1000*60*60*24*30;const stepDay=1000*60*60*24;const stepHour=1000*60*60;const stepMinute=1000*60;const stepSecond=1000;const stepMillisecond=1;// find the smallest step that is larger than the provided minimumStep
if(stepYear*1000>minimumStep){this.scale='year';this.step=1000;}if(stepYear*500>minimumStep){this.scale='year';this.step=500;}if(stepYear*100>minimumStep){this.scale='year';this.step=100;}if(stepYear*50>minimumStep){this.scale='year';this.step=50;}if(stepYear*10>minimumStep){this.scale='year';this.step=10;}if(stepYear*5>minimumStep){this.scale='year';this.step=5;}if(stepYear>minimumStep){this.scale='year';this.step=1;}if(stepMonth*3>minimumStep){this.scale='month';this.step=3;}if(stepMonth>minimumStep){this.scale='month';this.step=1;}if(stepDay*7>minimumStep&&this.options.showWeekScale){this.scale='week';this.step=1;}if(stepDay*2>minimumStep){this.scale='day';this.step=2;}if(stepDay>minimumStep){this.scale='day';this.step=1;}if(stepDay/2>minimumStep){this.scale='weekday';this.step=1;}if(stepHour*4>minimumStep){this.scale='hour';this.step=4;}if(stepHour>minimumStep){this.scale='hour';this.step=1;}if(stepMinute*15>minimumStep){this.scale='minute';this.step=15;}if(stepMinute*10>minimumStep){this.scale='minute';this.step=10;}if(stepMinute*5>minimumStep){this.scale='minute';this.step=5;}if(stepMinute>minimumStep){this.scale='minute';this.step=1;}if(stepSecond*15>minimumStep){this.scale='second';this.step=15;}if(stepSecond*10>minimumStep){this.scale='second';this.step=10;}if(stepSecond*5>minimumStep){this.scale='second';this.step=5;}if(stepSecond>minimumStep){this.scale='second';this.step=1;}if(stepMillisecond*200>minimumStep){this.scale='millisecond';this.step=200;}if(stepMillisecond*100>minimumStep){this.scale='millisecond';this.step=100;}if(stepMillisecond*50>minimumStep){this.scale='millisecond';this.step=50;}if(stepMillisecond*10>minimumStep){this.scale='millisecond';this.step=10;}if(stepMillisecond*5>minimumStep){this.scale='millisecond';this.step=5;}if(stepMillisecond>minimumStep){this.scale='millisecond';this.step=1;}}/**
* Snap a date to a rounded value.
* The snap intervals are dependent on the current scale and step.
* Static function
* @param {Date} date the date to be snapped.
* @param {string} scale Current scale, can be 'millisecond', 'second',
* 'minute', 'hour', 'weekday, 'day', 'week', 'month', 'year'.
* @param {number} step Current step (1, 2, 4, 5, ...
* @return {Date} snappedDate
*/static snap(date,scale,step){const clone=moment$3(date);if(scale=='year'){const year=clone.year()+Math.round(clone.month()/12);clone.year(Math.round(year/step)*step);clone.month(0);clone.date(0);clone.hours(0);clone.minutes(0);clone.seconds(0);clone.milliseconds(0);}else if(scale=='month'){if(clone.date()>15){clone.date(1);clone.add(1,'month');// important: first set Date to 1, after that change the month.
}else {clone.date(1);}clone.hours(0);clone.minutes(0);clone.seconds(0);clone.milliseconds(0);}else if(scale=='week'){if(clone.weekday()>2){// doing it the momentjs locale aware way
clone.weekday(0);clone.add(1,'week');}else {clone.weekday(0);}clone.hours(0);clone.minutes(0);clone.seconds(0);clone.milliseconds(0);}else if(scale=='day'){//noinspection FallthroughInSwitchStatementJS
switch(step){case 5:case 2:clone.hours(Math.round(clone.hours()/24)*24);break;default:clone.hours(Math.round(clone.hours()/12)*12);break;}clone.minutes(0);clone.seconds(0);clone.milliseconds(0);}else if(scale=='weekday'){//noinspection FallthroughInSwitchStatementJS
switch(step){case 5:case 2:clone.hours(Math.round(clone.hours()/12)*12);break;default:clone.hours(Math.round(clone.hours()/6)*6);break;}clone.minutes(0);clone.seconds(0);clone.milliseconds(0);}else if(scale=='hour'){switch(step){case 4:clone.minutes(Math.round(clone.minutes()/60)*60);break;default:clone.minutes(Math.round(clone.minutes()/30)*30);break;}clone.seconds(0);clone.milliseconds(0);}else if(scale=='minute'){//noinspection FallthroughInSwitchStatementJS
switch(step){case 15:case 10:clone.minutes(Math.round(clone.minutes()/5)*5);clone.seconds(0);break;case 5:clone.seconds(Math.round(clone.seconds()/60)*60);break;default:clone.seconds(Math.round(clone.seconds()/30)*30);break;}clone.milliseconds(0);}else if(scale=='second'){//noinspection FallthroughInSwitchStatementJS
switch(step){case 15:case 10:clone.seconds(Math.round(clone.seconds()/5)*5);clone.milliseconds(0);break;case 5:clone.milliseconds(Math.round(clone.milliseconds()/1000)*1000);break;default:clone.milliseconds(Math.round(clone.milliseconds()/500)*500);break;}}else if(scale=='millisecond'){const _step=step>5?step/2:1;clone.milliseconds(Math.round(clone.milliseconds()/_step)*_step);}return clone;}/**
* Check if the current value is a major value (for example when the step
* is DAY, a major value is each first day of the MONTH)
* @return {boolean} true if current date is major, else false.
*/isMajor(){if(this.switchedYear==true){switch(this.scale){case'year':case'month':case'week':case'weekday':case'day':case'hour':case'minute':case'second':case'millisecond':return true;default:return false;}}else if(this.switchedMonth==true){switch(this.scale){case'week':case'weekday':case'day':case'hour':case'minute':case'second':case'millisecond':return true;default:return false;}}else if(this.switchedDay==true){switch(this.scale){case'millisecond':case'second':case'minute':case'hour':return true;default:return false;}}const date=this.moment(this.current);switch(this.scale){case'millisecond':return date.milliseconds()==0;case'second':return date.seconds()==0;case'minute':return date.hours()==0&&date.minutes()==0;case'hour':return date.hours()==0;case'weekday':// intentional fall through
case'day':return this.options.showWeekScale?date.isoWeekday()==1:date.date()==1;case'week':return date.date()==1;case'month':return date.month()==0;case'year':return false;default:return false;}}/**
* Returns formatted text for the minor axislabel, depending on the current
* date and the scale. For example when scale is MINUTE, the current time is
* formatted as "hh:mm".
* @param {Date} [date=this.current] custom date. if not provided, current date is taken
* @returns {String}
*/getLabelMinor(date){if(date==undefined){date=this.current;}if(date instanceof Date){date=this.moment(date);}if(typeof this.format.minorLabels==="function"){return this.format.minorLabels(date,this.scale,this.step);}const format=this.format.minorLabels[this.scale];// noinspection FallThroughInSwitchStatementJS
switch(this.scale){case'week':// Don't draw the minor label if this date is the first day of a month AND if it's NOT the start of the week.
// The 'date' variable may actually be the 'next' step when called from TimeAxis' _repaintLabels.
if(date.date()===1&&date.weekday()!==0){return "";}default:// eslint-disable-line no-fallthrough
return format&&format.length>0?this.moment(date).format(format):'';}}/**
* Returns formatted text for the major axis label, depending on the current
* date and the scale. For example when scale is MINUTE, the major scale is
* hours, and the hour will be formatted as "hh".
* @param {Date} [date=this.current] custom date. if not provided, current date is taken
* @returns {String}
*/getLabelMajor(date){if(date==undefined){date=this.current;}if(date instanceof Date){date=this.moment(date);}if(typeof this.format.majorLabels==="function"){return this.format.majorLabels(date,this.scale,this.step);}const format=this.format.majorLabels[this.scale];return format&&format.length>0?this.moment(date).format(format):'';}/**
* get class name
* @return {string} class name
*/getClassName(){const _moment=this.moment;const m=this.moment(this.current);const current=m.locale?m.locale('en'):m.lang('en');// old versions of moment have .lang() function
const step=this.step;const classNames=[];/**
*
* @param {number} value
* @returns {String}
*/function even(value){return value/step%2==0?' vis-even':' vis-odd';}/**
*
* @param {Date} date
* @returns {String}
*/function today(date){if(date.isSame(Date.now(),'day')){return ' vis-today';}if(date.isSame(_moment().add(1,'day'),'day')){return ' vis-tomorrow';}if(date.isSame(_moment().add(-1,'day'),'day')){return ' vis-yesterday';}return '';}/**
*
* @param {Date} date
* @returns {String}
*/function currentWeek(date){return date.isSame(Date.now(),'week')?' vis-current-week':'';}/**
*
* @param {Date} date
* @returns {String}
*/function currentMonth(date){return date.isSame(Date.now(),'month')?' vis-current-month':'';}/**
*
* @param {Date} date
* @returns {String}
*/function currentYear(date){return date.isSame(Date.now(),'year')?' vis-current-year':'';}switch(this.scale){case'millisecond':classNames.push(today(current));classNames.push(even(current.milliseconds()));break;case'second':classNames.push(today(current));classNames.push(even(current.seconds()));break;case'minute':classNames.push(today(current));classNames.push(even(current.minutes()));break;case'hour':classNames.push(`vis-h${current.hours()}${this.step==4?'-h'+(current.hours()+4):''}`);classNames.push(today(current));classNames.push(even(current.hours()));break;case'weekday':classNames.push(`vis-${current.format('dddd').toLowerCase()}`);classNames.push(today(current));classNames.push(currentWeek(current));classNames.push(even(current.date()));break;case'day':classNames.push(`vis-day${current.date()}`);classNames.push(`vis-${current.format('MMMM').toLowerCase()}`);classNames.push(today(current));classNames.push(currentMonth(current));classNames.push(this.step<=2?today(current):'');classNames.push(this.step<=2?`vis-${current.format('dddd').toLowerCase()}`:'');classNames.push(even(current.date()-1));break;case'week':classNames.push(`vis-week${current.format('w')}`);classNames.push(currentWeek(current));classNames.push(even(current.week()));break;case'month':classNames.push(`vis-${current.format('MMMM').toLowerCase()}`);classNames.push(currentMonth(current));classNames.push(even(current.month()));break;case'year':classNames.push(`vis-year${current.year()}`);classNames.push(currentYear(current));classNames.push(even(current.year()));break;}return classNames.filter(String).join(" ");}}// Time formatting
TimeStep.FORMAT={minorLabels:{millisecond:'SSS',second:'s',minute:'HH:mm',hour:'HH:mm',weekday:'ddd D',day:'D',week:'w',month:'MMM',year:'YYYY'},majorLabels:{millisecond:'HH:mm:ss',second:'D MMMM HH:mm',minute:'ddd D MMMM',hour:'ddd D MMMM',weekday:'MMMM YYYY',day:'MMMM YYYY',week:'MMMM YYYY',month:'YYYY',year:''}};/** A horizontal time axis */class TimeAxis extends Component{/**
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
* @param {Object} [options] See TimeAxis.setOptions for the available
* options.
* @constructor TimeAxis
* @extends Component
*/constructor(body,options){super();this.dom={foreground:null,lines:[],majorTexts:[],minorTexts:[],redundant:{lines:[],majorTexts:[],minorTexts:[]}};this.props={range:{start:0,end:0,minimumStep:0},lineTop:0};this.defaultOptions={orientation:{axis:'bottom'},// axis orientation: 'top' or 'bottom'
showMinorLabels:true,showMajorLabels:true,showWeekScale:false,maxMinorChars:7,format:availableUtils.extend({},TimeStep.FORMAT),moment:moment$3,timeAxis:null};this.options=availableUtils.extend({},this.defaultOptions);this.body=body;// create the HTML DOM
this._create();this.setOptions(options);}/**
* Set options for the TimeAxis.
* Parameters will be merged in current options.
* @param {Object} options Available options:
* {string} [orientation.axis]
* {boolean} [showMinorLabels]
* {boolean} [showMajorLabels]
* {boolean} [showWeekScale]
*/setOptions(options){if(options){// copy all options that we know
availableUtils.selectiveExtend(['showMinorLabels','showMajorLabels','showWeekScale','maxMinorChars','hiddenDates','timeAxis','moment','rtl'],this.options,options);// deep copy the format options
availableUtils.selectiveDeepExtend(['format'],this.options,options);if('orientation'in options){if(typeof options.orientation==='string'){this.options.orientation.axis=options.orientation;}else if(typeof options.orientation==='object'&&'axis'in options.orientation){this.options.orientation.axis=options.orientation.axis;}}// apply locale to moment.js
// TODO: not so nice, this is applied globally to moment.js
if('locale'in options){if(typeof moment$3.locale==='function'){// moment.js 2.8.1+
moment$3.locale(options.locale);}else {moment$3.lang(options.locale);}}}}/**
* Create the HTML DOM for the TimeAxis
*/_create(){this.dom.foreground=document.createElement('div');this.dom.background=document.createElement('div');this.dom.foreground.className='vis-time-axis vis-foreground';this.dom.background.className='vis-time-axis vis-background';}/**
* Destroy the TimeAxis
*/destroy(){// remove from DOM
if(this.dom.foreground.parentNode){this.dom.foreground.parentNode.removeChild(this.dom.foreground);}if(this.dom.background.parentNode){this.dom.background.parentNode.removeChild(this.dom.background);}this.body=null;}/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/redraw(){const props=this.props;const foreground=this.dom.foreground;const background=this.dom.background;// determine the correct parent DOM element (depending on option orientation)
const parent=this.options.orientation.axis=='top'?this.body.dom.top:this.body.dom.bottom;const parentChanged=foreground.parentNode!==parent;// calculate character width and height
this._calculateCharSize();// TODO: recalculate sizes only needed when parent is resized or options is changed
const showMinorLabels=this.options.showMinorLabels&&this.options.orientation.axis!=='none';const showMajorLabels=this.options.showMajorLabels&&this.options.orientation.axis!=='none';// determine the width and height of the elemens for the axis
props.minorLabelHeight=showMinorLabels?props.minorCharHeight:0;props.majorLabelHeight=showMajorLabels?props.majorCharHeight:0;props.height=props.minorLabelHeight+props.majorLabelHeight;props.width=foreground.offsetWidth;props.minorLineHeight=this.body.domProps.root.height-props.majorLabelHeight-(this.options.orientation.axis=='top'?this.body.domProps.bottom.height:this.body.domProps.top.height);props.minorLineWidth=1;// TODO: really calculate width
props.majorLineHeight=props.minorLineHeight+props.majorLabelHeight;props.majorLineWidth=1;// TODO: really calculate width
// take foreground and background offline while updating (is almost twice as fast)
const foregroundNextSibling=foreground.nextSibling;const backgroundNextSibling=background.nextSibling;foreground.parentNode&&foreground.parentNode.removeChild(foreground);background.parentNode&&background.parentNode.removeChild(background);foreground.style.height=`${this.props.height}px`;this._repaintLabels();// put DOM online again (at the same place)
if(foregroundNextSibling){parent.insertBefore(foreground,foregroundNextSibling);}else {parent.appendChild(foreground);}if(backgroundNextSibling){this.body.dom.backgroundVertical.insertBefore(background,backgroundNextSibling);}else {this.body.dom.backgroundVertical.appendChild(background);}return this._isResized()||parentChanged;}/**
* Repaint major and minor text labels and vertical grid lines
* @private
*/_repaintLabels(){const orientation=this.options.orientation.axis;// calculate range and step (step such that we have space for 7 characters per label)
const start=availableUtils.convert(this.body.range.start,'Number');const end=availableUtils.convert(this.body.range.end,'Number');const timeLabelsize=this.body.util.toTime((this.props.minorCharWidth||10)*this.options.maxMinorChars).valueOf();let minimumStep=timeLabelsize-getHiddenDurationBefore(this.options.moment,this.body.hiddenDates,this.body.range,timeLabelsize);minimumStep-=this.body.util.toTime(0).valueOf();const step=new TimeStep(new Date(start),new Date(end),minimumStep,this.body.hiddenDates,this.options);step.setMoment(this.options.moment);if(this.options.format){step.setFormat(this.options.format);}if(this.options.timeAxis){step.setScale(this.options.timeAxis);}this.step=step;// Move all DOM elements to a "redundant" list, where they
// can be picked for re-use, and clear the lists with lines and texts.
// At the end of the function _repaintLabels, left over elements will be cleaned up
const dom=this.dom;dom.redundant.lines=dom.lines;dom.redundant.majorTexts=dom.majorTexts;dom.redundant.minorTexts=dom.minorTexts;dom.lines=[];dom.majorTexts=[];dom.minorTexts=[];let current;let next;let x;let xNext;let isMajor;let showMinorGrid;let width=0;let prevWidth;let line;let xFirstMajorLabel=undefined;let count=0;const MAX=1000;let className;step.start();next=step.getCurrent();xNext=this.body.util.toScreen(next);while(step.hasNext()&&count<MAX){count++;isMajor=step.isMajor();className=step.getClassName();current=next;x=xNext;step.next();next=step.getCurrent();xNext=this.body.util.toScreen(next);prevWidth=width;width=xNext-x;switch(step.scale){case'week':showMinorGrid=true;break;default:showMinorGrid=width>=prevWidth*0.4;break;// prevent displaying of the 31th of the month on a scale of 5 days
}if(this.options.showMinorLabels&&showMinorGrid){var label=this._repaintMinorText(x,step.getLabelMinor(current),orientation,className);label.style.width=`${width}px`;// set width to prevent overflow
}if(isMajor&&this.options.showMajorLabels){if(x>0){if(xFirstMajorLabel==undefined){xFirstMajorLabel=x;}label=this._repaintMajorText(x,step.getLabelMajor(current),orientation,className);}line=this._repaintMajorLine(x,width,orientation,className);}else {// minor line
if(showMinorGrid){line=this._repaintMinorLine(x,width,orientation,className);}else {if(line){// adjust the width of the previous grid
line.style.width=`${parseInt(line.style.width)+width}px`;}}}}if(count===MAX&&!warnedForOverflow){console.warn(`Something is wrong with the Timeline scale. Limited drawing of grid lines to ${MAX} lines.`);warnedForOverflow=true;}// create a major label on the left when needed
if(this.options.showMajorLabels){const leftTime=this.body.util.toTime(0);// upper bound estimation
const leftText=step.getLabelMajor(leftTime);const widthText=leftText.length*(this.props.majorCharWidth||10)+10;if(xFirstMajorLabel==undefined||widthText<xFirstMajorLabel){this._repaintMajorText(0,leftText,orientation,className);}}// Cleanup leftover DOM elements from the redundant list
availableUtils.forEach(this.dom.redundant,arr=>{while(arr.length){const elem=arr.pop();if(elem&&elem.parentNode){elem.parentNode.removeChild(elem);}}});}/**
* Create a minor label for the axis at position x
* @param {number} x
* @param {string} text
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the HTML element of the created label
* @private
*/_repaintMinorText(x,text,orientation,className){// reuse redundant label
let label=this.dom.redundant.minorTexts.shift();if(!label){// create new label
const content=document.createTextNode('');label=document.createElement('div');label.appendChild(content);this.dom.foreground.appendChild(label);}this.dom.minorTexts.push(label);label.innerHTML=availableUtils.xss(text);let y=orientation=='top'?this.props.majorLabelHeight:0;this._setXY(label,x,y);label.className=`vis-text vis-minor ${className}`;//label.title = title; // TODO: this is a heavy operation
return label;}/**
* Create a Major label for the axis at position x
* @param {number} x
* @param {string} text
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the HTML element of the created label
* @private
*/_repaintMajorText(x,text,orientation,className){// reuse redundant label
let label=this.dom.redundant.majorTexts.shift();if(!label){// create label
const content=document.createElement('div');label=document.createElement('div');label.appendChild(content);this.dom.foreground.appendChild(label);}label.childNodes[0].innerHTML=availableUtils.xss(text);label.className=`vis-text vis-major ${className}`;//label.title = title; // TODO: this is a heavy operation
let y=orientation=='top'?0:this.props.minorLabelHeight;this._setXY(label,x,y);this.dom.majorTexts.push(label);return label;}/**
* sets xy
* @param {string} label
* @param {number} x
* @param {number} y
* @private
*/_setXY(label,x,y){// If rtl is true, inverse x.
const directionX=this.options.rtl?x*-1:x;label.style.transform=`translate(${directionX}px, ${y}px)`;}/**
* Create a minor line for the axis at position x
* @param {number} left
* @param {number} width
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the created line
* @private
*/_repaintMinorLine(left,width,orientation,className){// reuse redundant line
let line=this.dom.redundant.lines.shift();if(!line){// create vertical line
line=document.createElement('div');this.dom.background.appendChild(line);}this.dom.lines.push(line);const props=this.props;line.style.width=`${width}px`;line.style.height=`${props.minorLineHeight}px`;let y=orientation=='top'?props.majorLabelHeight:this.body.domProps.top.height;let x=left-props.minorLineWidth/2;this._setXY(line,x,y);line.className=`vis-grid ${this.options.rtl?'vis-vertical-rtl':'vis-vertical'} vis-minor ${className}`;return line;}/**
* Create a Major line for the axis at position x
* @param {number} left
* @param {number} width
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the created line
* @private
*/_repaintMajorLine(left,width,orientation,className){// reuse redundant line
let line=this.dom.redundant.lines.shift();if(!line){// create vertical line
line=document.createElement('div');this.dom.background.appendChild(line);}this.dom.lines.push(line);const props=this.props;line.style.width=`${width}px`;line.style.height=`${props.majorLineHeight}px`;let y=orientation=='top'?0:this.body.domProps.top.height;let x=left-props.majorLineWidth/2;this._setXY(line,x,y);line.className=`vis-grid ${this.options.rtl?'vis-vertical-rtl':'vis-vertical'} vis-major ${className}`;return line;}/**
* Determine the size of text on the axis (both major and minor axis).
* The size is calculated only once and then cached in this.props.
* @private
*/_calculateCharSize(){// Note: We calculate char size with every redraw. Size may change, for
// example when any of the timelines parents had display:none for example.
// determine the char width and height on the minor axis
if(!this.dom.measureCharMinor){this.dom.measureCharMinor=document.createElement('DIV');this.dom.measureCharMinor.className='vis-text vis-minor vis-measure';this.dom.measureCharMinor.style.position='absolute';this.dom.measureCharMinor.appendChild(document.createTextNode('0'));this.dom.foreground.appendChild(this.dom.measureCharMinor);}this.props.minorCharHeight=this.dom.measureCharMinor.clientHeight;this.props.minorCharWidth=this.dom.measureCharMinor.clientWidth;// determine the char width and height on the major axis
if(!this.dom.measureCharMajor){this.dom.measureCharMajor=document.createElement('DIV');this.dom.measureCharMajor.className='vis-text vis-major vis-measure';this.dom.measureCharMajor.style.position='absolute';this.dom.measureCharMajor.appendChild(document.createTextNode('0'));this.dom.foreground.appendChild(this.dom.measureCharMajor);}this.props.majorCharHeight=this.dom.measureCharMajor.clientHeight;this.props.majorCharWidth=this.dom.measureCharMajor.clientWidth;}}var warnedForOverflow=false;/**
* Turn an element into an clickToUse element.
* When not active, the element has a transparent overlay. When the overlay is
* clicked, the mode is changed to active.
* When active, the element is displayed with a blue border around it, and
* the interactive contents of the element can be used. When clicked outside
* the element, the elements mode is changed to inactive.
* @param {Element} container
* @constructor Activator
*/function Activator(container){this.active=false;this.dom={container:container};this.dom.overlay=document.createElement('div');this.dom.overlay.className='vis-overlay';this.dom.container.appendChild(this.dom.overlay);this.hammer=Hammer(this.dom.overlay);this.hammer.on('tap',this._onTapOverlay.bind(this));// block all touch events (except tap)
var me=this;var events=['tap','doubletap','press','pinch','pan','panstart','panmove','panend'];events.forEach(function(event){me.hammer.on(event,function(event){event.stopPropagation();});});// attach a click event to the window, in order to deactivate when clicking outside the timeline
if(document&&document.body){this.onClick=function(event){if(!_hasParent(event.target,container)){me.deactivate();}};document.body.addEventListener('click',this.onClick);}if(this.keycharm!==undefined){this.keycharm.destroy();}this.keycharm=keycharm();// keycharm listener only bounded when active)
this.escListener=this.deactivate.bind(this);}// turn into an event emitter
componentEmitter(Activator.prototype);// The currently active activator
Activator.current=null;/**
* Destroy the activator. Cleans up all created DOM and event listeners
*/Activator.prototype.destroy=function(){this.deactivate();// remove dom
this.dom.overlay.parentNode.removeChild(this.dom.overlay);// remove global event listener
if(this.onClick){document.body.removeEventListener('click',this.onClick);}// remove keycharm
if(this.keycharm!==undefined){this.keycharm.destroy();}this.keycharm=null;// cleanup hammer instances
this.hammer.destroy();this.hammer=null;// FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory)
};/**
* Activate the element
* Overlay is hidden, element is decorated with a blue shadow border
*/Activator.prototype.activate=function(){// we allow only one active activator at a time
if(Activator.current){Activator.current.deactivate();}Activator.current=this;this.active=true;this.dom.overlay.style.display='none';availableUtils.addClassName(this.dom.container,'vis-active');this.emit('change');this.emit('activate');// ugly hack: bind ESC after emitting the events, as the Network rebinds all
// keyboard events on a 'change' event
this.keycharm.bind('esc',this.escListener);};/**
* Deactivate the element
* Overlay is displayed on top of the element
*/Activator.prototype.deactivate=function(){if(Activator.current===this){Activator.current=null;}this.active=false;this.dom.overlay.style.display='';availableUtils.removeClassName(this.dom.container,'vis-active');this.keycharm.unbind('esc',this.escListener);this.emit('change');this.emit('deactivate');};/**
* Handle a tap event: activate the container
* @param {Event} event The event
* @private
*/Activator.prototype._onTapOverlay=function(event){// activate the container
this.activate();event.stopPropagation();};/**
* Test whether the element has the requested parent element somewhere in
* its chain of parent nodes.
* @param {HTMLElement} element
* @param {HTMLElement} parent
* @returns {boolean} Returns true when the parent is found somewhere in the
* chain of parent nodes.
* @private
*/function _hasParent(element,parent){while(element){if(element===parent){return true;}element=element.parentNode;}return false;}/*
* IMPORTANT: Locales for Moment has to be imported in the legacy and standalone
* entry points. For the peer build it's users responsibility to do so.
*/ // English
const en$1={current:'current',time:'time',deleteSelected:'Delete selected'};const en_EN=en$1;const en_US=en$1;// Italiano
const it$1={current:'attuale',time:'tempo',deleteSelected:'Cancella la selezione'};const it_IT=it$1;const it_CH=it$1;// Dutch
const nl$1={current:'huidige',time:'tijd',deleteSelected:'Selectie verwijderen'};const nl_NL=nl$1;const nl_BE=nl$1;// German
const de$1={current:'Aktuelle',time:'Zeit',deleteSelected:'L\u00f6sche Auswahl'};const de_DE=de$1;// French
const fr$1={current:'actuel',time:'heure',deleteSelected:'Effacer la selection'};const fr_FR=fr$1;const fr_CA=fr$1;const fr_BE=fr$1;// Espanol
const es$1={current:'corriente',time:'hora',deleteSelected:'Eliminar selecci\u00f3n'};const es_ES=es$1;// Ukrainian
const uk$1={current:'поточний',time:'час',deleteSelected:'Видалити обране'};const uk_UA=uk$1;// Russian
const ru$1={current:'текущее',time:'время',deleteSelected:'Удалить выбранное'};const ru_RU=ru$1;// Polish
const pl={current:'aktualny',time:'czas',deleteSelected:'Usuń wybrane'};const pl_PL=pl;// Portuguese
const pt$1={current:'atual',time:'data',deleteSelected:'Apagar selecionado'};const pt_BR=pt$1;const pt_PT=pt$1;// Japanese
const ja={current:'現在',time:'時刻',deleteSelected:'選択されたものを削除'};const ja_JP=ja;// Swedish
const sv={current:'nuvarande',time:'tid',deleteSelected:'Radera valda'};const sv_SE=sv;// Norwegian
const nb={current:'nåværende',time:'tid',deleteSelected:'Slett valgte'};const nb_NO=nb;const nn=nb;const nn_NO=nb;// Lithuanian
const lt={current:'einamas',time:'laikas',deleteSelected:'Pašalinti pasirinktą'};const lt_LT=lt;const locales$1={en: en$1,en_EN,en_US,it: it$1,it_IT,it_CH,nl: nl$1,nl_NL,nl_BE,de: de$1,de_DE,fr: fr$1,fr_FR,fr_CA,fr_BE,es: es$1,es_ES,uk: uk$1,uk_UA,ru: ru$1,ru_RU,pl,pl_PL,pt: pt$1,pt_BR,pt_PT,ja,ja_JP,lt,lt_LT,sv,sv_SE,nb,nn,nb_NO,nn_NO};/** A custom time bar */class CustomTime extends Component{/**
* @param {{range: Range, dom: Object}} body
* @param {Object} [options] Available parameters:
* {number | string} id
* {string} locales
* {string} locale
* @constructor CustomTime
* @extends Component
*/constructor(body,options){super();this.body=body;// default options
this.defaultOptions={moment:moment$3,locales: locales$1,locale:'en',id:undefined,title:undefined};this.options=availableUtils.extend({},this.defaultOptions);this.setOptions(options);this.options.locales=availableUtils.extend({},locales$1,this.options.locales);const defaultLocales=this.defaultOptions.locales[this.defaultOptions.locale];Object.keys(this.options.locales).forEach(locale=>{this.options.locales[locale]=availableUtils.extend({},defaultLocales,this.options.locales[locale]);});if(options&&options.time!=null){this.customTime=options.time;}else {this.customTime=new Date();}this.eventParams={};// stores state parameters while dragging the bar
// create the DOM
this._create();}/**
* Set options for the component. Options will be merged in current options.
* @param {Object} options Available parameters:
* {number | string} id
* {string} locales
* {string} locale
*/setOptions(options){if(options){// copy all options that we know
availableUtils.selectiveExtend(['moment','locale','locales','id','title','rtl','snap'],this.options,options);}}/**
* Create the DOM for the custom time
* @private
*/_create(){const bar=document.createElement('div');bar['custom-time']=this;bar.className=`vis-custom-time ${this.options.id||''}`;bar.style.position='absolute';bar.style.top='0px';bar.style.height='100%';this.bar=bar;const drag=document.createElement('div');drag.style.position='relative';drag.style.top='0px';if(this.options.rtl){drag.style.right='-10px';}else {drag.style.left='-10px';}drag.style.height='100%';drag.style.width='20px';/**
*
* @param {WheelEvent} e
*/function onMouseWheel(e){this.body.range._onMouseWheel(e);}if(drag.addEventListener){// IE9, Chrome, Safari, Opera
drag.addEventListener("mousewheel",onMouseWheel.bind(this),false);// Firefox
drag.addEventListener("DOMMouseScroll",onMouseWheel.bind(this),false);}else {// IE 6/7/8
drag.attachEvent("onmousewheel",onMouseWheel.bind(this));}bar.appendChild(drag);// attach event listeners
this.hammer=new Hammer(drag);this.hammer.on('panstart',this._onDragStart.bind(this));this.hammer.on('panmove',this._onDrag.bind(this));this.hammer.on('panend',this._onDragEnd.bind(this));this.hammer.get('pan').set({threshold:5,direction:Hammer.DIRECTION_ALL});// delay addition on item click for trackpads...
this.hammer.get('press').set({time:10000});}/**
* Destroy the CustomTime bar
*/destroy(){this.hide();this.hammer.destroy();this.hammer=null;this.body=null;}/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/redraw(){const parent=this.body.dom.backgroundVertical;if(this.bar.parentNode!=parent){// attach to the dom
if(this.bar.parentNode){this.bar.parentNode.removeChild(this.bar);}parent.appendChild(this.bar);}const x=this.body.util.toScreen(this.customTime);let locale=this.options.locales[this.options.locale];if(!locale){if(!this.warned){console.warn(`WARNING: options.locales['${this.options.locale}'] not found. See https://visjs.github.io/vis-timeline/docs/timeline/#Localization`);this.warned=true;}locale=this.options.locales['en'];// fall back on english when not available
}let title=this.options.title;// To hide the title completely use empty string ''.
if(title===undefined){title=`${locale.time}: ${this.options.moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss')}`;title=title.charAt(0).toUpperCase()+title.substring(1);}else if(typeof title==="function"){title=title.call(this,this.customTime);}this.options.rtl?this.bar.style.right=`${x}px`:this.bar.style.left=`${x}px`;this.bar.title=title;return false;}/**
* Remove the CustomTime from the DOM
*/hide(){// remove the line from the DOM
if(this.bar.parentNode){this.bar.parentNode.removeChild(this.bar);}}/**
* Set custom time.
* @param {Date | number | string} time
*/setCustomTime(time){this.customTime=availableUtils.convert(time,'Date');this.redraw();}/**
* Retrieve the current custom time.
* @return {Date} customTime
*/getCustomTime(){return new Date(this.customTime.valueOf());}/**
* Set custom marker.
* @param {string} [title] Title of the custom marker
* @param {boolean} [editable] Make the custom marker editable.
*/setCustomMarker(title,editable){if(this.marker){this.bar.removeChild(this.marker);}this.marker=document.createElement('div');this.marker.className=`vis-custom-time-marker`;this.marker.innerHTML=availableUtils.xss(title);this.marker.style.position='absolute';if(editable){this.marker.setAttribute('contenteditable','true');this.marker.addEventListener('pointerdown',function(){this.marker.focus();});this.marker.addEventListener('input',this._onMarkerChange.bind(this));// The editable div element has no change event, so here emulates the change event.
this.marker.title=title;this.marker.addEventListener('blur',function(event){if(this.title!=event.target.innerHTML){this._onMarkerChanged(event);this.title=event.target.innerHTML;}}.bind(this));}this.bar.appendChild(this.marker);}/**
* Set custom title.
* @param {Date | number | string} title
*/setCustomTitle(title){this.options.title=title;}/**
* Start moving horizontally
* @param {Event} event
* @private
*/_onDragStart(event){this.eventParams.dragging=true;this.eventParams.customTime=this.customTime;event.stopPropagation();}/**
* Perform moving operating.
* @param {Event} event
* @private
*/_onDrag(event){if(!this.eventParams.dragging)return;let deltaX=this.options.rtl?-1*event.deltaX:event.deltaX;const x=this.body.util.toScreen(this.eventParams.customTime)+deltaX;const time=this.body.util.toTime(x);const scale=this.body.util.getScale();const step=this.body.util.getStep();const snap=this.options.snap;const snappedTime=snap?snap(time,scale,step):time;this.setCustomTime(snappedTime);// fire a timechange event
this.body.emitter.emit('timechange',{id:this.options.id,time:new Date(this.customTime.valueOf()),event});event.stopPropagation();}/**
* Stop moving operating.
* @param {Event} event
* @private
*/_onDragEnd(event){if(!this.eventParams.dragging)return;// fire a timechanged event
this.body.emitter.emit('timechanged',{id:this.options.id,time:new Date(this.customTime.valueOf()),event});event.stopPropagation();}/**
* Perform input operating.
* @param {Event} event
* @private
*/_onMarkerChange(event){this.body.emitter.emit('markerchange',{id:this.options.id,title:event.target.innerHTML,event});event.stopPropagation();}/**
* Perform change operating.
* @param {Event} event
* @private
*/_onMarkerChanged(event){this.body.emitter.emit('markerchanged',{id:this.options.id,title:event.target.innerHTML,event});event.stopPropagation();}/**
* Find a custom time from an event target:
* searches for the attribute 'custom-time' in the event target's element tree
* @param {Event} event
* @return {CustomTime | null} customTime
*/static customTimeFromTarget(event){let target=event.target;while(target){if(target.hasOwnProperty('custom-time')){return target['custom-time'];}target=target.parentNode;}return null;}}/**
* Create a timeline visualization
* @constructor Core
*/class Core{/**
* Create the main DOM for the Core: a root panel containing left, right,
* top, bottom, content, and background panel.
* @param {Element} container The container element where the Core will
* be attached.
* @protected
*/_create(container){this.dom={};this.dom.container=container;this.dom.container.style.position='relative';this.dom.root=document.createElement('div');this.dom.background=document.createElement('div');this.dom.backgroundVertical=document.createElement('div');this.dom.backgroundHorizontal=document.createElement('div');this.dom.centerContainer=document.createElement('div');this.dom.leftContainer=document.createElement('div');this.dom.rightContainer=document.createElement('div');this.dom.center=document.createElement('div');this.dom.left=document.createElement('div');this.dom.right=document.createElement('div');this.dom.top=document.createElement('div');this.dom.bottom=document.createElement('div');this.dom.shadowTop=document.createElement('div');this.dom.shadowBottom=document.createElement('div');this.dom.shadowTopLeft=document.createElement('div');this.dom.shadowBottomLeft=document.createElement('div');this.dom.shadowTopRight=document.createElement('div');this.dom.shadowBottomRight=document.createElement('div');this.dom.rollingModeBtn=document.createElement('div');this.dom.loadingScreen=document.createElement('div');this.dom.root.className='vis-timeline';this.dom.background.className='vis-panel vis-background';this.dom.backgroundVertical.className='vis-panel vis-background vis-vertical';this.dom.backgroundHorizontal.className='vis-panel vis-background vis-horizontal';this.dom.centerContainer.className='vis-panel vis-center';this.dom.leftContainer.className='vis-panel vis-left';this.dom.rightContainer.className='vis-panel vis-right';this.dom.top.className='vis-panel vis-top';this.dom.bottom.className='vis-panel vis-bottom';this.dom.left.className='vis-content';this.dom.center.className='vis-content';this.dom.right.className='vis-content';this.dom.shadowTop.className='vis-shadow vis-top';this.dom.shadowBottom.className='vis-shadow vis-bottom';this.dom.shadowTopLeft.className='vis-shadow vis-top';this.dom.shadowBottomLeft.className='vis-shadow vis-bottom';this.dom.shadowTopRight.className='vis-shadow vis-top';this.dom.shadowBottomRight.className='vis-shadow vis-bottom';this.dom.rollingModeBtn.className='vis-rolling-mode-btn';this.dom.loadingScreen.className='vis-loading-screen';this.dom.root.appendChild(this.dom.background);this.dom.root.appendChild(this.dom.backgroundVertical);this.dom.root.appendChild(this.dom.backgroundHorizontal);this.dom.root.appendChild(this.dom.centerContainer);this.dom.root.appendChild(this.dom.leftContainer);this.dom.root.appendChild(this.dom.rightContainer);this.dom.root.appendChild(this.dom.top);this.dom.root.appendChild(this.dom.bottom);this.dom.root.appendChild(this.dom.rollingModeBtn);this.dom.centerContainer.appendChild(this.dom.center);this.dom.leftContainer.appendChild(this.dom.left);this.dom.rightContainer.appendChild(this.dom.right);this.dom.centerContainer.appendChild(this.dom.shadowTop);this.dom.centerContainer.appendChild(this.dom.shadowBottom);this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);this.dom.rightContainer.appendChild(this.dom.shadowTopRight);this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);// size properties of each of the panels
this.props={root:{},background:{},centerContainer:{},leftContainer:{},rightContainer:{},center:{},left:{},right:{},top:{},bottom:{},border:{},scrollTop:0,scrollTopMin:0};this.on('rangechange',()=>{if(this.initialDrawDone===true){this._redraw();}});this.on('rangechanged',()=>{if(!this.initialRangeChangeDone){this.initialRangeChangeDone=true;}});this.on('touch',this._onTouch.bind(this));this.on('panmove',this._onDrag.bind(this));const me=this;this._origRedraw=this._redraw.bind(this);this._redraw=availableUtils.throttle(this._origRedraw);this.on('_change',properties=>{if(me.itemSet&&me.itemSet.initialItemSetDrawn&&properties&&properties.queue==true){me._redraw();}else {me._origRedraw();}});// create event listeners for all interesting events, these events will be
// emitted via emitter
this.hammer=new Hammer(this.dom.root);const pinchRecognizer=this.hammer.get('pinch').set({enable:true});pinchRecognizer&&disablePreventDefaultVertically(pinchRecognizer);this.hammer.get('pan').set({threshold:5,direction:Hammer.DIRECTION_ALL});this.timelineListeners={};const events=['tap','doubletap','press','pinch','pan','panstart','panmove','panend'// TODO: cleanup
//'touch', 'pinch',
//'tap', 'doubletap', 'hold',
//'dragstart', 'drag', 'dragend',
//'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
];events.forEach(type=>{const listener=event=>{if(me.isActive()){me.emit(type,event);}};me.hammer.on(type,listener);me.timelineListeners[type]=listener;});// emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
onTouch$1(this.hammer,event=>{me.emit('touch',event);});// emulate a release event (emitted after a pan, pinch, tap, or press)
onRelease$1(this.hammer,event=>{me.emit('release',event);});/**
*
* @param {WheelEvent} event
*/function onMouseWheel(event){// Reasonable default wheel deltas
const LINE_HEIGHT=40;const PAGE_HEIGHT=800;if(this.isActive()){this.emit('mousewheel',event);}// deltaX and deltaY normalization from jquery.mousewheel.js
let deltaX=0;let deltaY=0;// Old school scrollwheel delta
if('detail'in event){deltaY=event.detail*-1;}if('wheelDelta'in event){deltaY=event.wheelDelta;}if('wheelDeltaY'in event){deltaY=event.wheelDeltaY;}if('wheelDeltaX'in event){deltaX=event.wheelDeltaX*-1;}// Firefox < 17 horizontal scrolling related to DOMMouseScroll event
if('axis'in event&&event.axis===event.HORIZONTAL_AXIS){deltaX=deltaY*-1;deltaY=0;}// New school wheel delta (wheel event)
if('deltaY'in event){deltaY=event.deltaY*-1;}if('deltaX'in event){deltaX=event.deltaX;}// Normalize deltas
if(event.deltaMode){if(event.deltaMode===1){// delta in LINE units
deltaX*=LINE_HEIGHT;deltaY*=LINE_HEIGHT;}else {// delta in PAGE units
deltaX*=LINE_HEIGHT;deltaY*=PAGE_HEIGHT;}}// Prevent scrolling when zooming (no zoom key, or pressing zoom key)
if(this.options.preferZoom){if(!this.options.zoomKey||event[this.options.zoomKey])return;}else {if(this.options.zoomKey&&event[this.options.zoomKey])return;}// Don't preventDefault if you can't scroll
if(!this.options.verticalScroll&&!this.options.horizontalScroll)return;if(this.options.verticalScroll&&Math.abs(deltaY)>=Math.abs(deltaX)){const current=this.props.scrollTop;const adjusted=current+deltaY;if(this.isActive()){const newScrollTop=this._setScrollTop(adjusted);if(newScrollTop!==current){this._redraw();this.emit('scroll',event);// Prevent default actions caused by mouse wheel
// (else the page and timeline both scroll)
event.preventDefault();}}}else if(this.options.horizontalScroll){const delta=Math.abs(deltaX)>=Math.abs(deltaY)?deltaX:deltaY;// calculate a single scroll jump relative to the range scale
const diff=delta/120*(this.range.end-this.range.start)/20;// calculate new start and end
const newStart=this.range.start+diff;const newEnd=this.range.end+diff;const options={animation:false,byUser:true,event};this.range.setRange(newStart,newEnd,options);event.preventDefault();}}// Add modern wheel event listener
const wheelType="onwheel"in document.createElement("div")?"wheel":// Modern browsers support "wheel"
document.onmousewheel!==undefined?"mousewheel":// Webkit and IE support at least "mousewheel"
// DOMMouseScroll - Older Firefox versions use "DOMMouseScroll"
// onmousewheel - All the use "onmousewheel"
this.dom.centerContainer.addEventListener?"DOMMouseScroll":"onmousewheel";this.dom.top.addEventListener?"DOMMouseScroll":"onmousewheel";this.dom.bottom.addEventListener?"DOMMouseScroll":"onmousewheel";this.dom.centerContainer.addEventListener(wheelType,onMouseWheel.bind(this),false);this.dom.top.addEventListener(wheelType,onMouseWheel.bind(this),false);this.dom.bottom.addEventListener(wheelType,onMouseWheel.bind(this),false);/**
*
* @param {scroll} event
*/function onMouseScrollSide(event){if(!me.options.verticalScroll)return;event.preventDefault();if(me.isActive()){const adjusted=-event.target.scrollTop;me._setScrollTop(adjusted);me._redraw();me.emit('scrollSide',event);}}this.dom.left.parentNode.addEventListener('scroll',onMouseScrollSide.bind(this));this.dom.right.parentNode.addEventListener('scroll',onMouseScrollSide.bind(this));let itemAddedToTimeline=false;/**
*
* @param {dragover} event
* @returns {boolean}
*/function handleDragOver(event){if(event.preventDefault){me.emit('dragover',me.getEventProperties(event));event.preventDefault();// Necessary. Allows us to drop.
}// make sure your target is a timeline element
if(!(event.target.className.indexOf("timeline")>-1))return;// make sure only one item is added every time you're over the timeline
if(itemAddedToTimeline)return;event.dataTransfer.dropEffect='move';itemAddedToTimeline=true;return false;}/**
*
* @param {drop} event
* @returns {boolean}
*/function handleDrop(event){// prevent redirect to blank page - Firefox
if(event.preventDefault){event.preventDefault();}if(event.stopPropagation){event.stopPropagation();}// return when dropping non-timeline items
try{var itemData=JSON.parse(event.dataTransfer.getData("text"));if(!itemData||!itemData.content)return;}catch(err){return false;}itemAddedToTimeline=false;event.center={x:event.clientX,y:event.clientY};if(itemData.target!=='item'){me.itemSet._onAddItem(event);}else {me.itemSet._onDropObjectOnItem(event);}me.emit('drop',me.getEventProperties(event));return false;}this.dom.center.addEventListener('dragover',handleDragOver.bind(this),false);this.dom.center.addEventListener('drop',handleDrop.bind(this),false);this.customTimes=[];// store state information needed for touch events
this.touch={};this.redrawCount=0;this.initialDrawDone=false;this.initialRangeChangeDone=false;// attach the root panel to the provided container
if(!container)throw new Error('No container provided');container.appendChild(this.dom.root);container.appendChild(this.dom.loadingScreen);}/**
* Set options. Options will be passed to all components loaded in the Timeline.
* @param {Object} [options]
* {String} orientation
* Vertical orientation for the Timeline,
* can be 'bottom' (default) or 'top'.
* {string | number} width
* Width for the timeline, a number in pixels or
* a css string like '1000px' or '75%'. '100%' by default.
* {string | number} height
* Fixed height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'. If undefined,
* The Timeline will automatically size such that
* its contents fit.
* {string | number} minHeight
* Minimum height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'.
* {string | number} maxHeight
* Maximum height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'.
* {number | Date | string} start
* Start date for the visible window
* {number | Date | string} end
* End date for the visible window
*/setOptions(options){if(options){// copy the known options
const fields=['width','height','minHeight','maxHeight','autoResize','start','end','clickToUse','dataAttributes','hiddenDates','locale','locales','moment','preferZoom','rtl','zoomKey','horizontalScroll','verticalScroll','longSelectPressTime','snap'];availableUtils.selectiveExtend(fields,this.options,options);this.dom.rollingModeBtn.style.visibility='hidden';if(this.options.rtl){this.dom.container.style.direction="rtl";this.dom.backgroundVertical.className='vis-panel vis-background vis-vertical-rtl';}if(this.options.verticalScroll){if(this.options.rtl){this.dom.rightContainer.className='vis-panel vis-right vis-vertical-scroll';}else {this.dom.leftContainer.className='vis-panel vis-left vis-vertical-scroll';}}if(typeof this.options.orientation!=='object'){this.options.orientation={item:undefined,axis:undefined};}if('orientation'in options){if(typeof options.orientation==='string'){this.options.orientation={item:options.orientation,axis:options.orientation};}else if(typeof options.orientation==='object'){if('item'in options.orientation){this.options.orientation.item=options.orientation.item;}if('axis'in options.orientation){this.options.orientation.axis=options.orientation.axis;}}}if(this.options.orientation.axis==='both'){if(!this.timeAxis2){const timeAxis2=this.timeAxis2=new TimeAxis(this.body,this.options);timeAxis2.setOptions=options=>{const _options=options?availableUtils.extend({},options):{};_options.orientation='top';// override the orientation option, always top
TimeAxis.prototype.setOptions.call(timeAxis2,_options);};this.components.push(timeAxis2);}}else {if(this.timeAxis2){const index=this.components.indexOf(this.timeAxis2);if(index!==-1){this.components.splice(index,1);}this.timeAxis2.destroy();this.timeAxis2=null;}}// if the graph2d's drawPoints is a function delegate the callback to the onRender property
if(typeof options.drawPoints=='function'){options.drawPoints={onRender:options.drawPoints};}if('hiddenDates'in this.options){convertHiddenOptions(this.options.moment,this.body,this.options.hiddenDates);}if('clickToUse'in options){if(options.clickToUse){if(!this.activator){this.activator=new Activator(this.dom.root);}}else {if(this.activator){this.activator.destroy();delete this.activator;}}}// enable/disable autoResize
this._initAutoResize();}// propagate options to all components
this.components.forEach(component=>component.setOptions(options));// enable/disable configure
if('configure'in options){if(!this.configurator){this.configurator=this._createConfigurator();}this.configurator.setOptions(options.configure);// collect the settings of all components, and pass them to the configuration system
const appliedOptions=availableUtils.deepExtend({},this.options);this.components.forEach(component=>{availableUtils.deepExtend(appliedOptions,component.options);});this.configurator.setModuleOptions({global:appliedOptions});}this._redraw();}/**
* Returns true when the Timeline is active.
* @returns {boolean}
*/isActive(){return !this.activator||this.activator.active;}/**
* Destroy the Core, clean up all DOM elements and event listeners.
*/destroy(){// unbind datasets
this.setItems(null);this.setGroups(null);// remove all event listeners
this.off();// stop checking for changed size
this._stopAutoResize();// remove from DOM
if(this.dom.root.parentNode){this.dom.root.parentNode.removeChild(this.dom.root);}this.dom=null;// remove Activator
if(this.activator){this.activator.destroy();delete this.activator;}// cleanup hammer touch events
for(const event in this.timelineListeners){if(this.timelineListeners.hasOwnProperty(event)){delete this.timelineListeners[event];}}this.timelineListeners=null;this.hammer&&this.hammer.destroy();this.hammer=null;// give all components the opportunity to cleanup
this.components.forEach(component=>component.destroy());this.body=null;}/**
* Set a custom time bar
* @param {Date} time
* @param {number} [id=undefined] Optional id of the custom time bar to be adjusted.
*/setCustomTime(time,id){const customTimes=this.customTimes.filter(component=>id===component.options.id);if(customTimes.length===0){throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`);}if(customTimes.length>0){customTimes[0].setCustomTime(time);}}/**
* Retrieve the current custom time.
* @param {number} [id=undefined] Id of the custom time bar.
* @return {Date | undefined} customTime
*/getCustomTime(id){const customTimes=this.customTimes.filter(component=>component.options.id===id);if(customTimes.length===0){throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`);}return customTimes[0].getCustomTime();}/**
* Set a custom marker for the custom time bar.
* @param {string} [title] Title of the custom marker.
* @param {number} [id=undefined] Id of the custom marker.
* @param {boolean} [editable=false] Make the custom marker editable.
*/setCustomTimeMarker(title,id,editable){const customTimes=this.customTimes.filter(component=>component.options.id===id);if(customTimes.length===0){throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`);}if(customTimes.length>0){customTimes[0].setCustomMarker(title,editable);}}/**
* Set a custom title for the custom time bar.
* @param {string} [title] Custom title
* @param {number} [id=undefined] Id of the custom time bar.
* @returns {*}
*/setCustomTimeTitle(title,id){const customTimes=this.customTimes.filter(component=>component.options.id===id);if(customTimes.length===0){throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`);}if(customTimes.length>0){return customTimes[0].setCustomTitle(title);}}/**
* Retrieve meta information from an event.
* Should be overridden by classes extending Core
* @param {Event} event
* @return {Object} An object with related information.
*/getEventProperties(event){return {event};}/**
* Add custom vertical bar
* @param {Date | string | number} [time] A Date, unix timestamp, or
* ISO date string. Time point where
* the new bar should be placed.
* If not provided, `new Date()` will
* be used.
* @param {number | string} [id=undefined] Id of the new bar. Optional
* @return {number | string} Returns the id of the new bar
*/addCustomTime(time,id){const timestamp=time!==undefined?availableUtils.convert(time,'Date'):new Date();const exists=this.customTimes.some(customTime=>customTime.options.id===id);if(exists){throw new Error(`A custom time with id ${JSON.stringify(id)} already exists`);}const customTime=new CustomTime(this.body,availableUtils.extend({},this.options,{time:timestamp,id,snap:this.itemSet?this.itemSet.options.snap:this.options.snap}));this.customTimes.push(customTime);this.components.push(customTime);this._redraw();return id;}/**
* Remove previously added custom bar
* @param {int} id ID of the custom bar to be removed
* [at]returns {boolean} True if the bar exists and is removed, false otherwise
*/removeCustomTime(id){const customTimes=this.customTimes.filter(bar=>bar.options.id===id);if(customTimes.length===0){throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`);}customTimes.forEach(customTime=>{this.customTimes.splice(this.customTimes.indexOf(customTime),1);this.components.splice(this.components.indexOf(customTime),1);customTime.destroy();});}/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/getVisibleItems(){return this.itemSet&&this.itemSet.getVisibleItems()||[];}/**
* Get the id's of the items at specific time, where a click takes place on the timeline.
* @returns {Array} The ids of all items in existence at the time of event.
*/getItemsAtCurrentTime(timeOfEvent){this.time=timeOfEvent;return this.itemSet&&this.itemSet.getItemsAtCurrentTime(this.time)||[];}/**
* Get the id's of the currently visible groups.
* @returns {Array} The ids of the visible groups
*/getVisibleGroups(){return this.itemSet&&this.itemSet.getVisibleGroups()||[];}/**
* Set Core window such that it fits all items
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/fit(options,callback){const range=this.getDataRange();// skip range set if there is no min and max date
if(range.min===null&&range.max===null){return;}// apply a margin of 1% left and right of the data
const interval=range.max-range.min;const min=new Date(range.min.valueOf()-interval*0.01);const max=new Date(range.max.valueOf()+interval*0.01);const animation=options&&options.animation!==undefined?options.animation:true;this.range.setRange(min,max,{animation},callback);}/**
* Calculate the data range of the items start and end dates
* [at]returns {{min: [Date], max: [Date]}}
* @protected
*/getDataRange(){// must be implemented by Timeline and Graph2d
throw new Error('Cannot invoke abstract method getDataRange');}/**
* Set the visible window. Both parameters are optional, you can change only
* start or only end. Syntax:
*
* TimeLine.setWindow(start, end)
* TimeLine.setWindow(start, end, options)
* TimeLine.setWindow(range)
*
* Where start and end can be a Date, number, or string, and range is an
* object with properties start and end.
*
* @param {Date | number | string | Object} [start] Start date of visible window
* @param {Date | number | string} [end] End date of visible window
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/setWindow(start,end,options,callback){if(typeof arguments[2]=="function"){callback=arguments[2];options={};}let animation;let range;if(arguments.length==1){range=arguments[0];animation=range.animation!==undefined?range.animation:true;this.range.setRange(range.start,range.end,{animation});}else if(arguments.length==2&&typeof arguments[1]=="function"){range=arguments[0];callback=arguments[1];animation=range.animation!==undefined?range.animation:true;this.range.setRange(range.start,range.end,{animation},callback);}else {animation=options&&options.animation!==undefined?options.animation:true;this.range.setRange(start,end,{animation},callback);}}/**
* Move the window such that given time is centered on screen.
* @param {Date | number | string} time
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/moveTo(time,options,callback){if(typeof arguments[1]=="function"){callback=arguments[1];options={};}const interval=this.range.end-this.range.start;const t=availableUtils.convert(time,'Date').valueOf();const start=t-interval/2;const end=t+interval/2;const animation=options&&options.animation!==undefined?options.animation:true;this.range.setRange(start,end,{animation},callback);}/**
* Get the visible window
* @return {{start: Date, end: Date}} Visible range
*/getWindow(){const range=this.range.getRange();return {start:new Date(range.start),end:new Date(range.end)};}/**
* Zoom in the window such that given time is centered on screen.
* @param {number} percentage - must be between [0..1]
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/zoomIn(percentage,options,callback){if(!percentage||percentage<0||percentage>1)return;if(typeof arguments[1]=="function"){callback=arguments[1];options={};}const range=this.getWindow();const start=range.start.valueOf();const end=range.end.valueOf();const interval=end-start;const newInterval=interval/(1+percentage);const distance=(interval-newInterval)/2;const newStart=start+distance;const newEnd=end-distance;this.setWindow(newStart,newEnd,options,callback);}/**
* Zoom out the window such that given time is centered on screen.
* @param {number} percentage - must be between [0..1]
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/zoomOut(percentage,options,callback){if(!percentage||percentage<0||percentage>1)return;if(typeof arguments[1]=="function"){callback=arguments[1];options={};}const range=this.getWindow();const start=range.start.valueOf();const end=range.end.valueOf();const interval=end-start;const newStart=start-interval*percentage/2;const newEnd=end+interval*percentage/2;this.setWindow(newStart,newEnd,options,callback);}/**
* Force a redraw. Can be overridden by implementations of Core
*
* Note: this function will be overridden on construction with a trottled version
*/redraw(){this._redraw();}/**
* Redraw for internal use. Redraws all components. See also the public
* method redraw.
* @protected
*/_redraw(){this.redrawCount++;const dom=this.dom;if(!dom||!dom.container||dom.root.offsetWidth==0)return;// when destroyed, or invisible
let resized=false;const options=this.options;const props=this.props;updateHiddenDates(this.options.moment,this.body,this.options.hiddenDates);// update class names
if(options.orientation=='top'){availableUtils.addClassName(dom.root,'vis-top');availableUtils.removeClassName(dom.root,'vis-bottom');}else {availableUtils.removeClassName(dom.root,'vis-top');availableUtils.addClassName(dom.root,'vis-bottom');}if(options.rtl){availableUtils.addClassName(dom.root,'vis-rtl');availableUtils.removeClassName(dom.root,'vis-ltr');}else {availableUtils.addClassName(dom.root,'vis-ltr');availableUtils.removeClassName(dom.root,'vis-rtl');}// update root width and height options
dom.root.style.maxHeight=availableUtils.option.asSize(options.maxHeight,'');dom.root.style.minHeight=availableUtils.option.asSize(options.minHeight,'');dom.root.style.width=availableUtils.option.asSize(options.width,'');const rootOffsetWidth=dom.root.offsetWidth;// calculate border widths
props.border.left=1;props.border.right=1;props.border.top=1;props.border.bottom=1;// calculate the heights. If any of the side panels is empty, we set the height to
// minus the border width, such that the border will be invisible
props.center.height=dom.center.offsetHeight;props.left.height=dom.left.offsetHeight;props.right.height=dom.right.offsetHeight;props.top.height=dom.top.clientHeight||-props.border.top;props.bottom.height=Math.round(dom.bottom.getBoundingClientRect().height)||dom.bottom.clientHeight||-props.border.bottom;// TODO: compensate borders when any of the panels is empty.
// apply auto height
// TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
const contentHeight=Math.max(props.left.height,props.center.height,props.right.height);const autoHeight=props.top.height+contentHeight+props.bottom.height+props.border.top+props.border.bottom;dom.root.style.height=availableUtils.option.asSize(options.height,`${autoHeight}px`);// calculate heights of the content panels
props.root.height=dom.root.offsetHeight;props.background.height=props.root.height;const containerHeight=props.root.height-props.top.height-props.bottom.height;props.centerContainer.height=containerHeight;props.leftContainer.height=containerHeight;props.rightContainer.height=props.leftContainer.height;// calculate the widths of the panels
props.root.width=rootOffsetWidth;props.background.width=props.root.width;if(!this.initialDrawDone){props.scrollbarWidth=availableUtils.getScrollBarWidth();}const leftContainerClientWidth=dom.leftContainer.clientWidth;const rightContainerClientWidth=dom.rightContainer.clientWidth;if(options.verticalScroll){if(options.rtl){props.left.width=leftContainerClientWidth||-props.border.left;props.right.width=rightContainerClientWidth+props.scrollbarWidth||-props.border.right;}else {props.left.width=leftContainerClientWidth+props.scrollbarWidth||-props.border.left;props.right.width=rightContainerClientWidth||-props.border.right;}}else {props.left.width=leftContainerClientWidth||-props.border.left;props.right.width=rightContainerClientWidth||-props.border.right;}this._setDOM();// update the scrollTop, feasible range for the offset can be changed
// when the height of the Core or of the contents of the center changed
let offset=this._updateScrollTop();// reposition the scrollable contents
if(options.orientation.item!='top'){offset+=Math.max(props.centerContainer.height-props.center.height-props.border.top-props.border.bottom,0);}dom.center.style.transform=`translateY(${offset}px)`;// show shadows when vertical scrolling is available
const visibilityTop=props.scrollTop==0?'hidden':'';const visibilityBottom=props.scrollTop==props.scrollTopMin?'hidden':'';dom.shadowTop.style.visibility=visibilityTop;dom.shadowBottom.style.visibility=visibilityBottom;dom.shadowTopLeft.style.visibility=visibilityTop;dom.shadowBottomLeft.style.visibility=visibilityBottom;dom.shadowTopRight.style.visibility=visibilityTop;dom.shadowBottomRight.style.visibility=visibilityBottom;if(options.verticalScroll){dom.rightContainer.className='vis-panel vis-right vis-vertical-scroll';dom.leftContainer.className='vis-panel vis-left vis-vertical-scroll';dom.shadowTopRight.style.visibility="hidden";dom.shadowBottomRight.style.visibility="hidden";dom.shadowTopLeft.style.visibility="hidden";dom.shadowBottomLeft.style.visibility="hidden";dom.left.style.top='0px';dom.right.style.top='0px';}if(!options.verticalScroll||props.center.height<props.centerContainer.height){dom.left.style.top=`${offset}px`;dom.right.style.top=`${offset}px`;dom.rightContainer.className=dom.rightContainer.className.replace(new RegExp('(?:^|\\s)'+'vis-vertical-scroll'+'(?:\\s|$)'),' ');dom.leftContainer.className=dom.leftContainer.className.replace(new RegExp('(?:^|\\s)'+'vis-vertical-scroll'+'(?:\\s|$)'),' ');props.left.width=leftContainerClientWidth||-props.border.left;props.right.width=rightContainerClientWidth||-props.border.right;this._setDOM();}// enable/disable vertical panning
const contentsOverflow=props.center.height>props.centerContainer.height;this.hammer.get('pan').set({direction:contentsOverflow?Hammer.DIRECTION_ALL:Hammer.DIRECTION_HORIZONTAL});// set the long press time
this.hammer.get('press').set({time:this.options.longSelectPressTime});// redraw all components
this.components.forEach(component=>{resized=component.redraw()||resized;});const MAX_REDRAW=5;if(resized){if(this.redrawCount<MAX_REDRAW){this.body.emitter.emit('_change');return;}else {console.log('WARNING: infinite loop in redraw?');}}else {this.redrawCount=0;}//Emit public 'changed' event for UI updates, see issue #1592
this.body.emitter.emit("changed");}/**
* sets the basic DOM components needed for the timeline\graph2d
*/_setDOM(){const props=this.props;const dom=this.dom;props.leftContainer.width=props.left.width;props.rightContainer.width=props.right.width;const centerWidth=props.root.width-props.left.width-props.right.width;props.center.width=centerWidth;props.centerContainer.width=centerWidth;props.top.width=centerWidth;props.bottom.width=centerWidth;// resize the panels
dom.background.style.height=`${props.background.height}px`;dom.backgroundVertical.style.height=`${props.background.height}px`;dom.backgroundHorizontal.style.height=`${props.centerContainer.height}px`;dom.centerContainer.style.height=`${props.centerContainer.height}px`;dom.leftContainer.style.height=`${props.leftContainer.height}px`;dom.rightContainer.style.height=`${props.rightContainer.height}px`;dom.background.style.width=`${props.background.width}px`;dom.backgroundVertical.style.width=`${props.centerContainer.width}px`;dom.backgroundHorizontal.style.width=`${props.background.width}px`;dom.centerContainer.style.width=`${props.center.width}px`;dom.top.style.width=`${props.top.width}px`;dom.bottom.style.width=`${props.bottom.width}px`;// reposition the panels
dom.background.style.left='0';dom.background.style.top='0';dom.backgroundVertical.style.left=`${props.left.width+props.border.left}px`;dom.backgroundVertical.style.top='0';dom.backgroundHorizontal.style.left='0';dom.backgroundHorizontal.style.top=`${props.top.height}px`;dom.centerContainer.style.left=`${props.left.width}px`;dom.centerContainer.style.top=`${props.top.height}px`;dom.leftContainer.style.left='0';dom.leftContainer.style.top=`${props.top.height}px`;dom.rightContainer.style.left=`${props.left.width+props.center.width}px`;dom.rightContainer.style.top=`${props.top.height}px`;dom.top.style.left=`${props.left.width}px`;dom.top.style.top='0';dom.bottom.style.left=`${props.left.width}px`;dom.bottom.style.top=`${props.top.height+props.centerContainer.height}px`;dom.center.style.left='0';dom.left.style.left='0';dom.right.style.left='0';}/**
* Set a current time. This can be used for example to ensure that a client's
* time is synchronized with a shared server time.
* Only applicable when option `showCurrentTime` is true.
* @param {Date | string | number} time A Date, unix timestamp, or
* ISO date string.
*/setCurrentTime(time){if(!this.currentTime){throw new Error('Option showCurrentTime must be true');}this.currentTime.setCurrentTime(time);}/**
* Get the current time.
* Only applicable when option `showCurrentTime` is true.
* @return {Date} Returns the current time.
*/getCurrentTime(){if(!this.currentTime){throw new Error('Option showCurrentTime must be true');}return this.currentTime.getCurrentTime();}/**
* Convert a position on screen (pixels) to a datetime
* @param {int} x Position on the screen in pixels
* @return {Date} time The datetime the corresponds with given position x
* @protected
* TODO: move this function to Range
*/_toTime(x){return toTime(this,x,this.props.center.width);}/**
* Convert a position on the global screen (pixels) to a datetime
* @param {int} x Position on the screen in pixels
* @return {Date} time The datetime the corresponds with given position x
* @protected
* TODO: move this function to Range
*/_toGlobalTime(x){return toTime(this,x,this.props.root.width);//var conversion = this.range.conversion(this.props.root.width);
//return new Date(x / conversion.scale + conversion.offset);
}/**
* Convert a datetime (Date object) into a position on the screen
* @param {Date} time A date
* @return {int} x The position on the screen in pixels which corresponds
* with the given date.
* @protected
* TODO: move this function to Range
*/_toScreen(time){return toScreen(this,time,this.props.center.width);}/**
* Convert a datetime (Date object) into a position on the root
* This is used to get the pixel density estimate for the screen, not the center panel
* @param {Date} time A date
* @return {int} x The position on root in pixels which corresponds
* with the given date.
* @protected
* TODO: move this function to Range
*/_toGlobalScreen(time){return toScreen(this,time,this.props.root.width);//var conversion = this.range.conversion(this.props.root.width);
//return (time.valueOf() - conversion.offset) * conversion.scale;
}/**
* Initialize watching when option autoResize is true
* @private
*/_initAutoResize(){if(this.options.autoResize==true){this._startAutoResize();}else {this._stopAutoResize();}}/**
* Watch for changes in the size of the container. On resize, the Panel will
* automatically redraw itself.
* @private
*/_startAutoResize(){const me=this;this._stopAutoResize();this._onResize=()=>{if(me.options.autoResize!=true){// stop watching when the option autoResize is changed to false
me._stopAutoResize();return;}if(me.dom.root){const rootOffsetHeight=me.dom.root.offsetHeight;const rootOffsetWidth=me.dom.root.offsetWidth;// check whether the frame is resized
// Note: we compare offsetWidth here, not clientWidth. For some reason,
// IE does not restore the clientWidth from 0 to the actual width after
// changing the timeline's container display style from none to visible
if(rootOffsetWidth!=me.props.lastWidth||rootOffsetHeight!=me.props.lastHeight){me.props.lastWidth=rootOffsetWidth;me.props.lastHeight=rootOffsetHeight;me.props.scrollbarWidth=availableUtils.getScrollBarWidth();me.body.emitter.emit('_change');}}};// add event listener to window resize
window.addEventListener('resize',this._onResize);//Prevent initial unnecessary redraw
if(me.dom.root){me.props.lastWidth=me.dom.root.offsetWidth;me.props.lastHeight=me.dom.root.offsetHeight;}this.watchTimer=setInterval(this._onResize,1000);}/**
* Stop watching for a resize of the frame.
* @private
*/_stopAutoResize(){if(this.watchTimer){clearInterval(this.watchTimer);this.watchTimer=undefined;}// remove event listener on window.resize
if(this._onResize){window.removeEventListener('resize',this._onResize);this._onResize=null;}}/**
* Start moving the timeline vertically
* @param {Event} event
* @private
*/_onTouch(event){// eslint-disable-line no-unused-vars
this.touch.allowDragging=true;this.touch.initialScrollTop=this.props.scrollTop;}/**
* Start moving the timeline vertically
* @param {Event} event
* @private
*/_onPinch(event){// eslint-disable-line no-unused-vars
this.touch.allowDragging=false;}/**
* Move the timeline vertically
* @param {Event} event
* @private
*/_onDrag(event){if(!event)return;// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if(!this.touch.allowDragging)return;const delta=event.deltaY;const oldScrollTop=this._getScrollTop();const newScrollTop=this._setScrollTop(this.touch.initialScrollTop+delta);if(this.options.verticalScroll){this.dom.left.parentNode.scrollTop=-this.props.scrollTop;this.dom.right.parentNode.scrollTop=-this.props.scrollTop;}if(newScrollTop!=oldScrollTop){this.emit("verticalDrag");}}/**
* Apply a scrollTop
* @param {number} scrollTop
* @returns {number} scrollTop Returns the applied scrollTop
* @private
*/_setScrollTop(scrollTop){this.props.scrollTop=scrollTop;this._updateScrollTop();return this.props.scrollTop;}/**
* Update the current scrollTop when the height of the containers has been changed
* @returns {number} scrollTop Returns the applied scrollTop
* @private
*/_updateScrollTop(){// recalculate the scrollTopMin
const scrollTopMin=Math.min(this.props.centerContainer.height-this.props.border.top-this.props.border.bottom-this.props.center.height,0);// is negative or zero
if(scrollTopMin!=this.props.scrollTopMin){// in case of bottom orientation, change the scrollTop such that the contents
// do not move relative to the time axis at the bottom
if(this.options.orientation.item!='top'){this.props.scrollTop+=scrollTopMin-this.props.scrollTopMin;}this.props.scrollTopMin=scrollTopMin;}// limit the scrollTop to the feasible scroll range
if(this.props.scrollTop>0)this.props.scrollTop=0;if(this.props.scrollTop<scrollTopMin)this.props.scrollTop=scrollTopMin;if(this.options.verticalScroll){this.dom.left.parentNode.scrollTop=-this.props.scrollTop;this.dom.right.parentNode.scrollTop=-this.props.scrollTop;}return this.props.scrollTop;}/**
* Get the current scrollTop
* @returns {number} scrollTop
* @private
*/_getScrollTop(){return this.props.scrollTop;}/**
* Load a configurator
* [at]returns {Object}
* @private
*/_createConfigurator(){throw new Error('Cannot invoke abstract method _createConfigurator');}}// turn Core into an event emitter
componentEmitter(Core.prototype);/**
* A current time bar
*/class CurrentTime extends Component{/**
* @param {{range: Range, dom: Object, domProps: Object}} body
* @param {Object} [options] Available parameters:
* {Boolean} [showCurrentTime]
* {String} [alignCurrentTime]
* @constructor CurrentTime
* @extends Component
*/constructor(body,options){super();this.body=body;// default options
this.defaultOptions={rtl:false,showCurrentTime:true,alignCurrentTime:undefined,moment:moment$3,locales: locales$1,locale:'en'};this.options=availableUtils.extend({},this.defaultOptions);this.setOptions(options);this.options.locales=availableUtils.extend({},locales$1,this.options.locales);const defaultLocales=this.defaultOptions.locales[this.defaultOptions.locale];Object.keys(this.options.locales).forEach(locale=>{this.options.locales[locale]=availableUtils.extend({},defaultLocales,this.options.locales[locale]);});this.offset=0;this._create();}/**
* Create the HTML DOM for the current time bar
* @private
*/_create(){const bar=document.createElement('div');bar.className='vis-current-time';bar.style.position='absolute';bar.style.top='0px';bar.style.height='100%';this.bar=bar;}/**
* Destroy the CurrentTime bar
*/destroy(){this.options.showCurrentTime=false;this.redraw();// will remove the bar from the DOM and stop refreshing
this.body=null;}/**
* Set options for the component. Options will be merged in current options.
* @param {Object} options Available parameters:
* {boolean} [showCurrentTime]
* {String} [alignCurrentTime]
*/setOptions(options){if(options){// copy all options that we know
availableUtils.selectiveExtend(['rtl','showCurrentTime','alignCurrentTime','moment','locale','locales'],this.options,options);}}/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/redraw(){if(this.options.showCurrentTime){const parent=this.body.dom.backgroundVertical;if(this.bar.parentNode!=parent){// attach to the dom
if(this.bar.parentNode){this.bar.parentNode.removeChild(this.bar);}parent.appendChild(this.bar);this.start();}let now=this.options.moment(Date.now()+this.offset);if(this.options.alignCurrentTime){now=now.startOf(this.options.alignCurrentTime);}const x=this.body.util.toScreen(now);let locale=this.options.locales[this.options.locale];if(!locale){if(!this.warned){console.warn(`WARNING: options.locales['${this.options.locale}'] not found. See https://visjs.github.io/vis-timeline/docs/timeline/#Localization`);this.warned=true;}locale=this.options.locales['en'];// fall back on english when not available
}let title=`${locale.current} ${locale.time}: ${now.format('dddd, MMMM Do YYYY, H:mm:ss')}`;title=title.charAt(0).toUpperCase()+title.substring(1);if(this.options.rtl){this.bar.style.transform=`translateX(${x*-1}px)`;}else {this.bar.style.transform=`translateX(${x}px)`;}this.bar.title=title;}else {// remove the line from the DOM
if(this.bar.parentNode){this.bar.parentNode.removeChild(this.bar);}this.stop();}return false;}/**
* Start auto refreshing the current time bar
*/start(){const me=this;/**
* Updates the current time.
*/function update(){me.stop();// determine interval to refresh
const scale=me.body.range.conversion(me.body.domProps.center.width).scale;let interval=1/scale/10;if(interval<30)interval=30;if(interval>1000)interval=1000;me.redraw();me.body.emitter.emit('currentTimeTick');// start a renderTimer to adjust for the new time
me.currentTimeTimer=setTimeout(update,interval);}update();}/**
* Stop auto refreshing the current time bar
*/stop(){if(this.currentTimeTimer!==undefined){clearTimeout(this.currentTimeTimer);delete this.currentTimeTimer;}}/**
* Set a current time. This can be used for example to ensure that a client's
* time is synchronized with a shared server time.
* @param {Date | string | number} time A Date, unix timestamp, or
* ISO date string.
*/setCurrentTime(time){const t=availableUtils.convert(time,'Date').valueOf();const now=Date.now();this.offset=t-now;this.redraw();}/**
* Get the current time.
* @return {Date} Returns the current time.
*/getCurrentTime(){return new Date(Date.now()+this.offset);}}// Utility functions for ordering and stacking of items
const EPSILON=0.001;// used when checking collisions, to prevent round-off errors
/**
* Order items by their start data
* @param {Item[]} items
*/function orderByStart(items){items.sort((a,b)=>a.data.start-b.data.start);}/**
* Order items by their end date. If they have no end date, their start date
* is used.
* @param {Item[]} items
*/function orderByEnd(items){items.sort((a,b)=>{const aTime='end'in a.data?a.data.end:a.data.start;const bTime='end'in b.data?b.data.end:b.data.start;return aTime-bTime;});}/**
* Adjust vertical positions of the items such that they don't overlap each
* other.
* @param {Item[]} items
* All visible items
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
* @param {boolean} [force=false]
* If true, all items will be repositioned. If false (default), only
* items having a top===null will be re-stacked
* @param {function} shouldBailItemsRedrawFunction
* bailing function
* @return {boolean} shouldBail
*/function stack(items,margin,force,shouldBailItemsRedrawFunction){const stackingResult=performStacking(items,margin.item,false,item=>item.stack&&(force||item.top===null),item=>item.stack,item=>margin.axis,shouldBailItemsRedrawFunction);// If shouldBail function returned true during stacking calculation
return stackingResult===null;}/**
* Adjust vertical positions of the items within a single subgroup such that they
* don't overlap each other.
* @param {Item[]} items
* All items withina subgroup
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
* @param {subgroup} subgroup
* The subgroup that is being stacked
*/function substack(items,margin,subgroup){const subgroupHeight=performStacking(items,margin.item,false,item=>item.stack,item=>true,item=>item.baseTop);subgroup.height=subgroupHeight-subgroup.top+0.5*margin.item.vertical;}/**
* Adjust vertical positions of the items without stacking them
* @param {Item[]} items
* All visible items
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
* @param {subgroups[]} subgroups
* All subgroups
* @param {boolean} isStackSubgroups
*/function nostack(items,margin,subgroups,isStackSubgroups){for(let i=0;i<items.length;i++){if(items[i].data.subgroup==undefined){items[i].top=margin.item.vertical;}else if(items[i].data.subgroup!==undefined&&isStackSubgroups){let newTop=0;for(const subgroup in subgroups){if(subgroups.hasOwnProperty(subgroup)){if(subgroups[subgroup].visible==true&&subgroups[subgroup].index<subgroups[items[i].data.subgroup].index){newTop+=subgroups[subgroup].height;subgroups[items[i].data.subgroup].top=newTop;}}}items[i].top=newTop+0.5*margin.item.vertical;}}if(!isStackSubgroups){stackSubgroups(items,margin,subgroups);}}/**
* Adjust vertical positions of the subgroups such that they don't overlap each
* other.
* @param {Array.<timeline.Item>} items
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin Margins between items and between items and the axis.
* @param {subgroups[]} subgroups
* All subgroups
*/function stackSubgroups(items,margin,subgroups){performStacking(Object.values(subgroups).sort((a,b)=>{if(a.index>b.index)return 1;if(a.index<b.index)return -1;return 0;}),{vertical:0},true,item=>true,item=>true,item=>0);for(let i=0;i<items.length;i++){if(items[i].data.subgroup!==undefined){items[i].top=subgroups[items[i].data.subgroup].top+0.5*margin.item.vertical;}}}/**
* Adjust vertical positions of the subgroups such that they don't overlap each
* other, then stacks the contents of each subgroup individually.
* @param {Item[]} subgroupItems
* All the items in a subgroup
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
* @param {subgroups[]} subgroups
* All subgroups
*/function stackSubgroupsWithInnerStack(subgroupItems,margin,subgroups){let doSubStack=false;// Run subgroups in their order (if any)
const subgroupOrder=[];for(var subgroup in subgroups){if(subgroups[subgroup].hasOwnProperty("index")){subgroupOrder[subgroups[subgroup].index]=subgroup;}else {subgroupOrder.push(subgroup);}}for(let j=0;j<subgroupOrder.length;j++){subgroup=subgroupOrder[j];if(subgroups.hasOwnProperty(subgroup)){doSubStack=doSubStack||subgroups[subgroup].stack;subgroups[subgroup].top=0;for(const otherSubgroup in subgroups){if(subgroups[otherSubgroup].visible&&subgroups[subgroup].index>subgroups[otherSubgroup].index){subgroups[subgroup].top+=subgroups[otherSubgroup].height;}}const items=subgroupItems[subgroup];for(let i=0;i<items.length;i++){if(items[i].data.subgroup!==undefined){items[i].top=subgroups[items[i].data.subgroup].top+0.5*margin.item.vertical;if(subgroups[subgroup].stack){items[i].baseTop=items[i].top;}}}if(doSubStack&&subgroups[subgroup].stack){substack(subgroupItems[subgroup],margin,subgroups[subgroup]);}}}}/**
* Reusable stacking function
*
* @param {Item[]} items
* An array of items to consider during stacking.
* @param {{horizontal: number, vertical: number}} margins
* Margins to be used for collision checking and placement of items.
* @param {boolean} compareTimes
* By default, horizontal collision is checked based on the spatial position of the items (left/right and width).
* If this argument is true, horizontal collision will instead be checked based on the start/end times of each item.
* Vertical collision is always checked spatially.
* @param {(Item) => number | null} shouldStack
* A callback function which is called before we start to process an item. The return value indicates whether the item will be processed.
* @param {(Item) => boolean} shouldOthersStack
* A callback function which indicates whether other items should consider this item when being stacked.
* @param {(Item) => number} getInitialHeight
* A callback function which determines the height items are initially placed at
* @param {() => boolean} shouldBail
* A callback function which should indicate if the stacking process should be aborted.
*
* @returns {null|number}
* if shouldBail was triggered, returns null
* otherwise, returns the maximum height
*/function performStacking(items,margins,compareTimes,shouldStack,shouldOthersStack,getInitialHeight,shouldBail){// Time-based horizontal comparison
let getItemStart=item=>item.start;let getItemEnd=item=>item.end;if(!compareTimes){// Spatial horizontal comparisons
const rtl=!!(items[0]&&items[0].options.rtl);if(rtl){getItemStart=item=>item.right;}else {getItemStart=item=>item.left;}getItemEnd=item=>getItemStart(item)+item.width+margins.horizontal;}const itemsToPosition=[];const itemsAlreadyPositioned=[];// It's vital that this array is kept sorted based on the start of each item
// If the order we needed to place items was based purely on the start of each item, we could calculate stacking very efficiently.
// Unfortunately for us, this is not guaranteed. But the order is often based on the start of items at least to some degree, and
// we can use this to make some optimisations. While items are proceeding in order of start, we can keep moving our search indexes
// forwards. Then if we encounter an item that's out of order, we reset our indexes and search from the beginning of the array again.
let previousStart=null;let insertionIndex=0;// First let's handle any immoveable items
for(const item of items){if(shouldStack(item)){itemsToPosition.push(item);}else {if(shouldOthersStack(item)){const itemStart=getItemStart(item);// We need to put immoveable items into itemsAlreadyPositioned and ensure that this array is sorted.
// We could simply insert them, and then use JavaScript's sort function to sort them afterwards.
// This would achieve an average complexity of O(n log n).
//
// Instead, I'm gambling that the start of each item will usually be the same or later than the
// start of the previous item. While this holds (best case), we can insert items in O(n).
// In the worst case (where each item starts before the previous item) this grows to O(n^2).
//
// I am making the assumption that for most datasets, the "order" function will have relatively low cardinality,
// and therefore this tradeoff should be easily worth it.
if(previousStart!==null&&itemStart<previousStart-EPSILON){insertionIndex=0;}previousStart=itemStart;insertionIndex=findIndexFrom(itemsAlreadyPositioned,i=>getItemStart(i)-EPSILON>itemStart,insertionIndex);itemsAlreadyPositioned.splice(insertionIndex,0,item);insertionIndex++;}}}// Now we can loop through each item (in order) and find a position for them
previousStart=null;let previousEnd=null;insertionIndex=0;let horizontalOverlapStartIndex=0;let horizontalOverlapEndIndex=0;let maxHeight=0;while(itemsToPosition.length>0){const item=itemsToPosition.shift();item.top=getInitialHeight(item);const itemStart=getItemStart(item);const itemEnd=getItemEnd(item);if(previousStart!==null&&itemStart<previousStart-EPSILON){horizontalOverlapStartIndex=0;horizontalOverlapEndIndex=0;insertionIndex=0;previousEnd=null;}previousStart=itemStart;// Take advantage of the sorted itemsAlreadyPositioned array to narrow down the search
horizontalOverlapStartIndex=findIndexFrom(itemsAlreadyPositioned,i=>itemStart<getItemEnd(i)-EPSILON,horizontalOverlapStartIndex);// Since items aren't sorted by end time, it might increase or decrease from one item to the next. In order to keep an efficient search area, we will seek forwards/backwards accordingly.
if(previousEnd===null||previousEnd<itemEnd-EPSILON){horizontalOverlapEndIndex=findIndexFrom(itemsAlreadyPositioned,i=>itemEnd<getItemStart(i)-EPSILON,Math.max(horizontalOverlapStartIndex,horizontalOverlapEndIndex));}if(previousEnd!==null&&previousEnd-EPSILON>itemEnd){horizontalOverlapEndIndex=findLastIndexBetween(itemsAlreadyPositioned,i=>itemEnd+EPSILON>=getItemStart(i),horizontalOverlapStartIndex,horizontalOverlapEndIndex)+1;}// Sort by vertical position so we don't have to reconsider past items if we move an item
const horizontallyCollidingItems=itemsAlreadyPositioned.slice(horizontalOverlapStartIndex,horizontalOverlapEndIndex).filter(i=>itemStart<getItemEnd(i)-EPSILON&&itemEnd-EPSILON>getItemStart(i)).sort((a,b)=>a.top-b.top);// Keep moving the item down until it stops colliding with any other items
for(let i2=0;i2<horizontallyCollidingItems.length;i2++){const otherItem=horizontallyCollidingItems[i2];if(checkVerticalSpatialCollision(item,otherItem,margins)){item.top=otherItem.top+otherItem.height+margins.vertical;}}if(shouldOthersStack(item)){// Insert the item into itemsAlreadyPositioned, ensuring itemsAlreadyPositioned remains sorted.
// In the best case, we can insert an item in constant time O(1). In the worst case, we insert an item in linear time O(n).
// In both cases, this is better than doing a naive insert and then sort, which would cost on average O(n log n).
insertionIndex=findIndexFrom(itemsAlreadyPositioned,i=>getItemStart(i)-EPSILON>itemStart,insertionIndex);itemsAlreadyPositioned.splice(insertionIndex,0,item);insertionIndex++;}// Keep track of the tallest item we've seen before
const currentHeight=item.top+item.height;if(currentHeight>maxHeight){maxHeight=currentHeight;}if(shouldBail&&shouldBail()){return null;}}return maxHeight;}/**
* Test if the two provided items collide
* The items must have parameters left, width, top, and height.
* @param {Item} a The first item
* @param {Item} b The second item
* @param {{vertical: number}} margin
* An object containing a horizontal and vertical
* minimum required margin.
* @return {boolean} true if a and b collide, else false
*/function checkVerticalSpatialCollision(a,b,margin){return a.top-margin.vertical+EPSILON<b.top+b.height&&a.top+a.height+margin.vertical-EPSILON>b.top;}/**
* Find index of first item to meet predicate after a certain index.
* If no such item is found, returns the length of the array.
*
* @param {any[]} arr The array
* @param {(item) => boolean} predicate A function that should return true when a suitable item is found
* @param {number|undefined} startIndex The index to start search from (inclusive). Optional, if not provided will search from the beginning of the array.
*
* @return {number}
*/function findIndexFrom(arr,predicate,startIndex){if(!startIndex){startIndex=0;}const matchIndex=arr.slice(startIndex).findIndex(predicate);if(matchIndex===-1){return arr.length;}return matchIndex+startIndex;}/**
* Find index of last item to meet predicate within a given range.
* If no such item is found, returns the index prior to the start of the range.
*
* @param {any[]} arr The array
* @param {(item) => boolean} predicate A function that should return true when a suitable item is found
* @param {number|undefined} startIndex The earliest index to search to (inclusive). Optional, if not provided will continue until the start of the array.
* @param {number|undefined} endIndex The end of the search range (exclusive). The search will begin on the index prior to this value. Optional, defaults to the end of array.
*
* @return {number}
*/function findLastIndexBetween(arr,predicate,startIndex,endIndex){if(!startIndex){startIndex=0;}if(!endIndex){endIndex=arr.length;}for(i=endIndex-1;i>=startIndex;i--){if(predicate(arr[i])){return i;}}return startIndex-1;}const UNGROUPED$3='__ungrouped__';// reserved group id for ungrouped items
const BACKGROUND$2='__background__';// reserved group id for background items without group
const ReservedGroupIds$1={UNGROUPED:UNGROUPED$3,BACKGROUND:BACKGROUND$2};/**
* @constructor Group
*/class Group{/**
* @param {number | string} groupId
* @param {Object} data
* @param {ItemSet} itemSet
* @constructor Group
*/constructor(groupId,data,itemSet){this.groupId=groupId;this.subgroups={};this.subgroupStack={};this.subgroupStackAll=false;this.subgroupVisibility={};this.doInnerStack=false;this.shouldBailStackItems=false;this.subgroupIndex=0;this.subgroupOrderer=data&&data.subgroupOrder;this.itemSet=itemSet;this.isVisible=null;this.stackDirty=true;// if true, items will be restacked on next redraw
// This is a stack of functions (`() => void`) that will be executed before
// the instance is disposed off (method `dispose`). Anything that needs to
// be manually disposed off before garbage collection happens (or so that
// garbage collection can happen) should be added to this stack.
this._disposeCallbacks=[];if(data&&data.nestedGroups){this.nestedGroups=data.nestedGroups;if(data.showNested==false){this.showNested=false;}else {this.showNested=true;}}if(data&&data.subgroupStack){if(typeof data.subgroupStack==="boolean"){this.doInnerStack=data.subgroupStack;this.subgroupStackAll=data.subgroupStack;}else {// We might be doing stacking on specific sub groups, but only
// if at least one is set to do stacking
for(const key in data.subgroupStack){this.subgroupStack[key]=data.subgroupStack[key];this.doInnerStack=this.doInnerStack||data.subgroupStack[key];}}}if(data&&data.heightMode){this.heightMode=data.heightMode;}else {this.heightMode=itemSet.options.groupHeightMode;}this.nestedInGroup=null;this.dom={};this.props={label:{width:0,height:0}};this.className=null;this.items={};// items filtered by groupId of this group
this.visibleItems=[];// items currently visible in window
this.itemsInRange=[];// items currently in range
this.orderedItems={byStart:[],byEnd:[]};this.checkRangedItems=false;// needed to refresh the ranged items if the window is programatically changed with NO overlap.
const handleCheckRangedItems=()=>{this.checkRangedItems=true;};this.itemSet.body.emitter.on("checkRangedItems",handleCheckRangedItems);this._disposeCallbacks.push(()=>{this.itemSet.body.emitter.off("checkRangedItems",handleCheckRangedItems);});this._create();this.setData(data);}/**
* Create DOM elements for the group
* @private
*/_create(){const label=document.createElement('div');if(this.itemSet.options.groupEditable.order){label.className='vis-label draggable';}else {label.className='vis-label';}this.dom.label=label;const inner=document.createElement('div');inner.className='vis-inner';label.appendChild(inner);this.dom.inner=inner;const foreground=document.createElement('div');foreground.className='vis-group';foreground['vis-group']=this;this.dom.foreground=foreground;this.dom.background=document.createElement('div');this.dom.background.className='vis-group';this.dom.axis=document.createElement('div');this.dom.axis.className='vis-group';// create a hidden marker to detect when the Timelines container is attached
// to the DOM, or the style of a parent of the Timeline is changed from
// display:none is changed to visible.
this.dom.marker=document.createElement('div');this.dom.marker.style.visibility='hidden';this.dom.marker.style.position='absolute';this.dom.marker.innerHTML='';this.dom.background.appendChild(this.dom.marker);}/**
* Set the group data for this group
* @param {Object} data Group data, can contain properties content and className
*/setData(data){if(this.itemSet.groupTouchParams.isDragging)return;// update contents
let content;let templateFunction;if(data&&data.subgroupVisibility){for(const key in data.subgroupVisibility){this.subgroupVisibility[key]=data.subgroupVisibility[key];}}if(this.itemSet.options&&this.itemSet.options.groupTemplate){templateFunction=this.itemSet.options.groupTemplate.bind(this);content=templateFunction(data,this.dom.inner);}else {content=data&&data.content;}if(content instanceof Element){while(this.dom.inner.firstChild){this.dom.inner.removeChild(this.dom.inner.firstChild);}this.dom.inner.appendChild(content);}else if(content instanceof Object&&content.isReactComponent);else if(content instanceof Object){templateFunction(data,this.dom.inner);}else if(content!==undefined&&content!==null){this.dom.inner.innerHTML=availableUtils.xss(content);}else {this.dom.inner.innerHTML=availableUtils.xss(this.groupId||'');// groupId can be null
}// update title
this.dom.label.title=data&&data.title||'';if(!this.dom.inner.firstChild){availableUtils.addClassName(this.dom.inner,'vis-hidden');}else {availableUtils.removeClassName(this.dom.inner,'vis-hidden');}if(data&&data.nestedGroups){if(!this.nestedGroups||this.nestedGroups!=data.nestedGroups){this.nestedGroups=data.nestedGroups;}if(data.showNested!==undefined||this.showNested===undefined){if(data.showNested==false){this.showNested=false;}else {this.showNested=true;}}availableUtils.addClassName(this.dom.label,'vis-nesting-group');if(this.showNested){availableUtils.removeClassName(this.dom.label,'collapsed');availableUtils.addClassName(this.dom.label,'expanded');}else {availableUtils.removeClassName(this.dom.label,'expanded');availableUtils.addClassName(this.dom.label,'collapsed');}}else if(this.nestedGroups){this.nestedGroups=null;availableUtils.removeClassName(this.dom.label,'collapsed');availableUtils.removeClassName(this.dom.label,'expanded');availableUtils.removeClassName(this.dom.label,'vis-nesting-group');}if(data&&(data.treeLevel||data.nestedInGroup)){availableUtils.addClassName(this.dom.label,'vis-nested-group');if(data.treeLevel){availableUtils.addClassName(this.dom.label,'vis-group-level-'+data.treeLevel);}else {// Nesting level is unknown, but we're sure it's at least 1
availableUtils.addClassName(this.dom.label,'vis-group-level-unknown-but-gte1');}}else {availableUtils.addClassName(this.dom.label,'vis-group-level-0');}// update className
const className=data&&data.className||null;if(className!=this.className){if(this.className){availableUtils.removeClassName(this.dom.label,this.className);availableUtils.removeClassName(this.dom.foreground,this.className);availableUtils.removeClassName(this.dom.background,this.className);availableUtils.removeClassName(this.dom.axis,this.className);}availableUtils.addClassName(this.dom.label,className);availableUtils.addClassName(this.dom.foreground,className);availableUtils.addClassName(this.dom.background,className);availableUtils.addClassName(this.dom.axis,className);this.className=className;}// update style
if(this.style){availableUtils.removeCssText(this.dom.label,this.style);this.style=null;}if(data&&data.style){availableUtils.addCssText(this.dom.label,data.style);this.style=data.style;}}/**
* Get the width of the group label
* @return {number} width
*/getLabelWidth(){return this.props.label.width;}/**
* check if group has had an initial height hange
* @returns {boolean}
*/_didMarkerHeightChange(){const markerHeight=this.dom.marker.clientHeight;if(markerHeight!=this.lastMarkerHeight){this.lastMarkerHeight=markerHeight;const redrawQueue={};let redrawQueueLength=0;availableUtils.forEach(this.items,(item,key)=>{item.dirty=true;if(item.displayed){const returnQueue=true;redrawQueue[key]=item.redraw(returnQueue);redrawQueueLength=redrawQueue[key].length;}});const needRedraw=redrawQueueLength>0;if(needRedraw){// redraw all regular items
for(let i=0;i<redrawQueueLength;i++){availableUtils.forEach(redrawQueue,fns=>{fns[i]();});}}return true;}else {return false;}}/**
* calculate group dimentions and position
* @param {number} pixels
*/_calculateGroupSizeAndPosition(){const{offsetTop,offsetLeft,offsetWidth}=this.dom.foreground;this.top=offsetTop;this.right=offsetLeft;this.width=offsetWidth;}/**
* checks if should bail redraw of items
* @returns {boolean} should bail
*/_shouldBailItemsRedraw(){const me=this;const timeoutOptions=this.itemSet.options.onTimeout;const bailOptions={relativeBailingTime:this.itemSet.itemsSettingTime,bailTimeMs:timeoutOptions&&timeoutOptions.timeoutMs,userBailFunction:timeoutOptions&&timeoutOptions.callback,shouldBailStackItems:this.shouldBailStackItems};let bail=null;if(!this.itemSet.initialDrawDone){if(bailOptions.shouldBailStackItems){return true;}if(Math.abs(Date.now()-new Date(bailOptions.relativeBailingTime))>bailOptions.bailTimeMs){if(bailOptions.userBailFunction&&this.itemSet.userContinueNotBail==null){bailOptions.userBailFunction(didUserContinue=>{me.itemSet.userContinueNotBail=didUserContinue;bail=!didUserContinue;});}else if(me.itemSet.userContinueNotBail==false){bail=true;}else {bail=false;}}}return bail;}/**
* redraws items
* @param {boolean} forceRestack
* @param {boolean} lastIsVisible
* @param {number} margin
* @param {object} range
* @private
*/_redrawItems(forceRestack,lastIsVisible,margin,range){const restack=forceRestack||this.stackDirty||this.isVisible&&!lastIsVisible;// if restacking, reposition visible items vertically
if(restack){const orderedItems={byEnd:this.orderedItems.byEnd.filter(item=>!item.isCluster),byStart:this.orderedItems.byStart.filter(item=>!item.isCluster)};const orderedClusters={byEnd:[...new Set(this.orderedItems.byEnd.map(item=>item.cluster).filter(item=>!!item))],byStart:[...new Set(this.orderedItems.byStart.map(item=>item.cluster).filter(item=>!!item))]};/**
* Get all visible items in range
* @return {array} items
*/const getVisibleItems=()=>{const visibleItems=this._updateItemsInRange(orderedItems,this.visibleItems.filter(item=>!item.isCluster),range);const visibleClusters=this._updateClustersInRange(orderedClusters,this.visibleItems.filter(item=>item.isCluster),range);return [...visibleItems,...visibleClusters];};/**
* Get visible items grouped by subgroup
* @param {function} orderFn An optional function to order items inside the subgroups
* @return {Object}
*/const getVisibleItemsGroupedBySubgroup=orderFn=>{let visibleSubgroupsItems={};for(const subgroup in this.subgroups){const items=this.visibleItems.filter(item=>item.data.subgroup===subgroup);visibleSubgroupsItems[subgroup]=orderFn?items.sort((a,b)=>orderFn(a.data,b.data)):items;}return visibleSubgroupsItems;};if(typeof this.itemSet.options.order==='function'){// a custom order function
//show all items
const me=this;if(this.doInnerStack&&this.itemSet.options.stackSubgroups){// Order the items within each subgroup
const visibleSubgroupsItems=getVisibleItemsGroupedBySubgroup(this.itemSet.options.order);stackSubgroupsWithInnerStack(visibleSubgroupsItems,margin,this.subgroups);this.visibleItems=getVisibleItems();this._updateSubGroupHeights(margin);}else {this.visibleItems=getVisibleItems();this._updateSubGroupHeights(margin);// order all items and force a restacking
// order all items outside clusters and force a restacking
const customOrderedItems=this.visibleItems.slice().filter(item=>item.isCluster||!item.isCluster&&!item.cluster).sort((a,b)=>{return me.itemSet.options.order(a.data,b.data);});this.shouldBailStackItems=stack(customOrderedItems,margin,true,this._shouldBailItemsRedraw.bind(this));}}else {// no custom order function, lazy stacking
this.visibleItems=getVisibleItems();this._updateSubGroupHeights(margin);if(this.itemSet.options.stack){if(this.doInnerStack&&this.itemSet.options.stackSubgroups){const visibleSubgroupsItems=getVisibleItemsGroupedBySubgroup();stackSubgroupsWithInnerStack(visibleSubgroupsItems,margin,this.subgroups);}else {// TODO: ugly way to access options...
this.shouldBailStackItems=stack(this.visibleItems,margin,true,this._shouldBailItemsRedraw.bind(this));}}else {// no stacking
nostack(this.visibleItems,margin,this.subgroups,this.itemSet.options.stackSubgroups);}}for(let i=0;i<this.visibleItems.length;i++){this.visibleItems[i].repositionX();if(this.subgroupVisibility[this.visibleItems[i].data.subgroup]!==undefined){if(!this.subgroupVisibility[this.visibleItems[i].data.subgroup]){this.visibleItems[i].hide();}}}if(this.itemSet.options.cluster){availableUtils.forEach(this.items,item=>{if(item.cluster&&item.displayed){item.hide();}});}if(this.shouldBailStackItems){this.itemSet.body.emitter.emit('destroyTimeline');}this.stackDirty=false;}}/**
* check if group resized
* @param {boolean} resized
* @param {number} height
* @return {boolean} did resize
*/_didResize(resized,height){resized=availableUtils.updateProperty(this,'height',height)||resized;// recalculate size of label
const labelWidth=this.dom.inner.clientWidth;const labelHeight=this.dom.inner.clientHeight;resized=availableUtils.updateProperty(this.props.label,'width',labelWidth)||resized;resized=availableUtils.updateProperty(this.props.label,'height',labelHeight)||resized;return resized;}/**
* apply group height
* @param {number} height
*/_applyGroupHeight(height){this.dom.background.style.height=`${height}px`;this.dom.foreground.style.height=`${height}px`;this.dom.label.style.height=`${height}px`;}/**
* update vertical position of items after they are re-stacked and the height of the group is calculated
* @param {number} margin
*/_updateItemsVerticalPosition(margin){for(let i=0,ii=this.visibleItems.length;i<ii;i++){const item=this.visibleItems[i];item.repositionY(margin);if(!this.isVisible&&this.groupId!=ReservedGroupIds$1.BACKGROUND){if(item.displayed)item.hide();}}}/**
* Repaint this group
* @param {{start: number, end: number}} range
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @param {boolean} [forceRestack=false] Force restacking of all items
* @param {boolean} [returnQueue=false] return the queue or if the group resized
* @return {boolean} Returns true if the group is resized or the redraw queue if returnQueue=true
*/redraw(range,margin,forceRestack,returnQueue){let resized=false;const lastIsVisible=this.isVisible;let height;const queue=[()=>{forceRestack=this._didMarkerHeightChange.call(this)||forceRestack;},// recalculate the height of the subgroups
this._updateSubGroupHeights.bind(this,margin),// calculate actual size and position
this._calculateGroupSizeAndPosition.bind(this),()=>{this.isVisible=this._isGroupVisible.bind(this)(range,margin);},()=>{this._redrawItems.bind(this)(forceRestack,lastIsVisible,margin,range);},// update subgroups
this._updateSubgroupsSizes.bind(this),()=>{height=this._calculateHeight.bind(this)(margin);},// calculate actual size and position again
this._calculateGroupSizeAndPosition.bind(this),()=>{resized=this._didResize.bind(this)(resized,height);},()=>{this._applyGroupHeight.bind(this)(height);},()=>{this._updateItemsVerticalPosition.bind(this)(margin);},(()=>{if(!this.isVisible&&this.height){resized=false;}return resized;}).bind(this)];if(returnQueue){return queue;}else {let result;queue.forEach(fn=>{result=fn();});return result;}}/**
* recalculate the height of the subgroups
*
* @param {{item: timeline.Item}} margin
* @private
*/_updateSubGroupHeights(margin){if(Object.keys(this.subgroups).length>0){const me=this;this._resetSubgroups();availableUtils.forEach(this.visibleItems,item=>{if(item.data.subgroup!==undefined){me.subgroups[item.data.subgroup].height=Math.max(me.subgroups[item.data.subgroup].height,item.height+margin.item.vertical);me.subgroups[item.data.subgroup].visible=typeof this.subgroupVisibility[item.data.subgroup]==='undefined'?true:Boolean(this.subgroupVisibility[item.data.subgroup]);}});}}/**
* check if group is visible
*
* @param {timeline.Range} range
* @param {{axis: timeline.DataAxis}} margin
* @returns {boolean} is visible
* @private
*/_isGroupVisible(range,margin){return this.top<=range.body.domProps.centerContainer.height-range.body.domProps.scrollTop+margin.axis&&this.top+this.height+margin.axis>=-range.body.domProps.scrollTop;}/**
* recalculate the height of the group
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @returns {number} Returns the height
* @private
*/_calculateHeight(margin){// recalculate the height of the group
let height;let items;if(this.heightMode==='fixed'){items=availableUtils.toArray(this.items);}else {// default or 'auto'
items=this.visibleItems;}if(items.length>0){let min=items[0].top;let max=items[0].top+items[0].height;availableUtils.forEach(items,item=>{min=Math.min(min,item.top);max=Math.max(max,item.top+item.height);});if(min>margin.axis){// there is an empty gap between the lowest item and the axis
const offset=min-margin.axis;max-=offset;availableUtils.forEach(items,item=>{item.top-=offset;});}height=Math.ceil(max+margin.item.vertical/2);if(this.heightMode!=="fitItems"){height=Math.max(height,this.props.label.height);}}else {height=this.props.label.height;}return height;}/**
* Show this group: attach to the DOM
*/show(){if(!this.dom.label.parentNode){this.itemSet.dom.labelSet.appendChild(this.dom.label);}if(!this.dom.foreground.parentNode){this.itemSet.dom.foreground.appendChild(this.dom.foreground);}if(!this.dom.background.parentNode){this.itemSet.dom.background.appendChild(this.dom.background);}if(!this.dom.axis.parentNode){this.itemSet.dom.axis.appendChild(this.dom.axis);}}/**
* Hide this group: remove from the DOM
*/hide(){const label=this.dom.label;if(label.parentNode){label.parentNode.removeChild(label);}const foreground=this.dom.foreground;if(foreground.parentNode){foreground.parentNode.removeChild(foreground);}const background=this.dom.background;if(background.parentNode){background.parentNode.removeChild(background);}const axis=this.dom.axis;if(axis.parentNode){axis.parentNode.removeChild(axis);}}/**
* Add an item to the group
* @param {Item} item
*/add(item){this.items[item.id]=item;item.setParent(this);this.stackDirty=true;// add to
if(item.data.subgroup!==undefined){this._addToSubgroup(item);this.orderSubgroups();}if(!this.visibleItems.includes(item)){const range=this.itemSet.body.range;// TODO: not nice accessing the range like this
this._checkIfVisible(item,this.visibleItems,range);}}/**
* add item to subgroup
* @param {object} item
* @param {string} subgroupId
*/_addToSubgroup(item,subgroupId=item.data.subgroup){if(subgroupId!=undefined&&this.subgroups[subgroupId]===undefined){this.subgroups[subgroupId]={height:0,top:0,start:item.data.start,end:item.data.end||item.data.start,visible:false,index:this.subgroupIndex,items:[],stack:this.subgroupStackAll||this.subgroupStack[subgroupId]||false};this.subgroupIndex++;}if(new Date(item.data.start)<new Date(this.subgroups[subgroupId].start)){this.subgroups[subgroupId].start=item.data.start;}const itemEnd=item.data.end||item.data.start;if(new Date(itemEnd)>new Date(this.subgroups[subgroupId].end)){this.subgroups[subgroupId].end=itemEnd;}this.subgroups[subgroupId].items.push(item);}/**
* update subgroup sizes
*/_updateSubgroupsSizes(){const me=this;if(me.subgroups){for(const subgroup in me.subgroups){const initialEnd=me.subgroups[subgroup].items[0].data.end||me.subgroups[subgroup].items[0].data.start;let newStart=me.subgroups[subgroup].items[0].data.start;let newEnd=initialEnd-1;me.subgroups[subgroup].items.forEach(item=>{if(new Date(item.data.start)<new Date(newStart)){newStart=item.data.start;}const itemEnd=item.data.end||item.data.start;if(new Date(itemEnd)>new Date(newEnd)){newEnd=itemEnd;}});me.subgroups[subgroup].start=newStart;me.subgroups[subgroup].end=new Date(newEnd-1);// -1 to compensate for colliding end to start subgroups;
}}}/**
* order subgroups
*/orderSubgroups(){if(this.subgroupOrderer!==undefined){const sortArray=[];if(typeof this.subgroupOrderer=='string'){for(const subgroup in this.subgroups){sortArray.push({subgroup,sortField:this.subgroups[subgroup].items[0].data[this.subgroupOrderer]});}sortArray.sort((a,b)=>a.sortField-b.sortField);}else if(typeof this.subgroupOrderer=='function'){for(const subgroup in this.subgroups){sortArray.push(this.subgroups[subgroup].items[0].data);}sortArray.sort(this.subgroupOrderer);}if(sortArray.length>0){for(let i=0;i<sortArray.length;i++){this.subgroups[sortArray[i].subgroup].index=i;}}}}/**
* add item to subgroup
*/_resetSubgroups(){for(const subgroup in this.subgroups){if(this.subgroups.hasOwnProperty(subgroup)){this.subgroups[subgroup].visible=false;this.subgroups[subgroup].height=0;}}}/**
* Remove an item from the group
* @param {Item} item
*/remove(item){delete this.items[item.id];item.setParent(null);this.stackDirty=true;// remove from visible items
const index=this.visibleItems.indexOf(item);if(index!=-1)this.visibleItems.splice(index,1);if(item.data.subgroup!==undefined){this._removeFromSubgroup(item);this.orderSubgroups();}}/**
* remove item from subgroup
* @param {object} item
* @param {string} subgroupId
*/_removeFromSubgroup(item,subgroupId=item.data.subgroup){if(subgroupId!=undefined){const subgroup=this.subgroups[subgroupId];if(subgroup){const itemIndex=subgroup.items.indexOf(item);// Check the item is actually in this subgroup. How should items not in the group be handled?
if(itemIndex>=0){subgroup.items.splice(itemIndex,1);if(!subgroup.items.length){delete this.subgroups[subgroupId];}else {this._updateSubgroupsSizes();}}}}}/**
* Remove an item from the corresponding DataSet
* @param {Item} item
*/removeFromDataSet(item){this.itemSet.removeItem(item.id);}/**
* Reorder the items
*/order(){const array=availableUtils.toArray(this.items);const startArray=[];const endArray=[];for(let i=0;i<array.length;i++){if(array[i].data.end!==undefined){endArray.push(array[i]);}startArray.push(array[i]);}this.orderedItems={byStart:startArray,byEnd:endArray};orderByStart(this.orderedItems.byStart);orderByEnd(this.orderedItems.byEnd);}/**
* Update the visible items
* @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
* @param {Item[]} oldVisibleItems The previously visible items.
* @param {{start: number, end: number}} range Visible range
* @return {Item[]} visibleItems The new visible items.
* @private
*/_updateItemsInRange(orderedItems,oldVisibleItems,range){const visibleItems=[];const visibleItemsLookup={};// we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
if(!this.isVisible&&this.height!==undefined&&this.groupId!=ReservedGroupIds$1.BACKGROUND){for(let i=0;i<oldVisibleItems.length;i++){var item=oldVisibleItems[i];if(item.displayed)item.hide();}return visibleItems;}const interval=(range.end-range.start)/4;const lowerBound=range.start-interval;const upperBound=range.end+interval;// this function is used to do the binary search for items having start date only.
const startSearchFunction=value=>{if(value<lowerBound){return -1;}else if(value<=upperBound){return 0;}else {return 1;}};// this function is used to do the binary search for items having start and end dates (range).
const endSearchFunction=data=>{const{start,end}=data;if(end<lowerBound){return -1;}else if(start<=upperBound){return 0;}else {return 1;}};// first check if the items that were in view previously are still in view.
// IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
// also cleans up invisible items.
if(oldVisibleItems.length>0){for(let i=0;i<oldVisibleItems.length;i++){this._checkIfVisibleWithReference(oldVisibleItems[i],visibleItems,visibleItemsLookup,range);}}// we do a binary search for the items that have only start values.
const initialPosByStart=availableUtils.binarySearchCustom(orderedItems.byStart,startSearchFunction,'data','start');// trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
this._traceVisible(initialPosByStart,orderedItems.byStart,visibleItems,visibleItemsLookup,item=>item.data.start<lowerBound||item.data.start>upperBound);// if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
// We therefore have to brute force check all items in the byEnd list
if(this.checkRangedItems==true){this.checkRangedItems=false;for(let i=0;i<orderedItems.byEnd.length;i++){this._checkIfVisibleWithReference(orderedItems.byEnd[i],visibleItems,visibleItemsLookup,range);}}else {// we do a binary search for the items that have defined end times.
const initialPosByEnd=availableUtils.binarySearchCustom(orderedItems.byEnd,endSearchFunction,'data');// trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
this._traceVisible(initialPosByEnd,orderedItems.byEnd,visibleItems,visibleItemsLookup,item=>item.data.end<lowerBound||item.data.start>upperBound);}const redrawQueue={};let redrawQueueLength=0;for(let i=0;i<visibleItems.length;i++){const item=visibleItems[i];if(!item.displayed){const returnQueue=true;redrawQueue[i]=item.redraw(returnQueue);redrawQueueLength=redrawQueue[i].length;}}const needRedraw=redrawQueueLength>0;if(needRedraw){// redraw all regular items
for(let j=0;j<redrawQueueLength;j++){availableUtils.forEach(redrawQueue,fns=>{fns[j]();});}}for(let i=0;i<visibleItems.length;i++){visibleItems[i].repositionX();}return visibleItems;}/**
* trace visible items in group
* @param {number} initialPos
* @param {array} items
* @param {aray} visibleItems
* @param {object} visibleItemsLookup
* @param {function} breakCondition
*/_traceVisible(initialPos,items,visibleItems,visibleItemsLookup,breakCondition){if(initialPos!=-1){for(let i=initialPos;i>=0;i--){let item=items[i];if(breakCondition(item)){break;}else {if(!(item.isCluster&&!item.hasItems())&&!item.cluster){if(visibleItemsLookup[item.id]===undefined){visibleItemsLookup[item.id]=true;visibleItems.push(item);}}}}for(let i=initialPos+1;i<items.length;i++){let item=items[i];if(breakCondition(item)){break;}else {if(!(item.isCluster&&!item.hasItems())&&!item.cluster){if(visibleItemsLookup[item.id]===undefined){visibleItemsLookup[item.id]=true;visibleItems.push(item);}}}}}}/**
* this function is very similar to the _checkIfInvisible() but it does not
* return booleans, hides the item if it should not be seen and always adds to
* the visibleItems.
* this one is for brute forcing and hiding.
*
* @param {Item} item
* @param {Array} visibleItems
* @param {{start:number, end:number}} range
* @private
*/_checkIfVisible(item,visibleItems,range){if(item.isVisible(range)){if(!item.displayed)item.show();// reposition item horizontally
item.repositionX();visibleItems.push(item);}else {if(item.displayed)item.hide();}}/**
* this function is very similar to the _checkIfInvisible() but it does not
* return booleans, hides the item if it should not be seen and always adds to
* the visibleItems.
* this one is for brute forcing and hiding.
*
* @param {Item} item
* @param {Array.<timeline.Item>} visibleItems
* @param {Object<number, boolean>} visibleItemsLookup
* @param {{start:number, end:number}} range
* @private
*/_checkIfVisibleWithReference(item,visibleItems,visibleItemsLookup,range){if(item.isVisible(range)){if(visibleItemsLookup[item.id]===undefined){visibleItemsLookup[item.id]=true;visibleItems.push(item);}}else {if(item.displayed)item.hide();}}/**
* Update the visible items
* @param {array} orderedClusters
* @param {array} oldVisibleClusters
* @param {{start: number, end: number}} range
* @return {Item[]} visibleItems
* @private
*/_updateClustersInRange(orderedClusters,oldVisibleClusters,range){// Clusters can overlap each other so we cannot use binary search here
const visibleClusters=[];const visibleClustersLookup={};// we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
if(oldVisibleClusters.length>0){for(let i=0;i<oldVisibleClusters.length;i++){this._checkIfVisibleWithReference(oldVisibleClusters[i],visibleClusters,visibleClustersLookup,range);}}for(let i=0;i<orderedClusters.byStart.length;i++){this._checkIfVisibleWithReference(orderedClusters.byStart[i],visibleClusters,visibleClustersLookup,range);}for(let i=0;i<orderedClusters.byEnd.length;i++){this._checkIfVisibleWithReference(orderedClusters.byEnd[i],visibleClusters,visibleClustersLookup,range);}const redrawQueue={};let redrawQueueLength=0;for(let i=0;i<visibleClusters.length;i++){const item=visibleClusters[i];if(!item.displayed){const returnQueue=true;redrawQueue[i]=item.redraw(returnQueue);redrawQueueLength=redrawQueue[i].length;}}const needRedraw=redrawQueueLength>0;if(needRedraw){// redraw all regular items
for(var j=0;j<redrawQueueLength;j++){availableUtils.forEach(redrawQueue,function(fns){fns[j]();});}}for(let i=0;i<visibleClusters.length;i++){visibleClusters[i].repositionX();}return visibleClusters;}/**
* change item subgroup
* @param {object} item
* @param {string} oldSubgroup
* @param {string} newSubgroup
*/changeSubgroup(item,oldSubgroup,newSubgroup){this._removeFromSubgroup(item,oldSubgroup);this._addToSubgroup(item,newSubgroup);this.orderSubgroups();}/**
* Call this method before you lose the last reference to an instance of this.
* It will remove listeners etc.
*/dispose(){this.hide();let disposeCallback;while(disposeCallback=this._disposeCallbacks.pop()){disposeCallback();}}}/**
* @constructor BackgroundGroup
* @extends Group
*/class BackgroundGroup extends Group{/**
* @param {number | string} groupId
* @param {Object} data
* @param {ItemSet} itemSet
*/constructor(groupId,data,itemSet){super(groupId,data,itemSet);// Group.call(this, groupId, data, itemSet);
this.width=0;this.height=0;this.top=0;this.left=0;}/**
* Repaint this group
* @param {{start: number, end: number}} range
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @param {boolean} [forceRestack=false] Force restacking of all items
* @return {boolean} Returns true if the group is resized
*/redraw(range,margin,forceRestack){// eslint-disable-line no-unused-vars
const resized=false;this.visibleItems=this._updateItemsInRange(this.orderedItems,this.visibleItems,range);// calculate actual size
this.width=this.dom.background.offsetWidth;// apply new height (just always zero for BackgroundGroup
this.dom.background.style.height='0';// update vertical position of items after they are re-stacked and the height of the group is calculated
for(let i=0,ii=this.visibleItems.length;i<ii;i++){const item=this.visibleItems[i];item.repositionY(margin);}return resized;}/**
* Show this group: attach to the DOM
*/show(){if(!this.dom.background.parentNode){this.itemSet.dom.background.appendChild(this.dom.background);}}}/**
* Item
*/class Item{/**
* @constructor Item
* @param {Object} data Object containing (optional) parameters type,
* start, end, content, group, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} options Configuration options
* // TODO: describe available options
*/constructor(data,conversion,options){this.id=null;this.parent=null;this.data=data;this.dom=null;this.conversion=conversion||{};this.defaultOptions={locales: locales$1,locale:'en'};this.options=availableUtils.extend({},this.defaultOptions,options);this.options.locales=availableUtils.extend({},locales$1,this.options.locales);const defaultLocales=this.defaultOptions.locales[this.defaultOptions.locale];Object.keys(this.options.locales).forEach(locale=>{this.options.locales[locale]=availableUtils.extend({},defaultLocales,this.options.locales[locale]);});this.selected=false;this.displayed=false;this.groupShowing=true;this.selectable=options&&options.selectable||false;this.dirty=true;this.top=null;this.right=null;this.left=null;this.width=null;this.height=null;this.setSelectability(data);this.editable=null;this._updateEditStatus();}/**
* Select current item
*/select(){if(this.selectable){this.selected=true;this.dirty=true;if(this.displayed)this.redraw();}}/**
* Unselect current item
*/unselect(){this.selected=false;this.dirty=true;if(this.displayed)this.redraw();}/**
* Set data for the item. Existing data will be updated. The id should not
* be changed. When the item is displayed, it will be redrawn immediately.
* @param {Object} data
*/setData(data){const groupChanged=data.group!=undefined&&this.data.group!=data.group;if(groupChanged&&this.parent!=null){this.parent.itemSet._moveToGroup(this,data.group);}this.setSelectability(data);if(this.parent){this.parent.stackDirty=true;}const subGroupChanged=data.subgroup!=undefined&&this.data.subgroup!=data.subgroup;if(subGroupChanged&&this.parent!=null){this.parent.changeSubgroup(this,this.data.subgroup,data.subgroup);}this.data=data;this._updateEditStatus();this.dirty=true;if(this.displayed)this.redraw();}/**
* Set whether the item can be selected.
* Can only be set/unset if the timeline's `selectable` configuration option is `true`.
* @param {Object} data `data` from `constructor` and `setData`
*/setSelectability(data){if(data){this.selectable=typeof data.selectable==='undefined'?true:Boolean(data.selectable);}}/**
* Set a parent for the item
* @param {Group} parent
*/setParent(parent){if(this.displayed){this.hide();this.parent=parent;if(this.parent){this.show();}}else {this.parent=parent;}}/**
* Check whether this item is visible inside given range
* @param {timeline.Range} range with a timestamp for start and end
* @returns {boolean} True if visible
*/isVisible(range){// eslint-disable-line no-unused-vars
return false;}/**
* Show the Item in the DOM (when not already visible)
* @return {Boolean} changed
*/show(){return false;}/**
* Hide the Item from the DOM (when visible)
* @return {Boolean} changed
*/hide(){return false;}/**
* Repaint the item
*/redraw(){// should be implemented by the item
}/**
* Reposition the Item horizontally
*/repositionX(){// should be implemented by the item
}/**
* Reposition the Item vertically
*/repositionY(){// should be implemented by the item
}/**
* Repaint a drag area on the center of the item when the item is selected
* @protected
*/_repaintDragCenter(){if(this.selected&&this.editable.updateTime&&!this.dom.dragCenter){const me=this;// create and show drag area
const dragCenter=document.createElement('div');dragCenter.className='vis-drag-center';dragCenter.dragCenterItem=this;this.hammerDragCenter=new Hammer(dragCenter);this.hammerDragCenter.on('tap',event=>{me.parent.itemSet.body.emitter.emit('click',{event,item:me.id});});this.hammerDragCenter.on('doubletap',event=>{event.stopPropagation();me.parent.itemSet._onUpdateItem(me);me.parent.itemSet.body.emitter.emit('doubleClick',{event,item:me.id});});this.hammerDragCenter.on('panstart',event=>{// do not allow this event to propagate to the Range
event.stopPropagation();me.parent.itemSet._onDragStart(event);});this.hammerDragCenter.on('panmove',me.parent.itemSet._onDrag.bind(me.parent.itemSet));this.hammerDragCenter.on('panend',me.parent.itemSet._onDragEnd.bind(me.parent.itemSet));// delay addition on item click for trackpads...
this.hammerDragCenter.get('press').set({time:10000});if(this.dom.box){if(this.dom.dragLeft){this.dom.box.insertBefore(dragCenter,this.dom.dragLeft);}else {this.dom.box.appendChild(dragCenter);}}else if(this.dom.point){this.dom.point.appendChild(dragCenter);}this.dom.dragCenter=dragCenter;}else if(!this.selected&&this.dom.dragCenter){// delete drag area
if(this.dom.dragCenter.parentNode){this.dom.dragCenter.parentNode.removeChild(this.dom.dragCenter);}this.dom.dragCenter=null;if(this.hammerDragCenter){this.hammerDragCenter.destroy();this.hammerDragCenter=null;}}}/**
* Repaint a delete button on the top right of the item when the item is selected
* @param {HTMLElement} anchor
* @protected
*/_repaintDeleteButton(anchor){const editable=(this.options.editable.overrideItems||this.editable==null)&&this.options.editable.remove||!this.options.editable.overrideItems&&this.editable!=null&&this.editable.remove;if(this.selected&&editable&&!this.dom.deleteButton){// create and show button
const me=this;const deleteButton=document.createElement('div');if(this.options.rtl){deleteButton.className='vis-delete-rtl';}else {deleteButton.className='vis-delete';}let optionsLocale=this.options.locales[this.options.locale];if(!optionsLocale){if(!this.warned){console.warn(`WARNING: options.locales['${this.options.locale}'] not found. See https://visjs.github.io/vis-timeline/docs/timeline/#Localization`);this.warned=true;}optionsLocale=this.options.locales['en'];// fall back on english when not available
}deleteButton.title=optionsLocale.deleteSelected;// TODO: be able to destroy the delete button
this.hammerDeleteButton=new Hammer(deleteButton).on('tap',event=>{event.stopPropagation();me.parent.removeFromDataSet(me);});anchor.appendChild(deleteButton);this.dom.deleteButton=deleteButton;}else if((!this.selected||!editable)&&this.dom.deleteButton){// remove button
if(this.dom.deleteButton.parentNode){this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);}this.dom.deleteButton=null;if(this.hammerDeleteButton){this.hammerDeleteButton.destroy();this.hammerDeleteButton=null;}}}/**
* Repaint a onChange tooltip on the top right of the item when the item is selected
* @param {HTMLElement} anchor
* @protected
*/_repaintOnItemUpdateTimeTooltip(anchor){if(!this.options.tooltipOnItemUpdateTime)return;const editable=(this.options.editable.updateTime||this.data.editable===true)&&this.data.editable!==false;if(this.selected&&editable&&!this.dom.onItemUpdateTimeTooltip){const onItemUpdateTimeTooltip=document.createElement('div');onItemUpdateTimeTooltip.className='vis-onUpdateTime-tooltip';anchor.appendChild(onItemUpdateTimeTooltip);this.dom.onItemUpdateTimeTooltip=onItemUpdateTimeTooltip;}else if(!this.selected&&this.dom.onItemUpdateTimeTooltip){// remove button
if(this.dom.onItemUpdateTimeTooltip.parentNode){this.dom.onItemUpdateTimeTooltip.parentNode.removeChild(this.dom.onItemUpdateTimeTooltip);}this.dom.onItemUpdateTimeTooltip=null;}// position onChange tooltip
if(this.dom.onItemUpdateTimeTooltip){// only show when editing
this.dom.onItemUpdateTimeTooltip.style.visibility=this.parent.itemSet.touchParams.itemIsDragging?'visible':'hidden';// position relative to item's content
this.dom.onItemUpdateTimeTooltip.style.transform='translateX(-50%)';this.dom.onItemUpdateTimeTooltip.style.left='50%';// position above or below the item depending on the item's position in the window
const tooltipOffset=50;// TODO: should be tooltip height (depends on template)
const scrollTop=this.parent.itemSet.body.domProps.scrollTop;// TODO: this.top for orientation:true is actually the items distance from the bottom...
// (should be this.bottom)
let itemDistanceFromTop;if(this.options.orientation.item=='top'){itemDistanceFromTop=this.top;}else {itemDistanceFromTop=this.parent.height-this.top-this.height;}const isCloseToTop=itemDistanceFromTop+this.parent.top-tooltipOffset<-scrollTop;if(isCloseToTop){this.dom.onItemUpdateTimeTooltip.style.bottom="";this.dom.onItemUpdateTimeTooltip.style.top=`${this.height+2}px`;}else {this.dom.onItemUpdateTimeTooltip.style.top="";this.dom.onItemUpdateTimeTooltip.style.bottom=`${this.height+2}px`;}// handle tooltip content
let content;let templateFunction;if(this.options.tooltipOnItemUpdateTime&&this.options.tooltipOnItemUpdateTime.template){templateFunction=this.options.tooltipOnItemUpdateTime.template.bind(this);content=templateFunction(this.data);}else {content=`start: ${moment$3(this.data.start).format('MM/DD/YYYY hh:mm')}`;if(this.data.end){content+=`<br> end: ${moment$3(this.data.end).format('MM/DD/YYYY hh:mm')}`;}}this.dom.onItemUpdateTimeTooltip.innerHTML=availableUtils.xss(content);}}/**
* get item data
* @return {object}
* @private
*/_getItemData(){return this.parent.itemSet.itemsData.get(this.id);}/**
* Set HTML contents for the item
* @param {Element} element HTML element to fill with the contents
* @private
*/_updateContents(element){let content;let changed;let templateFunction;let itemVisibleFrameContent;let visibleFrameTemplateFunction;const itemData=this._getItemData();// get a clone of the data from the dataset
const frameElement=this.dom.box||this.dom.point;const itemVisibleFrameContentElement=frameElement.getElementsByClassName('vis-item-visible-frame')[0];if(this.options.visibleFrameTemplate){visibleFrameTemplateFunction=this.options.visibleFrameTemplate.bind(this);itemVisibleFrameContent=availableUtils.xss(visibleFrameTemplateFunction(itemData,itemVisibleFrameContentElement));}else {itemVisibleFrameContent='';}if(itemVisibleFrameContentElement){if(itemVisibleFrameContent instanceof Object&&!(itemVisibleFrameContent instanceof Element)){visibleFrameTemplateFunction(itemData,itemVisibleFrameContentElement);}else {changed=this._contentToString(this.itemVisibleFrameContent)!==this._contentToString(itemVisibleFrameContent);if(changed){// only replace the content when changed
if(itemVisibleFrameContent instanceof Element){itemVisibleFrameContentElement.innerHTML='';itemVisibleFrameContentElement.appendChild(itemVisibleFrameContent);}else if(itemVisibleFrameContent!=undefined){itemVisibleFrameContentElement.innerHTML=availableUtils.xss(itemVisibleFrameContent);}else {if(!(this.data.type=='background'&&this.data.content===undefined)){throw new Error(`Property "content" missing in item ${this.id}`);}}this.itemVisibleFrameContent=itemVisibleFrameContent;}}}if(this.options.template){templateFunction=this.options.template.bind(this);content=templateFunction(itemData,element,this.data);}else {content=this.data.content;}if(content instanceof Object&&!(content instanceof Element)){templateFunction(itemData,element);}else {changed=this._contentToString(this.content)!==this._contentToString(content);if(changed){// only replace the content when changed
if(content instanceof Element){element.innerHTML='';element.appendChild(content);}else if(content!=undefined){element.innerHTML=availableUtils.xss(content);}else {if(!(this.data.type=='background'&&this.data.content===undefined)){throw new Error(`Property "content" missing in item ${this.id}`);}}this.content=content;}}}/**
* Process dataAttributes timeline option and set as data- attributes on dom.content
* @param {Element} element HTML element to which the attributes will be attached
* @private
*/_updateDataAttributes(element){if(this.options.dataAttributes&&this.options.dataAttributes.length>0){let attributes=[];if(Array.isArray(this.options.dataAttributes)){attributes=this.options.dataAttributes;}else if(this.options.dataAttributes=='all'){attributes=Object.keys(this.data);}else {return;}for(const name of attributes){const value=this.data[name];if(value!=null){element.setAttribute(`data-${name}`,value);}else {element.removeAttribute(`data-${name}`);}}}}/**
* Update custom styles of the element
* @param {Element} element
* @private
*/_updateStyle(element){// remove old styles
if(this.style){availableUtils.removeCssText(element,this.style);this.style=null;}// append new styles
if(this.data.style){availableUtils.addCssText(element,this.data.style);this.style=this.data.style;}}/**
* Stringify the items contents
* @param {string | Element | undefined} content
* @returns {string | undefined}
* @private
*/_contentToString(content){if(typeof content==='string')return content;if(content&&'outerHTML'in content)return content.outerHTML;return content;}/**
* Update the editability of this item.
*/_updateEditStatus(){if(this.options){if(typeof this.options.editable==='boolean'){this.editable={updateTime:this.options.editable,updateGroup:this.options.editable,remove:this.options.editable};}else if(typeof this.options.editable==='object'){this.editable={};availableUtils.selectiveExtend(['updateTime','updateGroup','remove'],this.editable,this.options.editable);}}// Item data overrides, except if options.editable.overrideItems is set.
if(!this.options||!this.options.editable||this.options.editable.overrideItems!==true){if(this.data){if(typeof this.data.editable==='boolean'){this.editable={updateTime:this.data.editable,updateGroup:this.data.editable,remove:this.data.editable};}else if(typeof this.data.editable==='object'){// TODO: in timeline.js 5.0, we should change this to not reset options from the timeline configuration.
// Basically just remove the next line...
this.editable={};availableUtils.selectiveExtend(['updateTime','updateGroup','remove'],this.editable,this.data.editable);}}}}/**
* Return the width of the item left from its start date
* @return {number}
*/getWidthLeft(){return 0;}/**
* Return the width of the item right from the max of its start and end date
* @return {number}
*/getWidthRight(){return 0;}/**
* Return the title of the item
* @return {string | undefined}
*/getTitle(){if(this.options.tooltip&&this.options.tooltip.template){const templateFunction=this.options.tooltip.template.bind(this);return templateFunction(this._getItemData(),this.data);}return this.data.title;}}Item.prototype.stack=true;/**
* @constructor BoxItem
* @extends Item
*/class BoxItem extends Item{/**
* @param {Object} data Object containing parameters start
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe available options
*/constructor(data,conversion,options){super(data,conversion,options);this.props={dot:{width:0,height:0},line:{width:0,height:0}};// validate data
if(data){if(data.start==undefined){throw new Error(`Property "start" missing in item ${data}`);}}}/**
* Check whether this item is visible inside given range
* @param {{start: number, end: number}} range with a timestamp for start and end
* @returns {boolean} True if visible
*/isVisible(range){if(this.cluster){return false;}// determine visibility
let isVisible;const align=this.data.align||this.options.align;const widthInMs=this.width*range.getMillisecondsPerPixel();if(align=='right'){isVisible=this.data.start.getTime()>range.start&&this.data.start.getTime()-widthInMs<range.end;}else if(align=='left'){isVisible=this.data.start.getTime()+widthInMs>range.start&&this.data.start.getTime()<range.end;}else {// default or 'center'
isVisible=this.data.start.getTime()+widthInMs/2>range.start&&this.data.start.getTime()-widthInMs/2<range.end;}return isVisible;}/**
* create DOM element
* @private
*/_createDomElement(){if(!this.dom){// create DOM
this.dom={};// create main box
this.dom.box=document.createElement('DIV');// contents box (inside the background box). used for making margins
this.dom.content=document.createElement('DIV');this.dom.content.className='vis-item-content';this.dom.box.appendChild(this.dom.content);// line to axis
this.dom.line=document.createElement('DIV');this.dom.line.className='vis-line';// dot on axis
this.dom.dot=document.createElement('DIV');this.dom.dot.className='vis-dot';// attach this item as attribute
this.dom.box['vis-item']=this;this.dirty=true;}}/**
* append DOM element
* @private
*/_appendDomElement(){if(!this.parent){throw new Error('Cannot redraw item: no parent attached');}if(!this.dom.box.parentNode){const foreground=this.parent.dom.foreground;if(!foreground)throw new Error('Cannot redraw item: parent has no foreground container element');foreground.appendChild(this.dom.box);}if(!this.dom.line.parentNode){var background=this.parent.dom.background;if(!background)throw new Error('Cannot redraw item: parent has no background container element');background.appendChild(this.dom.line);}if(!this.dom.dot.parentNode){const axis=this.parent.dom.axis;if(!background)throw new Error('Cannot redraw item: parent has no axis container element');axis.appendChild(this.dom.dot);}this.displayed=true;}/**
* update dirty DOM element
* @private
*/_updateDirtyDomComponents(){// An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if(this.dirty){this._updateContents(this.dom.content);this._updateDataAttributes(this.dom.box);this._updateStyle(this.dom.box);const editable=this.editable.updateTime||this.editable.updateGroup;// update class
const className=(this.data.className?' '+this.data.className:'')+(this.selected?' vis-selected':'')+(editable?' vis-editable':' vis-readonly');this.dom.box.className=`vis-item vis-box${className}`;this.dom.line.className=`vis-item vis-line${className}`;this.dom.dot.className=`vis-item vis-dot${className}`;}}/**
* get DOM components sizes
* @return {object}
* @private
*/_getDomComponentsSizes(){return {previous:{right:this.dom.box.style.right,left:this.dom.box.style.left},dot:{height:this.dom.dot.offsetHeight,width:this.dom.dot.offsetWidth},line:{width:this.dom.line.offsetWidth},box:{width:this.dom.box.offsetWidth,height:this.dom.box.offsetHeight}};}/**
* update DOM components sizes
* @param {object} sizes
* @private
*/_updateDomComponentsSizes(sizes){if(this.options.rtl){this.dom.box.style.right="0px";}else {this.dom.box.style.left="0px";}// recalculate size
this.props.dot.height=sizes.dot.height;this.props.dot.width=sizes.dot.width;this.props.line.width=sizes.line.width;this.width=sizes.box.width;this.height=sizes.box.height;// restore previous position
if(this.options.rtl){this.dom.box.style.right=sizes.previous.right;}else {this.dom.box.style.left=sizes.previous.left;}this.dirty=false;}/**
* repaint DOM additionals
* @private
*/_repaintDomAdditionals(){this._repaintOnItemUpdateTimeTooltip(this.dom.box);this._repaintDragCenter();this._repaintDeleteButton(this.dom.box);}/**
* Repaint the item
* @param {boolean} [returnQueue=false] return the queue
* @return {boolean} the redraw queue if returnQueue=true
*/redraw(returnQueue){let sizes;const queue=[// create item DOM
this._createDomElement.bind(this),// append DOM to parent DOM
this._appendDomElement.bind(this),// update dirty DOM
this._updateDirtyDomComponents.bind(this),()=>{if(this.dirty){sizes=this._getDomComponentsSizes();}},()=>{if(this.dirty){this._updateDomComponentsSizes.bind(this)(sizes);}},// repaint DOM additionals
this._repaintDomAdditionals.bind(this)];if(returnQueue){return queue;}else {let result;queue.forEach(fn=>{result=fn();});return result;}}/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
* @param {boolean} [returnQueue=false] whether to return a queue of functions to execute instead of just executing them
* @return {boolean} the redraw queue if returnQueue=true
*/show(returnQueue){if(!this.displayed){return this.redraw(returnQueue);}}/**
* Hide the item from the DOM (when visible)
*/hide(){if(this.displayed){const dom=this.dom;if(dom.box.remove)dom.box.remove();else if(dom.box.parentNode)dom.box.parentNode.removeChild(dom.box);// IE11
if(dom.line.remove)dom.line.remove();else if(dom.line.parentNode)dom.line.parentNode.removeChild(dom.line);// IE11
if(dom.dot.remove)dom.dot.remove();else if(dom.dot.parentNode)dom.dot.parentNode.removeChild(dom.dot);// IE11
this.displayed=false;}}/**
* Reposition the item XY
*/repositionXY(){const rtl=this.options.rtl;const repositionXY=(element,x,y,rtl=false)=>{if(x===undefined&&y===undefined)return;// If rtl invert the number.
const directionX=rtl?x*-1:x;//no y. translate x
if(y===undefined){element.style.transform=`translateX(${directionX}px)`;return;}//no x. translate y
if(x===undefined){element.style.transform=`translateY(${y}px)`;return;}element.style.transform=`translate(${directionX}px, ${y}px)`;};repositionXY(this.dom.box,this.boxX,this.boxY,rtl);repositionXY(this.dom.dot,this.dotX,this.dotY,rtl);repositionXY(this.dom.line,this.lineX,this.lineY,rtl);}/**
* Reposition the item horizontally
* @Override
*/repositionX(){const start=this.conversion.toScreen(this.data.start);const align=this.data.align===undefined?this.options.align:this.data.align;const lineWidth=this.props.line.width;const dotWidth=this.props.dot.width;if(align=='right'){// calculate right position of the box
this.boxX=start-this.width;this.lineX=start-lineWidth;this.dotX=start-lineWidth/2-dotWidth/2;}else if(align=='left'){// calculate left position of the box
this.boxX=start;this.lineX=start;this.dotX=start+lineWidth/2-dotWidth/2;}else {// default or 'center'
this.boxX=start-this.width/2;this.lineX=this.options.rtl?start-lineWidth:start-lineWidth/2;this.dotX=start-dotWidth/2;}if(this.options.rtl)this.right=this.boxX;else this.left=this.boxX;this.repositionXY();}/**
* Reposition the item vertically
* @Override
*/repositionY(){const orientation=this.options.orientation.item;const lineStyle=this.dom.line.style;if(orientation=='top'){const lineHeight=this.parent.top+this.top+1;this.boxY=this.top||0;lineStyle.height=`${lineHeight}px`;lineStyle.bottom='';lineStyle.top='0';}else {// orientation 'bottom'
const itemSetHeight=this.parent.itemSet.props.height;// TODO: this is nasty
const lineHeight=itemSetHeight-this.parent.top-this.parent.height+this.top;this.boxY=this.parent.height-this.top-(this.height||0);lineStyle.height=`${lineHeight}px`;lineStyle.top='';lineStyle.bottom='0';}this.dotY=-this.props.dot.height/2;this.repositionXY();}/**
* Return the width of the item left from its start date
* @return {number}
*/getWidthLeft(){return this.width/2;}/**
* Return the width of the item right from its start date
* @return {number}
*/getWidthRight(){return this.width/2;}}/**
* @constructor PointItem
* @extends Item
*/class PointItem extends Item{/**
* @param {Object} data Object containing parameters start
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe available options
*/constructor(data,conversion,options){super(data,conversion,options);this.props={dot:{top:0,width:0,height:0},content:{height:0,marginLeft:0,marginRight:0}};// validate data
if(data){if(data.start==undefined){throw new Error(`Property "start" missing in item ${data}`);}}}/**
* Check whether this item is visible inside given range
* @param {{start: number, end: number}} range with a timestamp for start and end
* @returns {boolean} True if visible
*/isVisible(range){if(this.cluster){return false;}// determine visibility
const widthInMs=this.width*range.getMillisecondsPerPixel();return this.data.start.getTime()+widthInMs>range.start&&this.data.start<range.end;}/**
* create DOM element
* @private
*/_createDomElement(){if(!this.dom){// create DOM
this.dom={};// background box
this.dom.point=document.createElement('div');// className is updated in redraw()
// contents box, right from the dot
this.dom.content=document.createElement('div');this.dom.content.className='vis-item-content';this.dom.point.appendChild(this.dom.content);// dot at start
this.dom.dot=document.createElement('div');this.dom.point.appendChild(this.dom.dot);// attach this item as attribute
this.dom.point['vis-item']=this;this.dirty=true;}}/**
* append DOM element
* @private
*/_appendDomElement(){if(!this.parent){throw new Error('Cannot redraw item: no parent attached');}if(!this.dom.point.parentNode){const foreground=this.parent.dom.foreground;if(!foreground){throw new Error('Cannot redraw item: parent has no foreground container element');}foreground.appendChild(this.dom.point);}this.displayed=true;}/**
* update dirty DOM components
* @private
*/_updateDirtyDomComponents(){// An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if(this.dirty){this._updateContents(this.dom.content);this._updateDataAttributes(this.dom.point);this._updateStyle(this.dom.point);const editable=this.editable.updateTime||this.editable.updateGroup;// update class
const className=(this.data.className?' '+this.data.className:'')+(this.selected?' vis-selected':'')+(editable?' vis-editable':' vis-readonly');this.dom.point.className=`vis-item vis-point${className}`;this.dom.dot.className=`vis-item vis-dot${className}`;}}/**
* get DOM component sizes
* @return {object}
* @private
*/_getDomComponentsSizes(){return {dot:{width:this.dom.dot.offsetWidth,height:this.dom.dot.offsetHeight},content:{width:this.dom.content.offsetWidth,height:this.dom.content.offsetHeight},point:{width:this.dom.point.offsetWidth,height:this.dom.point.offsetHeight}};}/**
* update DOM components sizes
* @param {array} sizes
* @private
*/_updateDomComponentsSizes(sizes){// recalculate size of dot and contents
this.props.dot.width=sizes.dot.width;this.props.dot.height=sizes.dot.height;this.props.content.height=sizes.content.height;// resize contents
if(this.options.rtl){this.dom.content.style.marginRight=`${this.props.dot.width/2}px`;}else {this.dom.content.style.marginLeft=`${this.props.dot.width/2}px`;}//this.dom.content.style.marginRight = ... + 'px'; // TODO: margin right
// recalculate size
this.width=sizes.point.width;this.height=sizes.point.height;// reposition the dot
this.dom.dot.style.top=`${(this.height-this.props.dot.height)/2}px`;const dotWidth=this.props.dot.width;const translateX=this.options.rtl?dotWidth/2:dotWidth/2*-1;this.dom.dot.style.transform=`translateX(${translateX}px`;this.dirty=false;}/**
* Repain DOM additionals
* @private
*/_repaintDomAdditionals(){this._repaintOnItemUpdateTimeTooltip(this.dom.point);this._repaintDragCenter();this._repaintDeleteButton(this.dom.point);}/**
* Repaint the item
* @param {boolean} [returnQueue=false] return the queue
* @return {boolean} the redraw queue if returnQueue=true
*/redraw(returnQueue){let sizes;const queue=[// create item DOM
this._createDomElement.bind(this),// append DOM to parent DOM
this._appendDomElement.bind(this),// update dirty DOM
this._updateDirtyDomComponents.bind(this),()=>{if(this.dirty){sizes=this._getDomComponentsSizes();}},()=>{if(this.dirty){this._updateDomComponentsSizes.bind(this)(sizes);}},// repaint DOM additionals
this._repaintDomAdditionals.bind(this)];if(returnQueue){return queue;}else {let result;queue.forEach(fn=>{result=fn();});return result;}}/**
* Reposition XY
*/repositionXY(){const rtl=this.options.rtl;const repositionXY=(element,x,y,rtl=false)=>{if(x===undefined&&y===undefined)return;// If rtl invert the number.
const directionX=rtl?x*-1:x;//no y. translate x
if(y===undefined){element.style.transform=`translateX(${directionX}px)`;return;}//no x. translate y
if(x===undefined){element.style.transform=`translateY(${y}px)`;return;}element.style.transform=`translate(${directionX}px, ${y}px)`;};repositionXY(this.dom.point,this.pointX,this.pointY,rtl);}/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
* @param {boolean} [returnQueue=false] whether to return a queue of functions to execute instead of just executing them
* @return {boolean} the redraw queue if returnQueue=true
*/show(returnQueue){if(!this.displayed){return this.redraw(returnQueue);}}/**
* Hide the item from the DOM (when visible)
*/hide(){if(this.displayed){if(this.dom.point.parentNode){this.dom.point.parentNode.removeChild(this.dom.point);}this.displayed=false;}}/**
* Reposition the item horizontally
* @Override
*/repositionX(){const start=this.conversion.toScreen(this.data.start);this.pointX=start;if(this.options.rtl){this.right=start-this.props.dot.width;}else {this.left=start-this.props.dot.width;}this.repositionXY();}/**
* Reposition the item vertically
* @Override
*/repositionY(){const orientation=this.options.orientation.item;if(orientation=='top'){this.pointY=this.top;}else {this.pointY=this.parent.height-this.top-this.height;}this.repositionXY();}/**
* Return the width of the item left from its start date
* @return {number}
*/getWidthLeft(){return this.props.dot.width;}/**
* Return the width of the item right from its start date
* @return {number}
*/getWidthRight(){return this.props.dot.width;}}/**
* @constructor RangeItem
* @extends Item
*/class RangeItem extends Item{/**
* @param {Object} data Object containing parameters start, end
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe options
*/constructor(data,conversion,options){super(data,conversion,options);this.props={content:{width:0}};this.overflow=false;// if contents can overflow (css styling), this flag is set to true
// validate data
if(data){if(data.start==undefined){throw new Error(`Property "start" missing in item ${data.id}`);}if(data.end==undefined){throw new Error(`Property "end" missing in item ${data.id}`);}}}/**
* Check whether this item is visible inside given range
*
* @param {timeline.Range} range with a timestamp for start and end
* @returns {boolean} True if visible
*/isVisible(range){if(this.cluster){return false;}// determine visibility
return this.data.start<range.end&&this.data.end>range.start;}/**
* create DOM elements
* @private
*/_createDomElement(){if(!this.dom){// create DOM
this.dom={};// background box
this.dom.box=document.createElement('div');// className is updated in redraw()
// frame box (to prevent the item contents from overflowing)
this.dom.frame=document.createElement('div');this.dom.frame.className='vis-item-overflow';this.dom.box.appendChild(this.dom.frame);// visible frame box (showing the frame that is always visible)
this.dom.visibleFrame=document.createElement('div');this.dom.visibleFrame.className='vis-item-visible-frame';this.dom.box.appendChild(this.dom.visibleFrame);// contents box
this.dom.content=document.createElement('div');this.dom.content.className='vis-item-content';this.dom.frame.appendChild(this.dom.content);// attach this item as attribute
this.dom.box['vis-item']=this;this.dirty=true;}}/**
* append element to DOM
* @private
*/_appendDomElement(){if(!this.parent){throw new Error('Cannot redraw item: no parent attached');}if(!this.dom.box.parentNode){const foreground=this.parent.dom.foreground;if(!foreground){throw new Error('Cannot redraw item: parent has no foreground container element');}foreground.appendChild(this.dom.box);}this.displayed=true;}/**
* update dirty DOM components
* @private
*/_updateDirtyDomComponents(){// update dirty DOM. An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if(this.dirty){this._updateContents(this.dom.content);this._updateDataAttributes(this.dom.box);this._updateStyle(this.dom.box);const editable=this.editable.updateTime||this.editable.updateGroup;// update class
const className=(this.data.className?' '+this.data.className:'')+(this.selected?' vis-selected':'')+(editable?' vis-editable':' vis-readonly');this.dom.box.className=this.baseClassName+className;// turn off max-width to be able to calculate the real width
// this causes an extra browser repaint/reflow, but so be it
this.dom.content.style.maxWidth='none';}}/**
* get DOM component sizes
* @return {object}
* @private
*/_getDomComponentsSizes(){// determine from css whether this box has overflow
this.overflow=window.getComputedStyle(this.dom.frame).overflow!=='hidden';this.whiteSpace=window.getComputedStyle(this.dom.content).whiteSpace!=='nowrap';return {content:{width:this.dom.content.offsetWidth},box:{height:this.dom.box.offsetHeight}};}/**
* update DOM component sizes
* @param {array} sizes
* @private
*/_updateDomComponentsSizes(sizes){this.props.content.width=sizes.content.width;this.height=sizes.box.height;this.dom.content.style.maxWidth='';this.dirty=false;}/**
* repaint DOM additional components
* @private
*/_repaintDomAdditionals(){this._repaintOnItemUpdateTimeTooltip(this.dom.box);this._repaintDeleteButton(this.dom.box);this._repaintDragCenter();this._repaintDragLeft();this._repaintDragRight();}/**
* Repaint the item
* @param {boolean} [returnQueue=false] return the queue
* @return {boolean} the redraw queue if returnQueue=true
*/redraw(returnQueue){let sizes;const queue=[// create item DOM
this._createDomElement.bind(this),// append DOM to parent DOM
this._appendDomElement.bind(this),// update dirty DOM
this._updateDirtyDomComponents.bind(this),()=>{if(this.dirty){sizes=this._getDomComponentsSizes.bind(this)();}},()=>{if(this.dirty){this._updateDomComponentsSizes.bind(this)(sizes);}},// repaint DOM additionals
this._repaintDomAdditionals.bind(this)];if(returnQueue){return queue;}else {let result;queue.forEach(fn=>{result=fn();});return result;}}/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
* @param {boolean} [returnQueue=false] whether to return a queue of functions to execute instead of just executing them
* @return {boolean} the redraw queue if returnQueue=true
*/show(returnQueue){if(!this.displayed){return this.redraw(returnQueue);}}/**
* Hide the item from the DOM (when visible)
*/hide(){if(this.displayed){const box=this.dom.box;if(box.parentNode){box.parentNode.removeChild(box);}this.displayed=false;}}/**
* Reposition the item horizontally
* @param {boolean} [limitSize=true] If true (default), the width of the range
* item will be limited, as the browser cannot
* display very wide divs. This means though
* that the applied left and width may
* not correspond to the ranges start and end
* @Override
*/repositionX(limitSize){const parentWidth=this.parent.width;let start=this.conversion.toScreen(this.data.start);let end=this.conversion.toScreen(this.data.end);const align=this.data.align===undefined?this.options.align:this.data.align;let contentStartPosition;let contentWidth;// limit the width of the range, as browsers cannot draw very wide divs
// unless limitSize: false is explicitly set in item data
if(this.data.limitSize!==false&&(limitSize===undefined||limitSize===true)){if(start<-parentWidth){start=-parentWidth;}if(end>2*parentWidth){end=2*parentWidth;}}//round to 3 decimals to compensate floating-point values rounding
const boxWidth=Math.max(Math.round((end-start)*1000)/1000,1);if(this.overflow){if(this.options.rtl){this.right=start;}else {this.left=start;}this.width=boxWidth+this.props.content.width;contentWidth=this.props.content.width;// Note: The calculation of width is an optimistic calculation, giving
// a width which will not change when moving the Timeline
// So no re-stacking needed, which is nicer for the eye;
}else {if(this.options.rtl){this.right=start;}else {this.left=start;}this.width=boxWidth;contentWidth=Math.min(end-start,this.props.content.width);}if(this.options.rtl){this.dom.box.style.transform=`translateX(${this.right*-1}px)`;}else {this.dom.box.style.transform=`translateX(${this.left}px)`;}this.dom.box.style.width=`${boxWidth}px`;if(this.whiteSpace){this.height=this.dom.box.offsetHeight;}switch(align){case'left':this.dom.content.style.transform='translateX(0)';break;case'right':if(this.options.rtl){const translateX=Math.max(boxWidth-contentWidth,0)*-1;this.dom.content.style.transform=`translateX(${translateX}px)`;}else {this.dom.content.style.transform=`translateX(${Math.max(boxWidth-contentWidth,0)}px)`;}break;case'center':if(this.options.rtl){const translateX=Math.max((boxWidth-contentWidth)/2,0)*-1;this.dom.content.style.transform=`translateX(${translateX}px)`;}else {this.dom.content.style.transform=`translateX(${Math.max((boxWidth-contentWidth)/2,0)}px)`;}break;default:// 'auto'
// when range exceeds left of the window, position the contents at the left of the visible area
if(this.overflow){if(end>0){contentStartPosition=Math.max(-start,0);}else {contentStartPosition=-contentWidth;// ensure it's not visible anymore
}}else {if(start<0){contentStartPosition=-start;}else {contentStartPosition=0;}}if(this.options.rtl){const translateX=contentStartPosition*-1;this.dom.content.style.transform=`translateX(${translateX}px)`;}else {this.dom.content.style.transform=`translateX(${contentStartPosition}px)`;// this.dom.content.style.width = `calc(100% - ${contentStartPosition}px)`;
}}}/**
* Reposition the item vertically
* @Override
*/repositionY(){const orientation=this.options.orientation.item;const box=this.dom.box;if(orientation=='top'){box.style.top=`${this.top}px`;}else {box.style.top=`${this.parent.height-this.top-this.height}px`;}}/**
* Repaint a drag area on the left side of the range when the range is selected
* @protected
*/_repaintDragLeft(){if((this.selected||this.options.itemsAlwaysDraggable.range)&&this.editable.updateTime&&!this.dom.dragLeft){// create and show drag area
const dragLeft=document.createElement('div');dragLeft.className='vis-drag-left';dragLeft.dragLeftItem=this;this.dom.box.appendChild(dragLeft);this.dom.dragLeft=dragLeft;}else if(!this.selected&&!this.options.itemsAlwaysDraggable.range&&this.dom.dragLeft){// delete drag area
if(this.dom.dragLeft.parentNode){this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);}this.dom.dragLeft=null;}}/**
* Repaint a drag area on the right side of the range when the range is selected
* @protected
*/_repaintDragRight(){if((this.selected||this.options.itemsAlwaysDraggable.range)&&this.editable.updateTime&&!this.dom.dragRight){// create and show drag area
const dragRight=document.createElement('div');dragRight.className='vis-drag-right';dragRight.dragRightItem=this;this.dom.box.appendChild(dragRight);this.dom.dragRight=dragRight;}else if(!this.selected&&!this.options.itemsAlwaysDraggable.range&&this.dom.dragRight){// delete drag area
if(this.dom.dragRight.parentNode){this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);}this.dom.dragRight=null;}}}RangeItem.prototype.baseClassName='vis-item vis-range';/**
* @constructor BackgroundItem
* @extends Item
*/class BackgroundItem extends Item{/**
* @constructor BackgroundItem
* @param {Object} data Object containing parameters start, end
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe options
* // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation
*/constructor(data,conversion,options){super(data,conversion,options);this.props={content:{width:0}};this.overflow=false;// if contents can overflow (css styling), this flag is set to true
// validate data
if(data){if(data.start==undefined){throw new Error(`Property "start" missing in item ${data.id}`);}if(data.end==undefined){throw new Error(`Property "end" missing in item ${data.id}`);}}}/**
* Check whether this item is visible inside given range
* @param {timeline.Range} range with a timestamp for start and end
* @returns {boolean} True if visible
*/isVisible(range){// determine visibility
return this.data.start<range.end&&this.data.end>range.start;}/**
* create DOM element
* @private
*/_createDomElement(){if(!this.dom){// create DOM
this.dom={};// background box
this.dom.box=document.createElement('div');// className is updated in redraw()
// frame box (to prevent the item contents from overflowing
this.dom.frame=document.createElement('div');this.dom.frame.className='vis-item-overflow';this.dom.box.appendChild(this.dom.frame);// contents box
this.dom.content=document.createElement('div');this.dom.content.className='vis-item-content';this.dom.frame.appendChild(this.dom.content);// Note: we do NOT attach this item as attribute to the DOM,
// such that background items cannot be selected
//this.dom.box['vis-item'] = this;
this.dirty=true;}}/**
* append DOM element
* @private
*/_appendDomElement(){if(!this.parent){throw new Error('Cannot redraw item: no parent attached');}if(!this.dom.box.parentNode){const background=this.parent.dom.background;if(!background){throw new Error('Cannot redraw item: parent has no background container element');}background.appendChild(this.dom.box);}this.displayed=true;}/**
* update DOM Dirty components
* @private
*/_updateDirtyDomComponents(){// update dirty DOM. An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if(this.dirty){this._updateContents(this.dom.content);this._updateDataAttributes(this.dom.content);this._updateStyle(this.dom.box);// update class
const className=(this.data.className?' '+this.data.className:'')+(this.selected?' vis-selected':'');this.dom.box.className=this.baseClassName+className;}}/**
* get DOM components sizes
* @return {object}
* @private
*/_getDomComponentsSizes(){// determine from css whether this box has overflow
this.overflow=window.getComputedStyle(this.dom.content).overflow!=='hidden';return {content:{width:this.dom.content.offsetWidth}};}/**
* update DOM components sizes
* @param {object} sizes
* @private
*/_updateDomComponentsSizes(sizes){// recalculate size
this.props.content.width=sizes.content.width;this.height=0;// set height zero, so this item will be ignored when stacking items
this.dirty=false;}/**
* repaint DOM additionals
* @private
*/_repaintDomAdditionals(){}/**
* Repaint the item
* @param {boolean} [returnQueue=false] return the queue
* @return {boolean} the redraw result or the redraw queue if returnQueue=true
*/redraw(returnQueue){let sizes;const queue=[// create item DOM
this._createDomElement.bind(this),// append DOM to parent DOM
this._appendDomElement.bind(this),this._updateDirtyDomComponents.bind(this),()=>{if(this.dirty){sizes=this._getDomComponentsSizes.bind(this)();}},()=>{if(this.dirty){this._updateDomComponentsSizes.bind(this)(sizes);}},// repaint DOM additionals
this._repaintDomAdditionals.bind(this)];if(returnQueue){return queue;}else {let result;queue.forEach(fn=>{result=fn();});return result;}}/**
* Reposition the item vertically
* @Override
*/repositionY(margin){// eslint-disable-line no-unused-vars
let height;const orientation=this.options.orientation.item;// special positioning for subgroups
if(this.data.subgroup!==undefined){// TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset
const itemSubgroup=this.data.subgroup;this.dom.box.style.height=`${this.parent.subgroups[itemSubgroup].height}px`;if(orientation=='top'){this.dom.box.style.top=`${this.parent.top+this.parent.subgroups[itemSubgroup].top}px`;}else {this.dom.box.style.top=`${this.parent.top+this.parent.height-this.parent.subgroups[itemSubgroup].top-this.parent.subgroups[itemSubgroup].height}px`;}this.dom.box.style.bottom='';}// and in the case of no subgroups:
else {// we want backgrounds with groups to only show in groups.
if(this.parent instanceof BackgroundGroup){// if the item is not in a group:
height=Math.max(this.parent.height,this.parent.itemSet.body.domProps.center.height,this.parent.itemSet.body.domProps.centerContainer.height);this.dom.box.style.bottom=orientation=='bottom'?'0':'';this.dom.box.style.top=orientation=='top'?'0':'';}else {height=this.parent.height;// same alignment for items when orientation is top or bottom
this.dom.box.style.top=`${this.parent.top}px`;this.dom.box.style.bottom='';}}this.dom.box.style.height=`${height}px`;}}BackgroundItem.prototype.baseClassName='vis-item vis-background';BackgroundItem.prototype.stack=false;/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
*/BackgroundItem.prototype.show=RangeItem.prototype.show;/**
* Hide the item from the DOM (when visible)
* @return {Boolean} changed
*/BackgroundItem.prototype.hide=RangeItem.prototype.hide;/**
* Reposition the item horizontally
* @Override
*/BackgroundItem.prototype.repositionX=RangeItem.prototype.repositionX;/**
* Popup is a class to create a popup window with some text
*/class Popup{/**
* @param {Element} container The container object.
* @param {string} overflowMethod How the popup should act to overflowing ('flip', 'cap' or 'none')
*/constructor(container,overflowMethod){this.container=container;this.overflowMethod=overflowMethod||'cap';this.x=0;this.y=0;this.padding=5;this.hidden=false;// create the frame
this.frame=document.createElement('div');this.frame.className='vis-tooltip';this.container.appendChild(this.frame);}/**
* @param {number} x Horizontal position of the popup window
* @param {number} y Vertical position of the popup window
*/setPosition(x,y){this.x=parseInt(x);this.y=parseInt(y);}/**
* Set the content for the popup window. This can be HTML code or text.
* @param {string | Element} content
*/setText(content){if(content instanceof Element){this.frame.innerHTML='';this.frame.appendChild(content);}else {this.frame.innerHTML=availableUtils.xss(content);// string containing text or HTML
}}/**
* Show the popup window
* @param {boolean} [doShow] Show or hide the window
*/show(doShow){if(doShow===undefined){doShow=true;}if(doShow===true){var height=this.frame.clientHeight;var width=this.frame.clientWidth;var maxHeight=this.frame.parentNode.clientHeight;var maxWidth=this.frame.parentNode.clientWidth;var left=0,top=0;if(this.overflowMethod=='flip'||this.overflowMethod=='none'){let isLeft=false,isTop=true;// Where around the position it's located
if(this.overflowMethod=='flip'){if(this.y-height<this.padding){isTop=false;}if(this.x+width>maxWidth-this.padding){isLeft=true;}}if(isLeft){left=this.x-width;}else {left=this.x;}if(isTop){top=this.y-height;}else {top=this.y;}}else {// this.overflowMethod == 'cap'
top=this.y-height;if(top+height+this.padding>maxHeight){top=maxHeight-height-this.padding;}if(top<this.padding){top=this.padding;}left=this.x;if(left+width+this.padding>maxWidth){left=maxWidth-width-this.padding;}if(left<this.padding){left=this.padding;}}this.frame.style.left=left+"px";this.frame.style.top=top+"px";this.frame.style.visibility="visible";this.hidden=false;}else {this.hide();}}/**
* Hide the popup window
*/hide(){this.hidden=true;this.frame.style.left="0";this.frame.style.top="0";this.frame.style.visibility="hidden";}/**
* Remove the popup window
*/destroy(){this.frame.parentNode.removeChild(this.frame);// Remove element from DOM
}}/**
* ClusterItem
*/class ClusterItem extends Item{/**
* @constructor Item
* @param {Object} data Object containing (optional) parameters type,
* start, end, content, group, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} options Configuration options
* // TODO: describe available options
*/constructor(data,conversion,options){const modifiedOptions=Object.assign({},{fitOnDoubleClick:true},options,{editable:false});super(data,conversion,modifiedOptions);this.props={content:{width:0,height:0}};if(!data||data.uiItems==undefined){throw new Error('Property "uiItems" missing in item '+data.id);}this.id=v4();this.group=data.group;this._setupRange();this.emitter=this.data.eventEmitter;this.range=this.data.range;this.attached=false;this.isCluster=true;this.data.isCluster=true;}/**
* check if there are items
* @return {boolean}
*/hasItems(){return this.data.uiItems&&this.data.uiItems.length&&this.attached;}/**
* set UI items
* @param {array} items
*/setUiItems(items){this.detach();this.data.uiItems=items;this._setupRange();this.attach();}/**
* check is visible
* @param {object} range
* @return {boolean}
*/isVisible(range){const rangeWidth=this.data.end?this.data.end-this.data.start:0;const widthInMs=this.width*range.getMillisecondsPerPixel();const end=Math.max(this.data.start.getTime()+rangeWidth,this.data.start.getTime()+widthInMs);return this.data.start<range.end&&end>range.start&&this.hasItems();}/**
* get cluster data
* @return {object}
*/getData(){return {isCluster:true,id:this.id,items:this.data.items||[],data:this.data};}/**
* redraw cluster item
* @param {boolean} returnQueue
* @return {boolean}
*/redraw(returnQueue){var sizes;var queue=[// create item DOM
this._createDomElement.bind(this),// append DOM to parent DOM
this._appendDomElement.bind(this),// update dirty DOM
this._updateDirtyDomComponents.bind(this),function(){if(this.dirty){sizes=this._getDomComponentsSizes();}}.bind(this),function(){if(this.dirty){this._updateDomComponentsSizes.bind(this)(sizes);}}.bind(this),// repaint DOM additionals
this._repaintDomAdditionals.bind(this)];if(returnQueue){return queue;}else {var result;queue.forEach(function(fn){result=fn();});return result;}}/**
* show cluster item
*/show(){if(!this.displayed){this.redraw();}}/**
* Hide the item from the DOM (when visible)
*/hide(){if(this.displayed){var dom=this.dom;if(dom.box.parentNode){dom.box.parentNode.removeChild(dom.box);}if(this.options.showStipes){if(dom.line.parentNode){dom.line.parentNode.removeChild(dom.line);}if(dom.dot.parentNode){dom.dot.parentNode.removeChild(dom.dot);}}this.displayed=false;}}/**
* reposition item x axis
*/repositionX(){let start=this.conversion.toScreen(this.data.start);let end=this.data.end?this.conversion.toScreen(this.data.end):0;if(end){this.repositionXWithRanges(start,end);}else {let align=this.data.align===undefined?this.options.align:this.data.align;this.repositionXWithoutRanges(start,align);}if(this.options.showStipes){this.dom.line.style.display=this._isStipeVisible()?'block':'none';this.dom.dot.style.display=this._isStipeVisible()?'block':'none';if(this._isStipeVisible()){this.repositionStype(start,end);}}}/**
* reposition item stype
* @param {date} start
* @param {date} end
*/repositionStype(start,end){this.dom.line.style.display='block';this.dom.dot.style.display='block';const lineOffsetWidth=this.dom.line.offsetWidth;const dotOffsetWidth=this.dom.dot.offsetWidth;if(end){const lineOffset=lineOffsetWidth+start+(end-start)/2;const dotOffset=lineOffset-dotOffsetWidth/2;const lineOffsetDirection=this.options.rtl?lineOffset*-1:lineOffset;const dotOffsetDirection=this.options.rtl?dotOffset*-1:dotOffset;this.dom.line.style.transform=`translateX(${lineOffsetDirection}px)`;this.dom.dot.style.transform=`translateX(${dotOffsetDirection}px)`;}else {const lineOffsetDirection=this.options.rtl?start*-1:start;const dotOffsetDirection=this.options.rtl?(start-dotOffsetWidth/2)*-1:start-dotOffsetWidth/2;this.dom.line.style.transform=`translateX(${lineOffsetDirection}px)`;this.dom.dot.style.transform=`translateX(${dotOffsetDirection}px)`;}}/**
* reposition x without ranges
* @param {date} start
* @param {string} align
*/repositionXWithoutRanges(start,align){// calculate left position of the box
if(align=='right'){if(this.options.rtl){this.right=start-this.width;// reposition box, line, and dot
this.dom.box.style.right=this.right+'px';}else {this.left=start-this.width;// reposition box, line, and dot
this.dom.box.style.left=this.left+'px';}}else if(align=='left'){if(this.options.rtl){this.right=start;// reposition box, line, and dot
this.dom.box.style.right=this.right+'px';}else {this.left=start;// reposition box, line, and dot
this.dom.box.style.left=this.left+'px';}}else {// default or 'center'
if(this.options.rtl){this.right=start-this.width/2;// reposition box, line, and dot
this.dom.box.style.right=this.right+'px';}else {this.left=start-this.width/2;// reposition box, line, and dot
this.dom.box.style.left=this.left+'px';}}}/**
* reposition x with ranges
* @param {date} start
* @param {date} end
*/repositionXWithRanges(start,end){let boxWidth=Math.round(Math.max(end-start+0.5,1));if(this.options.rtl){this.right=start;}else {this.left=start;}this.width=Math.max(boxWidth,this.minWidth||0);if(this.options.rtl){this.dom.box.style.right=this.right+'px';}else {this.dom.box.style.left=this.left+'px';}this.dom.box.style.width=boxWidth+'px';}/**
* reposition item y axis
*/repositionY(){var orientation=this.options.orientation.item;var box=this.dom.box;if(orientation=='top'){box.style.top=(this.top||0)+'px';}else {// orientation 'bottom'
box.style.top=(this.parent.height-this.top-this.height||0)+'px';}if(this.options.showStipes){if(orientation=='top'){this.dom.line.style.top='0';this.dom.line.style.height=this.parent.top+this.top+1+'px';this.dom.line.style.bottom='';}else {// orientation 'bottom'
var itemSetHeight=this.parent.itemSet.props.height;var lineHeight=itemSetHeight-this.parent.top-this.parent.height+this.top;this.dom.line.style.top=itemSetHeight-lineHeight+'px';this.dom.line.style.bottom='0';}this.dom.dot.style.top=-this.dom.dot.offsetHeight/2+'px';}}/**
* get width left
* @return {number}
*/getWidthLeft(){return this.width/2;}/**
* get width right
* @return {number}
*/getWidthRight(){return this.width/2;}/**
* move cluster item
*/move(){this.repositionX();this.repositionY();}/**
* attach
*/attach(){for(let item of this.data.uiItems){item.cluster=this;}this.data.items=this.data.uiItems.map(item=>item.data);this.attached=true;this.dirty=true;}/**
* detach
* @param {boolean} detachFromParent
* @return {void}
*/detach(detachFromParent=false){if(!this.hasItems()){return;}for(let item of this.data.uiItems){delete item.cluster;}this.attached=false;if(detachFromParent&&this.group){this.group.remove(this);this.group=null;}this.data.items=[];this.dirty=true;}/**
* handle on double click
*/_onDoubleClick(){this._fit();}/**
* set range
*/_setupRange(){const stats=this.data.uiItems.map(item=>({start:item.data.start.valueOf(),end:item.data.end?item.data.end.valueOf():item.data.start.valueOf()}));this.data.min=Math.min(...stats.map(s=>Math.min(s.start,s.end||s.start)));this.data.max=Math.max(...stats.map(s=>Math.max(s.start,s.end||s.start)));const centers=this.data.uiItems.map(item=>item.center);const avg=centers.reduce((sum,value)=>sum+value,0)/this.data.uiItems.length;if(this.data.uiItems.some(item=>item.data.end)){// contains ranges
this.data.start=new Date(this.data.min);this.data.end=new Date(this.data.max);}else {this.data.start=new Date(avg);this.data.end=null;}}/**
* get UI items
* @return {array}
*/_getUiItems(){if(this.data.uiItems&&this.data.uiItems.length){return this.data.uiItems.filter(item=>item.cluster===this);}return [];}/**
* create DOM element
*/_createDomElement(){if(!this.dom){// create DOM
this.dom={};// create main box
this.dom.box=document.createElement('DIV');// contents box (inside the background box). used for making margins
this.dom.content=document.createElement('DIV');this.dom.content.className='vis-item-content';this.dom.box.appendChild(this.dom.content);if(this.options.showStipes){// line to axis
this.dom.line=document.createElement('DIV');this.dom.line.className='vis-cluster-line';this.dom.line.style.display='none';// dot on axis
this.dom.dot=document.createElement('DIV');this.dom.dot.className='vis-cluster-dot';this.dom.dot.style.display='none';}if(this.options.fitOnDoubleClick){this.dom.box.ondblclick=ClusterItem.prototype._onDoubleClick.bind(this);}// attach this item as attribute
this.dom.box['vis-item']=this;this.dirty=true;}}/**
* append element to DOM
*/_appendDomElement(){if(!this.parent){throw new Error('Cannot redraw item: no parent attached');}if(!this.dom.box.parentNode){const foreground=this.parent.dom.foreground;if(!foreground){throw new Error('Cannot redraw item: parent has no foreground container element');}foreground.appendChild(this.dom.box);}const background=this.parent.dom.background;if(this.options.showStipes){if(!this.dom.line.parentNode){if(!background)throw new Error('Cannot redraw item: parent has no background container element');background.appendChild(this.dom.line);}if(!this.dom.dot.parentNode){var axis=this.parent.dom.axis;if(!background)throw new Error('Cannot redraw item: parent has no axis container element');axis.appendChild(this.dom.dot);}}this.displayed=true;}/**
* update dirty DOM components
*/_updateDirtyDomComponents(){// An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if(this.dirty){this._updateContents(this.dom.content);this._updateDataAttributes(this.dom.box);this._updateStyle(this.dom.box);// update class
const className=this.baseClassName+' '+(this.data.className?' '+this.data.className:'')+(this.selected?' vis-selected':'')+' vis-readonly';this.dom.box.className='vis-item '+className;if(this.options.showStipes){this.dom.line.className='vis-item vis-cluster-line '+(this.selected?' vis-selected':'');this.dom.dot.className='vis-item vis-cluster-dot '+(this.selected?' vis-selected':'');}if(this.data.end){// turn off max-width to be able to calculate the real width
// this causes an extra browser repaint/reflow, but so be it
this.dom.content.style.maxWidth='none';}}}/**
* get DOM components sizes
* @return {object}
*/_getDomComponentsSizes(){const sizes={previous:{right:this.dom.box.style.right,left:this.dom.box.style.left},box:{width:this.dom.box.offsetWidth,height:this.dom.box.offsetHeight}};if(this.options.showStipes){sizes.dot={height:this.dom.dot.offsetHeight,width:this.dom.dot.offsetWidth};sizes.line={width:this.dom.line.offsetWidth};}return sizes;}/**
* update DOM components sizes
* @param {object} sizes
*/_updateDomComponentsSizes(sizes){if(this.options.rtl){this.dom.box.style.right="0px";}else {this.dom.box.style.left="0px";}// recalculate size
if(!this.data.end){this.width=sizes.box.width;}else {this.minWidth=sizes.box.width;}this.height=sizes.box.height;// restore previous position
if(this.options.rtl){this.dom.box.style.right=sizes.previous.right;}else {this.dom.box.style.left=sizes.previous.left;}this.dirty=false;}/**
* repaint DOM additional components
*/_repaintDomAdditionals(){this._repaintOnItemUpdateTimeTooltip(this.dom.box);}/**
* check is stripe visible
* @return {number}
* @private
*/_isStipeVisible(){return this.minWidth>=this.width||!this.data.end;}/**
* get fit range
* @return {object}
* @private
*/_getFitRange(){const offset=0.05*(this.data.max-this.data.min)/2;return {fitStart:this.data.min-offset,fitEnd:this.data.max+offset};}/**
* fit
* @private
*/_fit(){if(this.emitter){const{fitStart,fitEnd}=this._getFitRange();const fitArgs={start:new Date(fitStart),end:new Date(fitEnd),animation:true};this.emitter.emit('fit',fitArgs);}}/**
* get item data
* @return {object}
* @private
*/_getItemData(){return this.data;}}ClusterItem.prototype.baseClassName='vis-item vis-range vis-cluster';const UNGROUPED$2='__ungrouped__';// reserved group id for ungrouped items
const BACKGROUND$1='__background__';// reserved group id for background items without group
const ReservedGroupIds={UNGROUPED:UNGROUPED$2,BACKGROUND:BACKGROUND$1};/**
* An Cluster generator generates cluster items
*/class ClusterGenerator{/**
* @param {ItemSet} itemSet itemsSet instance
* @constructor ClusterGenerator
*/constructor(itemSet){this.itemSet=itemSet;this.groups={};this.cache={};this.cache[-1]=[];}/**
* @param {Object} itemData Object containing parameters start content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* @return {Object} newItem
*/createClusterItem(itemData,conversion,options){const newItem=new ClusterItem(itemData,conversion,options);return newItem;}/**
* Set the items to be clustered.
* This will clear cached clusters.
* @param {Item[]} items
* @param {Object} [options] Available options:
* {boolean} applyOnChangedLevel
* If true (default), the changed data is applied
* as soon the cluster level changes. If false,
* The changed data is applied immediately
*/setItems(items,options){this.items=items||[];this.dataChanged=true;this.applyOnChangedLevel=false;if(options&&options.applyOnChangedLevel){this.applyOnChangedLevel=options.applyOnChangedLevel;}}/**
* Update the current data set: clear cache, and recalculate the clustering for
* the current level
*/updateData(){this.dataChanged=true;this.applyOnChangedLevel=false;}/**
* Cluster the items which are too close together
* @param {array} oldClusters
* @param {number} scale The scale of the current window : (windowWidth / (endDate - startDate))
* @param {{maxItems: number, clusterCriteria: function, titleTemplate: string}} options
* @return {array} clusters
*/getClusters(oldClusters,scale,options){let{maxItems,clusterCriteria}=typeof options==="boolean"?{}:options;if(!clusterCriteria){clusterCriteria=()=>true;}maxItems=maxItems||1;let level=-1;let granularity=2;let timeWindow=0;if(scale>0){if(scale>=1){return [];}level=Math.abs(Math.round(Math.log(100/scale)/Math.log(granularity)));timeWindow=Math.abs(Math.pow(granularity,level));}// clear the cache when and re-generate groups the data when needed.
if(this.dataChanged){const levelChanged=level!=this.cacheLevel;const applyDataNow=this.applyOnChangedLevel?levelChanged:true;if(applyDataNow){this._dropLevelsCache();this._filterData();}}this.cacheLevel=level;let clusters=this.cache[level];if(!clusters){clusters=[];for(let groupName in this.groups){if(this.groups.hasOwnProperty(groupName)){const items=this.groups[groupName];const iMax=items.length;let i=0;while(i<iMax){// find all items around current item, within the timeWindow
let item=items[i];let neighbors=1;// start at 1, to include itself)
// loop through items left from the current item
let j=i-1;while(j>=0&&item.center-items[j].center<timeWindow/2){if(!items[j].cluster&&clusterCriteria(item.data,items[j].data)){neighbors++;}j--;}// loop through items right from the current item
let k=i+1;while(k<items.length&&items[k].center-item.center<timeWindow/2){if(clusterCriteria(item.data,items[k].data)){neighbors++;}k++;}// loop through the created clusters
let l=clusters.length-1;while(l>=0&&item.center-clusters[l].center<timeWindow){if(item.group==clusters[l].group&&clusterCriteria(item.data,clusters[l].data)){neighbors++;}l--;}// aggregate until the number of items is within maxItems
if(neighbors>maxItems){// too busy in this window.
const num=neighbors-maxItems+1;const clusterItems=[];// append the items to the cluster,
// and calculate the average start for the cluster
let m=i;while(clusterItems.length<num&&m<items.length){if(clusterCriteria(items[i].data,items[m].data)){clusterItems.push(items[m]);}m++;}const groupId=this.itemSet.getGroupId(item.data);const group=this.itemSet.groups[groupId]||this.itemSet.groups[ReservedGroupIds.UNGROUPED];let cluster=this._getClusterForItems(clusterItems,group,oldClusters,options);clusters.push(cluster);i+=num;}else {delete item.cluster;i+=1;}}}}this.cache[level]=clusters;}return clusters;}/**
* Filter the items per group.
* @private
*/_filterData(){// filter per group
const groups={};this.groups=groups;// split the items per group
for(const item of Object.values(this.items)){// put the item in the correct group
const groupName=item.parent?item.parent.groupId:'';let group=groups[groupName];if(!group){group=[];groups[groupName]=group;}group.push(item);// calculate the center of the item
if(item.data.start){if(item.data.end){// range
item.center=(item.data.start.valueOf()+item.data.end.valueOf())/2;}else {// box, dot
item.center=item.data.start.valueOf();}}}// sort the items per group
for(let currentGroupName in groups){if(groups.hasOwnProperty(currentGroupName)){groups[currentGroupName].sort((a,b)=>a.center-b.center);}}this.dataChanged=false;}/**
* Create new cluster or return existing
* @private
* @param {array} clusterItems
* @param {object} group
* @param {array} oldClusters
* @param {object} options
* @returns {object} cluster
*/_getClusterForItems(clusterItems,group,oldClusters,options){const oldClustersLookup=(oldClusters||[]).map(cluster=>({cluster,itemsIds:new Set(cluster.data.uiItems.map(item=>item.id))}));let cluster;if(oldClustersLookup.length){for(let oldClusterData of oldClustersLookup){if(oldClusterData.itemsIds.size===clusterItems.length&&clusterItems.every(clusterItem=>oldClusterData.itemsIds.has(clusterItem.id))){cluster=oldClusterData.cluster;break;}}}if(cluster){cluster.setUiItems(clusterItems);if(cluster.group!==group){if(cluster.group){cluster.group.remove(cluster);}if(group){group.add(cluster);cluster.group=group;}}return cluster;}let titleTemplate=options.titleTemplate||'';const conversion={toScreen:this.itemSet.body.util.toScreen,toTime:this.itemSet.body.util.toTime};const title=titleTemplate.replace(/{count}/,clusterItems.length);const clusterContent='<div title="'+title+'">'+clusterItems.length+'</div>';const clusterOptions=Object.assign({},options,this.itemSet.options);const data={'content':clusterContent,'title':title,'group':group,'uiItems':clusterItems,'eventEmitter':this.itemSet.body.emitter,'range':this.itemSet.body.range};cluster=this.createClusterItem(data,conversion,clusterOptions);if(group){group.add(cluster);cluster.group=group;}cluster.attach();return cluster;}/**
* Drop cache
* @private
*/_dropLevelsCache(){this.cache={};this.cacheLevel=-1;this.cache[this.cacheLevel]=[];}}const UNGROUPED$1='__ungrouped__';// reserved group id for ungrouped items
const BACKGROUND='__background__';// reserved group id for background items without group
/**
* An ItemSet holds a set of items and ranges which can be displayed in a
* range. The width is determined by the parent of the ItemSet, and the height
* is determined by the size of the items.
*/class ItemSet extends Component{/**
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
* @param {Object} [options] See ItemSet.setOptions for the available options.
* @constructor ItemSet
* @extends Component
*/constructor(body,options){super();this.body=body;this.defaultOptions={type:null,// 'box', 'point', 'range', 'background'
orientation:{item:'bottom'// item orientation: 'top' or 'bottom'
},align:'auto',// alignment of box items
stack:true,stackSubgroups:true,groupOrderSwap(fromGroup,toGroup,groups){// eslint-disable-line no-unused-vars
const targetOrder=toGroup.order;toGroup.order=fromGroup.order;fromGroup.order=targetOrder;},groupOrder:'order',selectable:true,multiselect:false,longSelectPressTime:251,itemsAlwaysDraggable:{item:false,range:false},editable:{updateTime:false,updateGroup:false,add:false,remove:false,overrideItems:false},groupEditable:{order:false,add:false,remove:false},snap:TimeStep.snap,// Only called when `objectData.target === 'item'.
onDropObjectOnItem(objectData,item,callback){callback(item);},onAdd(item,callback){callback(item);},onUpdate(item,callback){callback(item);},onMove(item,callback){callback(item);},onRemove(item,callback){callback(item);},onMoving(item,callback){callback(item);},onAddGroup(item,callback){callback(item);},onMoveGroup(item,callback){callback(item);},onRemoveGroup(item,callback){callback(item);},margin:{item:{horizontal:10,vertical:10},axis:20},showTooltips:true,tooltip:{followMouse:false,overflowMethod:'flip',delay:500},tooltipOnItemUpdateTime:false};// options is shared by this ItemSet and all its items
this.options=availableUtils.extend({},this.defaultOptions);this.options.rtl=options.rtl;this.options.onTimeout=options.onTimeout;this.conversion={toScreen:body.util.toScreen,toTime:body.util.toTime};this.dom={};this.props={};this.hammer=null;const me=this;this.itemsData=null;// DataSet
this.groupsData=null;// DataSet
this.itemsSettingTime=null;this.initialItemSetDrawn=false;this.userContinueNotBail=null;this.sequentialSelection=false;// listeners for the DataSet of the items
this.itemListeners={'add'(event,params,senderId){// eslint-disable-line no-unused-vars
me._onAdd(params.items);if(me.options.cluster){me.clusterGenerator.setItems(me.items,{applyOnChangedLevel:false});}me.redraw();},'update'(event,params,senderId){// eslint-disable-line no-unused-vars
me._onUpdate(params.items);if(me.options.cluster){me.clusterGenerator.setItems(me.items,{applyOnChangedLevel:false});}me.redraw();},'remove'(event,params,senderId){// eslint-disable-line no-unused-vars
me._onRemove(params.items);if(me.options.cluster){me.clusterGenerator.setItems(me.items,{applyOnChangedLevel:false});}me.redraw();}};// listeners for the DataSet of the groups
this.groupListeners={'add'(event,params,senderId){// eslint-disable-line no-unused-vars
me._onAddGroups(params.items);if(me.groupsData&&me.groupsData.length>0){const groupsData=me.groupsData.getDataSet();groupsData.get().forEach(groupData=>{if(groupData.nestedGroups){if(groupData.showNested!=false){groupData.showNested=true;}let updatedGroups=[];groupData.nestedGroups.forEach(nestedGroupId=>{const updatedNestedGroup=groupsData.get(nestedGroupId);if(!updatedNestedGroup){return;}updatedNestedGroup.nestedInGroup=groupData.id;if(groupData.showNested==false){updatedNestedGroup.visible=false;}updatedGroups=updatedGroups.concat(updatedNestedGroup);});groupsData.update(updatedGroups,senderId);}});}},'update'(event,params,senderId){// eslint-disable-line no-unused-vars
me._onUpdateGroups(params.items);},'remove'(event,params,senderId){// eslint-disable-line no-unused-vars
me._onRemoveGroups(params.items);}};this.items={};// object with an Item for every data item
this.groups={};// Group object for every group
this.groupIds=[];this.selection=[];// list with the ids of all selected nodes
this.popup=null;this.popupTimer=null;this.touchParams={};// stores properties while dragging
this.groupTouchParams={group:null,isDragging:false};// create the HTML DOM
this._create();this.setOptions(options);this.clusters=[];}/**
* Create the HTML DOM for the ItemSet
*/_create(){const frame=document.createElement('div');frame.className='vis-itemset';frame['vis-itemset']=this;this.dom.frame=frame;// create background panel
const background=document.createElement('div');background.className='vis-background';frame.appendChild(background);this.dom.background=background;// create foreground panel
const foreground=document.createElement('div');foreground.className='vis-foreground';frame.appendChild(foreground);this.dom.foreground=foreground;// create axis panel
const axis=document.createElement('div');axis.className='vis-axis';this.dom.axis=axis;// create labelset
const labelSet=document.createElement('div');labelSet.className='vis-labelset';this.dom.labelSet=labelSet;// create ungrouped Group
this._updateUngrouped();// create background Group
const backgroundGroup=new BackgroundGroup(BACKGROUND,null,this);backgroundGroup.show();this.groups[BACKGROUND]=backgroundGroup;// attach event listeners
// Note: we bind to the centerContainer for the case where the height
// of the center container is larger than of the ItemSet, so we
// can click in the empty area to create a new item or deselect an item.
this.hammer=new Hammer(this.body.dom.centerContainer);// drag items when selected
this.hammer.on('hammer.input',event=>{if(event.isFirst){this._onTouch(event);}});this.hammer.on('panstart',this._onDragStart.bind(this));this.hammer.on('panmove',this._onDrag.bind(this));this.hammer.on('panend',this._onDragEnd.bind(this));this.hammer.get('pan').set({threshold:5,direction:Hammer.ALL});// delay addition on item click for trackpads...
this.hammer.get('press').set({time:10000});// single select (or unselect) when tapping an item
this.hammer.on('tap',this._onSelectItem.bind(this));// multi select when holding mouse/touch, or on ctrl+click
this.hammer.on('press',this._onMultiSelectItem.bind(this));// delay addition on item click for trackpads...
this.hammer.get('press').set({time:10000});// add item on doubletap
this.hammer.on('doubletap',this._onAddItem.bind(this));if(this.options.rtl){this.groupHammer=new Hammer(this.body.dom.rightContainer);}else {this.groupHammer=new Hammer(this.body.dom.leftContainer);}this.groupHammer.on('tap',this._onGroupClick.bind(this));this.groupHammer.on('panstart',this._onGroupDragStart.bind(this));this.groupHammer.on('panmove',this._onGroupDrag.bind(this));this.groupHammer.on('panend',this._onGroupDragEnd.bind(this));this.groupHammer.get('pan').set({threshold:5,direction:Hammer.DIRECTION_VERTICAL});this.body.dom.centerContainer.addEventListener('mouseover',this._onMouseOver.bind(this));this.body.dom.centerContainer.addEventListener('mouseout',this._onMouseOut.bind(this));this.body.dom.centerContainer.addEventListener('mousemove',this._onMouseMove.bind(this));// right-click on timeline
this.body.dom.centerContainer.addEventListener('contextmenu',this._onDragEnd.bind(this));this.body.dom.centerContainer.addEventListener('mousewheel',this._onMouseWheel.bind(this));// attach to the DOM
this.show();}/**
* Set options for the ItemSet. Existing options will be extended/overwritten.
* @param {Object} [options] The following options are available:
* {string} type
* Default type for the items. Choose from 'box'
* (default), 'point', 'range', or 'background'.
* The default style can be overwritten by
* individual items.
* {string} align
* Alignment for the items, only applicable for
* BoxItem. Choose 'center' (default), 'left', or
* 'right'.
* {string} orientation.item
* Orientation of the item set. Choose 'top' or
* 'bottom' (default).
* {Function} groupOrder
* A sorting function for ordering groups
* {boolean} stack
* If true (default), items will be stacked on
* top of each other.
* {number} margin.axis
* Margin between the axis and the items in pixels.
* Default is 20.
* {number} margin.item.horizontal
* Horizontal margin between items in pixels.
* Default is 10.
* {number} margin.item.vertical
* Vertical Margin between items in pixels.
* Default is 10.
* {number} margin.item
* Margin between items in pixels in both horizontal
* and vertical direction. Default is 10.
* {number} margin
* Set margin for both axis and items in pixels.
* {boolean} selectable
* If true (default), items can be selected.
* {boolean} multiselect
* If true, multiple items can be selected.
* False by default.
* {boolean} editable
* Set all editable options to true or false
* {boolean} editable.updateTime
* Allow dragging an item to an other moment in time
* {boolean} editable.updateGroup
* Allow dragging an item to an other group
* {boolean} editable.add
* Allow creating new items on double tap
* {boolean} editable.remove
* Allow removing items by clicking the delete button
* top right of a selected item.
* {Function(item: Item, callback: Function)} onAdd
* Callback function triggered when an item is about to be added:
* when the user double taps an empty space in the Timeline.
* {Function(item: Item, callback: Function)} onUpdate
* Callback function fired when an item is about to be updated.
* This function typically has to show a dialog where the user
* change the item. If not implemented, nothing happens.
* {Function(item: Item, callback: Function)} onMove
* Fired when an item has been moved. If not implemented,
* the move action will be accepted.
* {Function(item: Item, callback: Function)} onRemove
* Fired when an item is about to be deleted.
* If not implemented, the item will be always removed.
*/setOptions(options){if(options){// copy all options that we know
const fields=['type','rtl','align','order','stack','stackSubgroups','selectable','multiselect','sequentialSelection','multiselectPerGroup','longSelectPressTime','groupOrder','dataAttributes','template','groupTemplate','visibleFrameTemplate','hide','snap','groupOrderSwap','showTooltips','tooltip','tooltipOnItemUpdateTime','groupHeightMode','onTimeout'];availableUtils.selectiveExtend(fields,this.options,options);if('itemsAlwaysDraggable'in options){if(typeof options.itemsAlwaysDraggable==='boolean'){this.options.itemsAlwaysDraggable.item=options.itemsAlwaysDraggable;this.options.itemsAlwaysDraggable.range=false;}else if(typeof options.itemsAlwaysDraggable==='object'){availableUtils.selectiveExtend(['item','range'],this.options.itemsAlwaysDraggable,options.itemsAlwaysDraggable);// only allow range always draggable when item is always draggable as well
if(!this.options.itemsAlwaysDraggable.item){this.options.itemsAlwaysDraggable.range=false;}}}if('sequentialSelection'in options){if(typeof options.sequentialSelection==='boolean'){this.options.sequentialSelection=options.sequentialSelection;}}if('orientation'in options){if(typeof options.orientation==='string'){this.options.orientation.item=options.orientation==='top'?'top':'bottom';}else if(typeof options.orientation==='object'&&'item'in options.orientation){this.options.orientation.item=options.orientation.item;}}if('margin'in options){if(typeof options.margin==='number'){this.options.margin.axis=options.margin;this.options.margin.item.horizontal=options.margin;this.options.margin.item.vertical=options.margin;}else if(typeof options.margin==='object'){availableUtils.selectiveExtend(['axis'],this.options.margin,options.margin);if('item'in options.margin){if(typeof options.margin.item==='number'){this.options.margin.item.horizontal=options.margin.item;this.options.margin.item.vertical=options.margin.item;}else if(typeof options.margin.item==='object'){availableUtils.selectiveExtend(['horizontal','vertical'],this.options.margin.item,options.margin.item);}}}}['locale','locales'].forEach(key=>{if(key in options){this.options[key]=options[key];}});if('editable'in options){if(typeof options.editable==='boolean'){this.options.editable.updateTime=options.editable;this.options.editable.updateGroup=options.editable;this.options.editable.add=options.editable;this.options.editable.remove=options.editable;this.options.editable.overrideItems=false;}else if(typeof options.editable==='object'){availableUtils.selectiveExtend(['updateTime','updateGroup','add','remove','overrideItems'],this.options.editable,options.editable);}}if('groupEditable'in options){if(typeof options.groupEditable==='boolean'){this.options.groupEditable.order=options.groupEditable;this.options.groupEditable.add=options.groupEditable;this.options.groupEditable.remove=options.groupEditable;}else if(typeof options.groupEditable==='object'){availableUtils.selectiveExtend(['order','add','remove'],this.options.groupEditable,options.groupEditable);}}// callback functions
const addCallback=name=>{const fn=options[name];if(fn){if(!(typeof fn==='function')){throw new Error(`option ${name} must be a function ${name}(item, callback)`);}this.options[name]=fn;}};['onDropObjectOnItem','onAdd','onUpdate','onRemove','onMove','onMoving','onAddGroup','onMoveGroup','onRemoveGroup'].forEach(addCallback);if(options.cluster){Object.assign(this.options,{cluster:options.cluster});if(!this.clusterGenerator){this.clusterGenerator=new ClusterGenerator(this);}this.clusterGenerator.setItems(this.items,{applyOnChangedLevel:false});this.markDirty({refreshItems:true,restackGroups:true});this.redraw();}else if(this.clusterGenerator){this._detachAllClusters();this.clusters=[];this.clusterGenerator=null;this.options.cluster=undefined;this.markDirty({refreshItems:true,restackGroups:true});this.redraw();}else {// force the itemSet to refresh: options like orientation and margins may be changed
this.markDirty();}}}/**
* Mark the ItemSet dirty so it will refresh everything with next redraw.
* Optionally, all items can be marked as dirty and be refreshed.
* @param {{refreshItems: boolean}} [options]
*/markDirty(options){this.groupIds=[];if(options){if(options.refreshItems){availableUtils.forEach(this.items,item=>{item.dirty=true;if(item.displayed)item.redraw();});}if(options.restackGroups){availableUtils.forEach(this.groups,(group,key)=>{if(key===BACKGROUND)return;group.stackDirty=true;});}}}/**
* Destroy the ItemSet
*/destroy(){this.clearPopupTimer();this.hide();this.setItems(null);this.setGroups(null);this.hammer&&this.hammer.destroy();this.groupHammer&&this.groupHammer.destroy();this.hammer=null;this.body=null;this.conversion=null;}/**
* Hide the component from the DOM
*/hide(){// remove the frame containing the items
if(this.dom.frame.parentNode){this.dom.frame.parentNode.removeChild(this.dom.frame);}// remove the axis with dots
if(this.dom.axis.parentNode){this.dom.axis.parentNode.removeChild(this.dom.axis);}// remove the labelset containing all group labels
if(this.dom.labelSet.parentNode){this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);}}/**
* Show the component in the DOM (when not already visible).
*/show(){// show frame containing the items
if(!this.dom.frame.parentNode){this.body.dom.center.appendChild(this.dom.frame);}// show axis with dots
if(!this.dom.axis.parentNode){this.body.dom.backgroundVertical.appendChild(this.dom.axis);}// show labelset containing labels
if(!this.dom.labelSet.parentNode){if(this.options.rtl){this.body.dom.right.appendChild(this.dom.labelSet);}else {this.body.dom.left.appendChild(this.dom.labelSet);}}}/**
* Activates the popup timer to show the given popup after a fixed time.
* @param {Popup} popup
*/setPopupTimer(popup){this.clearPopupTimer();if(popup){const delay=this.options.tooltip.delay||typeof this.options.tooltip.delay==='number'?this.options.tooltip.delay:500;this.popupTimer=setTimeout(function(){popup.show();},delay);}}/**
* Clears the popup timer for the tooltip.
*/clearPopupTimer(){if(this.popupTimer!=null){clearTimeout(this.popupTimer);this.popupTimer=null;}}/**
* Set selected items by their id. Replaces the current selection
* Unknown id's are silently ignored.
* @param {string[] | string} [ids] An array with zero or more id's of the items to be
* selected, or a single item id. If ids is undefined
* or an empty array, all items will be unselected.
*/setSelection(ids){if(ids==undefined){ids=[];}if(!Array.isArray(ids)){ids=[ids];}const idsToDeselect=this.selection.filter(id=>ids.indexOf(id)===-1);// unselect currently selected items
for(let selectedId of idsToDeselect){const item=this.getItemById(selectedId);if(item){item.unselect();}}// select items
this.selection=[...ids];for(let id of ids){const item=this.getItemById(id);if(item){item.select();}}}/**
* Get the selected items by their id
* @return {Array} ids The ids of the selected items
*/getSelection(){return this.selection.concat([]);}/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/getVisibleItems(){const range=this.body.range.getRange();let right;let left;if(this.options.rtl){right=this.body.util.toScreen(range.start);left=this.body.util.toScreen(range.end);}else {left=this.body.util.toScreen(range.start);right=this.body.util.toScreen(range.end);}const ids=[];for(const groupId in this.groups){if(this.groups.hasOwnProperty(groupId)){const group=this.groups[groupId];const rawVisibleItems=group.isVisible?group.visibleItems:[];// filter the "raw" set with visibleItems into a set which is really
// visible by pixels
for(const item of rawVisibleItems){// TODO: also check whether visible vertically
if(this.options.rtl){if(item.right<left&&item.right+item.width>right){ids.push(item.id);}}else {if(item.left<right&&item.left+item.width>left){ids.push(item.id);}}}}}return ids;}/**
* Get the id's of the items at specific time, where a click takes place on the timeline.
* @returns {Array} The ids of all items in existence at the time of click event on the timeline.
*/getItemsAtCurrentTime(timeOfEvent){let right;let left;if(this.options.rtl){right=this.body.util.toScreen(timeOfEvent);left=this.body.util.toScreen(timeOfEvent);}else {left=this.body.util.toScreen(timeOfEvent);right=this.body.util.toScreen(timeOfEvent);}const ids=[];for(const groupId in this.groups){if(this.groups.hasOwnProperty(groupId)){const group=this.groups[groupId];const rawVisibleItems=group.isVisible?group.visibleItems:[];// filter the "raw" set with visibleItems into a set which is really
// visible by pixels
for(const item of rawVisibleItems){if(this.options.rtl){if(item.right<left&&item.right+item.width>right){ids.push(item.id);}}else {if(item.left<right&&item.left+item.width>left){ids.push(item.id);}}}}}return ids;}/**
* Get the id's of the currently visible groups.
* @returns {Array} The ids of the visible groups
*/getVisibleGroups(){const ids=[];for(const groupId in this.groups){if(this.groups.hasOwnProperty(groupId)){const group=this.groups[groupId];if(group.isVisible){ids.push(groupId);}}}return ids;}/**
* get item by id
* @param {string} id
* @return {object} item
*/getItemById(id){return this.items[id]||this.clusters.find(cluster=>cluster.id===id);}/**
* Deselect a selected item
* @param {string | number} id
* @private
*/_deselect(id){const selection=this.selection;for(let i=0,ii=selection.length;i<ii;i++){if(selection[i]==id){// non-strict comparison!
selection.splice(i,1);break;}}}/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/redraw(){const margin=this.options.margin;const range=this.body.range;const asSize=availableUtils.option.asSize;const options=this.options;const orientation=options.orientation.item;let resized=false;const frame=this.dom.frame;// recalculate absolute position (before redrawing groups)
this.props.top=this.body.domProps.top.height+this.body.domProps.border.top;if(this.options.rtl){this.props.right=this.body.domProps.right.width+this.body.domProps.border.right;}else {this.props.left=this.body.domProps.left.width+this.body.domProps.border.left;}// update class name
frame.className='vis-itemset';if(this.options.cluster){this._clusterItems();}// reorder the groups (if needed)
resized=this._orderGroups()||resized;// check whether zoomed (in that case we need to re-stack everything)
// TODO: would be nicer to get this as a trigger from Range
const visibleInterval=range.end-range.start;const zoomed=visibleInterval!=this.lastVisibleInterval||this.props.width!=this.props.lastWidth;const scrolled=range.start!=this.lastRangeStart;const changedStackOption=options.stack!=this.lastStack;const changedStackSubgroupsOption=options.stackSubgroups!=this.lastStackSubgroups;const forceRestack=zoomed||scrolled||changedStackOption||changedStackSubgroupsOption;this.lastVisibleInterval=visibleInterval;this.lastRangeStart=range.start;this.lastStack=options.stack;this.lastStackSubgroups=options.stackSubgroups;this.props.lastWidth=this.props.width;const firstGroup=this._firstGroup();const firstMargin={item:margin.item,axis:margin.axis};const nonFirstMargin={item:margin.item,axis:margin.item.vertical/2};let height=0;const minHeight=margin.axis+margin.item.vertical;// redraw the background group
this.groups[BACKGROUND].redraw(range,nonFirstMargin,forceRestack);const redrawQueue={};let redrawQueueLength=0;// collect redraw functions
availableUtils.forEach(this.groups,(group,key)=>{if(key===BACKGROUND)return;const groupMargin=group==firstGroup?firstMargin:nonFirstMargin;const returnQueue=true;redrawQueue[key]=group.redraw(range,groupMargin,forceRestack,returnQueue);redrawQueueLength=redrawQueue[key].length;});const needRedraw=redrawQueueLength>0;if(needRedraw){const redrawResults={};for(let i=0;i<redrawQueueLength;i++){availableUtils.forEach(redrawQueue,(fns,key)=>{redrawResults[key]=fns[i]();});}// redraw all regular groups
availableUtils.forEach(this.groups,(group,key)=>{if(key===BACKGROUND)return;const groupResized=redrawResults[key];resized=groupResized||resized;height+=group.height;});height=Math.max(height,minHeight);}height=Math.max(height,minHeight);// update frame height
frame.style.height=asSize(height);// calculate actual size
this.props.width=frame.offsetWidth;this.props.height=height;// reposition axis
this.dom.axis.style.top=asSize(orientation=='top'?this.body.domProps.top.height+this.body.domProps.border.top:this.body.domProps.top.height+this.body.domProps.centerContainer.height);if(this.options.rtl){this.dom.axis.style.right='0';}else {this.dom.axis.style.left='0';}this.hammer.get('press').set({time:this.options.longSelectPressTime});this.initialItemSetDrawn=true;// check if this component is resized
resized=this._isResized()||resized;return resized;}/**
* Get the first group, aligned with the axis
* @return {Group | null} firstGroup
* @private
*/_firstGroup(){const firstGroupIndex=this.options.orientation.item=='top'?0:this.groupIds.length-1;const firstGroupId=this.groupIds[firstGroupIndex];const firstGroup=this.groups[firstGroupId]||this.groups[UNGROUPED$1];return firstGroup||null;}/**
* Create or delete the group holding all ungrouped items. This group is used when
* there are no groups specified.
* @protected
*/_updateUngrouped(){let ungrouped=this.groups[UNGROUPED$1];let item;let itemId;if(this.groupsData){// remove the group holding all ungrouped items
if(ungrouped){ungrouped.dispose();delete this.groups[UNGROUPED$1];for(itemId in this.items){if(this.items.hasOwnProperty(itemId)){item=this.items[itemId];item.parent&&item.parent.remove(item);const groupId=this.getGroupId(item.data);const group=this.groups[groupId];group&&group.add(item)||item.hide();}}}}else {// create a group holding all (unfiltered) items
if(!ungrouped){const id=null;const data=null;ungrouped=new Group(id,data,this);this.groups[UNGROUPED$1]=ungrouped;for(itemId in this.items){if(this.items.hasOwnProperty(itemId)){item=this.items[itemId];ungrouped.add(item);}}ungrouped.show();}}}/**
* Get the element for the labelset
* @return {HTMLElement} labelSet
*/getLabelSet(){return this.dom.labelSet;}/**
* Set items
* @param {vis.DataSet | null} items
*/setItems(items){this.itemsSettingTime=new Date();const me=this;let ids;const oldItemsData=this.itemsData;// replace the dataset
if(!items){this.itemsData=null;}else if(isDataViewLike(items)){this.itemsData=typeCoerceDataSet(items);}else {throw new TypeError('Data must implement the interface of DataSet or DataView');}if(oldItemsData){// unsubscribe from old dataset
availableUtils.forEach(this.itemListeners,(callback,event)=>{oldItemsData.off(event,callback);});// stop maintaining a coerced version of the old data set
oldItemsData.dispose();// remove all drawn items
ids=oldItemsData.getIds();this._onRemove(ids);}if(this.itemsData){// subscribe to new dataset
const id=this.id;availableUtils.forEach(this.itemListeners,(callback,event)=>{me.itemsData.on(event,callback,id);});// add all new items
ids=this.itemsData.getIds();this._onAdd(ids);// update the group holding all ungrouped items
this._updateUngrouped();}this.body.emitter.emit('_change',{queue:true});}/**
* Get the current items
* @returns {vis.DataSet | null}
*/getItems(){return this.itemsData!=null?this.itemsData.rawDS:null;}/**
* Set groups
* @param {vis.DataSet} groups
*/setGroups(groups){const me=this;let ids;// unsubscribe from current dataset
if(this.groupsData){availableUtils.forEach(this.groupListeners,(callback,event)=>{me.groupsData.off(event,callback);});// remove all drawn groups
ids=this.groupsData.getIds();this.groupsData=null;this._onRemoveGroups(ids);// note: this will cause a redraw
}// replace the dataset
if(!groups){this.groupsData=null;}else if(isDataViewLike(groups)){this.groupsData=groups;}else {throw new TypeError('Data must implement the interface of DataSet or DataView');}if(this.groupsData){// go over all groups nesting
const groupsData=this.groupsData.getDataSet();groupsData.get().forEach(group=>{if(group.nestedGroups){group.nestedGroups.forEach(nestedGroupId=>{const updatedNestedGroup=groupsData.get(nestedGroupId);updatedNestedGroup.nestedInGroup=group.id;if(group.showNested==false){updatedNestedGroup.visible=false;}groupsData.update(updatedNestedGroup);});}});// subscribe to new dataset
const id=this.id;availableUtils.forEach(this.groupListeners,(callback,event)=>{me.groupsData.on(event,callback,id);});// draw all ms
ids=this.groupsData.getIds();this._onAddGroups(ids);}// update the group holding all ungrouped items
this._updateUngrouped();// update the order of all items in each group
this._order();if(this.options.cluster){this.clusterGenerator.updateData();this._clusterItems();this.markDirty({refreshItems:true,restackGroups:true});}this.body.emitter.emit('_change',{queue:true});}/**
* Get the current groups
* @returns {vis.DataSet | null} groups
*/getGroups(){return this.groupsData;}/**
* Remove an item by its id
* @param {string | number} id
*/removeItem(id){const item=this.itemsData.get(id);if(item){// confirm deletion
this.options.onRemove(item,item=>{if(item){// remove by id here, it is possible that an item has no id defined
// itself, so better not delete by the item itself
this.itemsData.remove(id);}});}}/**
* Get the time of an item based on it's data and options.type
* @param {Object} itemData
* @returns {string} Returns the type
* @private
*/_getType(itemData){return itemData.type||this.options.type||(itemData.end?'range':'box');}/**
* Get the group id for an item
* @param {Object} itemData
* @returns {string} Returns the groupId
* @private
*/getGroupId(itemData){const type=this._getType(itemData);if(type=='background'&&itemData.group==undefined){return BACKGROUND;}else {return this.groupsData?itemData.group:UNGROUPED$1;}}/**
* Handle updated items
* @param {number[]} ids
* @protected
*/_onUpdate(ids){const me=this;ids.forEach(id=>{const itemData=me.itemsData.get(id);let item=me.items[id];const type=itemData?me._getType(itemData):null;const constructor=ItemSet.types[type];let selected;if(item){// update item
if(!constructor||!(item instanceof constructor)){// item type has changed, delete the item and recreate it
selected=item.selected;// preserve selection of this item
me._removeItem(item);item=null;}else {me._updateItem(item,itemData);}}if(!item&&itemData){// create item
if(constructor){item=new constructor(itemData,me.conversion,me.options);item.id=id;// TODO: not so nice setting id afterwards
me._addItem(item);if(selected){this.selection.push(id);item.select();}}else {throw new TypeError(`Unknown item type "${type}"`);}}});this._order();if(this.options.cluster){this.clusterGenerator.setItems(this.items,{applyOnChangedLevel:false});this._clusterItems();}this.body.emitter.emit('_change',{queue:true});}/**
* Handle removed items
* @param {number[]} ids
* @protected
*/_onRemove(ids){let count=0;const me=this;ids.forEach(id=>{const item=me.items[id];if(item){count++;me._removeItem(item);}});if(count){// update order
this._order();this.body.emitter.emit('_change',{queue:true});}}/**
* Update the order of item in all groups
* @private
*/_order(){// reorder the items in all groups
// TODO: optimization: only reorder groups affected by the changed items
availableUtils.forEach(this.groups,group=>{group.order();});}/**
* Handle updated groups
* @param {number[]} ids
* @private
*/_onUpdateGroups(ids){this._onAddGroups(ids);}/**
* Handle changed groups (added or updated)
* @param {number[]} ids
* @private
*/_onAddGroups(ids){const me=this;ids.forEach(id=>{const groupData=me.groupsData.get(id);let group=me.groups[id];if(!group){// check for reserved ids
if(id==UNGROUPED$1||id==BACKGROUND){throw new Error(`Illegal group id. ${id} is a reserved id.`);}const groupOptions=Object.create(me.options);availableUtils.extend(groupOptions,{height:null});group=new Group(id,groupData,me);me.groups[id]=group;// add items with this groupId to the new group
for(const itemId in me.items){if(me.items.hasOwnProperty(itemId)){const item=me.items[itemId];if(item.data.group==id){group.add(item);}}}group.order();group.show();}else {// update group
group.setData(groupData);}});this.body.emitter.emit('_change',{queue:true});}/**
* Handle removed groups
* @param {number[]} ids
* @private
*/_onRemoveGroups(ids){ids.forEach(id=>{const group=this.groups[id];if(group){group.dispose();delete this.groups[id];}});if(this.options.cluster){this.clusterGenerator.updateData();this._clusterItems();}this.markDirty({restackGroups:!!this.options.cluster});this.body.emitter.emit('_change',{queue:true});}/**
* Reorder the groups if needed
* @return {boolean} changed
* @private
*/_orderGroups(){if(this.groupsData){// reorder the groups
let groupIds=this.groupsData.getIds({order:this.options.groupOrder});groupIds=this._orderNestedGroups(groupIds);const changed=!availableUtils.equalArray(groupIds,this.groupIds);if(changed){// hide all groups, removes them from the DOM
const groups=this.groups;groupIds.forEach(groupId=>{groups[groupId].hide();});// show the groups again, attach them to the DOM in correct order
groupIds.forEach(groupId=>{groups[groupId].show();});this.groupIds=groupIds;}return changed;}else {return false;}}/**
* Reorder the nested groups
*
* @param {Array.<number>} groupIds
* @returns {Array.<number>}
* @private
*/_orderNestedGroups(groupIds){/**
* Recursively order nested groups
*
* @param {ItemSet} t
* @param {Array.<number>} groupIds
* @returns {Array.<number>}
* @private
*/function getOrderedNestedGroups(t,groupIds){let result=[];groupIds.forEach(groupId=>{result.push(groupId);const groupData=t.groupsData.get(groupId);if(groupData.nestedGroups){const nestedGroupIds=t.groupsData.get({filter(nestedGroup){return nestedGroup.nestedInGroup==groupId;},order:t.options.groupOrder}).map(nestedGroup=>nestedGroup.id);result=result.concat(getOrderedNestedGroups(t,nestedGroupIds));}});return result;}const topGroupIds=groupIds.filter(groupId=>!this.groupsData.get(groupId).nestedInGroup);return getOrderedNestedGroups(this,topGroupIds);}/**
* Add a new item
* @param {Item} item
* @private
*/_addItem(item){this.items[item.id]=item;// add to group
const groupId=this.getGroupId(item.data);const group=this.groups[groupId];if(!group){item.groupShowing=false;}else if(group&&group.data&&group.data.showNested){item.groupShowing=true;}if(group)group.add(item);}/**
* Update an existing item
* @param {Item} item
* @param {Object} itemData
* @private
*/_updateItem(item,itemData){// update the items data (will redraw the item when displayed)
item.setData(itemData);const groupId=this.getGroupId(item.data);const group=this.groups[groupId];if(!group){item.groupShowing=false;}else if(group&&group.data&&group.data.showNested){item.groupShowing=true;}}/**
* Delete an item from the ItemSet: remove it from the DOM, from the map
* with items, and from the map with visible items, and from the selection
* @param {Item} item
* @private
*/_removeItem(item){// remove from DOM
item.hide();// remove from items
delete this.items[item.id];// remove from selection
const index=this.selection.indexOf(item.id);if(index!=-1)this.selection.splice(index,1);// remove from group
item.parent&&item.parent.remove(item);// remove Tooltip from DOM
if(this.popup!=null){this.popup.hide();}}/**
* Create an array containing all items being a range (having an end date)
* @param {Array.<Object>} array
* @returns {Array}
* @private
*/_constructByEndArray(array){const endArray=[];for(let i=0;i<array.length;i++){if(array[i]instanceof RangeItem){endArray.push(array[i]);}}return endArray;}/**
* Register the clicked item on touch, before dragStart is initiated.
*
* dragStart is initiated from a mousemove event, AFTER the mouse/touch is
* already moving. Therefore, the mouse/touch can sometimes be above an other
* DOM element than the item itself.
*
* @param {Event} event
* @private
*/_onTouch(event){// store the touched item, used in _onDragStart
this.touchParams.item=this.itemFromTarget(event);this.touchParams.dragLeftItem=event.target.dragLeftItem||false;this.touchParams.dragRightItem=event.target.dragRightItem||false;this.touchParams.itemProps=null;}/**
* Given an group id, returns the index it has.
*
* @param {number} groupId
* @returns {number} index / groupId
* @private
*/_getGroupIndex(groupId){for(let i=0;i<this.groupIds.length;i++){if(groupId==this.groupIds[i])return i;}}/**
* Start dragging the selected events
* @param {Event} event
* @private
*/_onDragStart(event){if(this.touchParams.itemIsDragging){return;}const item=this.touchParams.item||null;const me=this;let props;if(item&&(item.selected||this.options.itemsAlwaysDraggable.item)){if(this.options.editable.overrideItems&&!this.options.editable.updateTime&&!this.options.editable.updateGroup){return;}// override options.editable
if(item.editable!=null&&!item.editable.updateTime&&!item.editable.updateGroup&&!this.options.editable.overrideItems){return;}const dragLeftItem=this.touchParams.dragLeftItem;const dragRightItem=this.touchParams.dragRightItem;this.touchParams.itemIsDragging=true;this.touchParams.selectedItem=item;if(dragLeftItem){props={item:dragLeftItem,initialX:event.center.x,dragLeft:true,data:this._cloneItemData(item.data)};this.touchParams.itemProps=[props];}else if(dragRightItem){props={item:dragRightItem,initialX:event.center.x,dragRight:true,data:this._cloneItemData(item.data)};this.touchParams.itemProps=[props];}else if(this.options.editable.add&&(event.srcEvent.ctrlKey||event.srcEvent.metaKey)){// create a new range item when dragging with ctrl key down
this._onDragStartAddItem(event);}else {if(this.groupIds.length<1){// Mitigates a race condition if _onDragStart() is
// called after markDirty() without redraw() being called between.
this.redraw();}const baseGroupIndex=this._getGroupIndex(item.data.group);const itemsToDrag=this.options.itemsAlwaysDraggable.item&&!item.selected?[item.id]:this.getSelection();this.touchParams.itemProps=itemsToDrag.map(id=>{const item=me.items[id];const groupIndex=me._getGroupIndex(item.data.group);return {item,initialX:event.center.x,groupOffset:baseGroupIndex-groupIndex,data:this._cloneItemData(item.data)};});}event.stopPropagation();}else if(this.options.editable.add&&(event.srcEvent.ctrlKey||event.srcEvent.metaKey)){// create a new range item when dragging with ctrl key down
this._onDragStartAddItem(event);}}/**
* Start creating a new range item by dragging.
* @param {Event} event
* @private
*/_onDragStartAddItem(event){const snap=this.options.snap||null;const frameRect=this.dom.frame.getBoundingClientRect();// plus (if rtl) 10 to compensate for the drag starting as soon as you've moved 10px
const x=this.options.rtl?frameRect.right-event.center.x+10:event.center.x-frameRect.left-10;const time=this.body.util.toTime(x);const scale=this.body.util.getScale();const step=this.body.util.getStep();const start=snap?snap(time,scale,step):time;const end=start;const itemData={type:'range',start,end,content:'new item'};const id=v4();itemData[this.itemsData.idProp]=id;const group=this.groupFromTarget(event);if(group){itemData.group=group.groupId;}const newItem=new RangeItem(itemData,this.conversion,this.options);newItem.id=id;// TODO: not so nice setting id afterwards
newItem.data=this._cloneItemData(itemData);this._addItem(newItem);this.touchParams.selectedItem=newItem;const props={item:newItem,initialX:event.center.x,data:newItem.data};if(this.options.rtl){props.dragLeft=true;}else {props.dragRight=true;}this.touchParams.itemProps=[props];event.stopPropagation();}/**
* Drag selected items
* @param {Event} event
* @private
*/_onDrag(event){if(this.popup!=null&&this.options.showTooltips&&!this.popup.hidden){// this.popup.hide();
const container=this.body.dom.centerContainer;const containerRect=container.getBoundingClientRect();this.popup.setPosition(event.center.x-containerRect.left+container.offsetLeft,event.center.y-containerRect.top+container.offsetTop);this.popup.show();// redraw
}if(this.touchParams.itemProps){event.stopPropagation();const me=this;const snap=this.options.snap||null;const domRootOffsetLeft=this.body.dom.root.offsetLeft;const xOffset=this.options.rtl?domRootOffsetLeft+this.body.domProps.right.width:domRootOffsetLeft+this.body.domProps.left.width;const scale=this.body.util.getScale();const step=this.body.util.getStep();//only calculate the new group for the item that's actually dragged
const selectedItem=this.touchParams.selectedItem;const updateGroupAllowed=(this.options.editable.overrideItems||selectedItem.editable==null)&&this.options.editable.updateGroup||!this.options.editable.overrideItems&&selectedItem.editable!=null&&selectedItem.editable.updateGroup;let newGroupBase=null;if(updateGroupAllowed&&selectedItem){if(selectedItem.data.group!=undefined){// drag from one group to another
const group=me.groupFromTarget(event);if(group){//we know the offset for all items, so the new group for all items
//will be relative to this one.
newGroupBase=this._getGroupIndex(group.groupId);}}}// move
this.touchParams.itemProps.forEach(props=>{const current=me.body.util.toTime(event.center.x-xOffset);const initial=me.body.util.toTime(props.initialX-xOffset);let offset;let initialStart;let initialEnd;let start;let end;if(this.options.rtl){offset=-(current-initial);// ms
}else {offset=current-initial;// ms
}let itemData=this._cloneItemData(props.item.data);// clone the data
if(props.item.editable!=null&&!props.item.editable.updateTime&&!props.item.editable.updateGroup&&!me.options.editable.overrideItems){return;}const updateTimeAllowed=(this.options.editable.overrideItems||selectedItem.editable==null)&&this.options.editable.updateTime||!this.options.editable.overrideItems&&selectedItem.editable!=null&&selectedItem.editable.updateTime;if(updateTimeAllowed){if(props.dragLeft){// drag left side of a range item
if(this.options.rtl){if(itemData.end!=undefined){initialEnd=availableUtils.convert(props.data.end,'Date');end=new Date(initialEnd.valueOf()+offset);// TODO: pass a Moment instead of a Date to snap(). (Breaking change)
itemData.end=snap?snap(end,scale,step):end;}}else {if(itemData.start!=undefined){initialStart=availableUtils.convert(props.data.start,'Date');start=new Date(initialStart.valueOf()+offset);// TODO: pass a Moment instead of a Date to snap(). (Breaking change)
itemData.start=snap?snap(start,scale,step):start;}}}else if(props.dragRight){// drag right side of a range item
if(this.options.rtl){if(itemData.start!=undefined){initialStart=availableUtils.convert(props.data.start,'Date');start=new Date(initialStart.valueOf()+offset);// TODO: pass a Moment instead of a Date to snap(). (Breaking change)
itemData.start=snap?snap(start,scale,step):start;}}else {if(itemData.end!=undefined){initialEnd=availableUtils.convert(props.data.end,'Date');end=new Date(initialEnd.valueOf()+offset);// TODO: pass a Moment instead of a Date to snap(). (Breaking change)
itemData.end=snap?snap(end,scale,step):end;}}}else {// drag both start and end
if(itemData.start!=undefined){initialStart=availableUtils.convert(props.data.start,'Date').valueOf();start=new Date(initialStart+offset);if(itemData.end!=undefined){initialEnd=availableUtils.convert(props.data.end,'Date');const duration=initialEnd.valueOf()-initialStart.valueOf();// TODO: pass a Moment instead of a Date to snap(). (Breaking change)
itemData.start=snap?snap(start,scale,step):start;itemData.end=new Date(itemData.start.valueOf()+duration);}else {// TODO: pass a Moment instead of a Date to snap(). (Breaking change)
itemData.start=snap?snap(start,scale,step):start;}}}}if(updateGroupAllowed&&!props.dragLeft&&!props.dragRight&&newGroupBase!=null){if(itemData.group!=undefined){let newOffset=newGroupBase-props.groupOffset;//make sure we stay in bounds
newOffset=Math.max(0,newOffset);newOffset=Math.min(me.groupIds.length-1,newOffset);itemData.group=me.groupIds[newOffset];}}// confirm moving the item
itemData=this._cloneItemData(itemData);// convert start and end to the correct type
me.options.onMoving(itemData,itemData=>{if(itemData){props.item.setData(this._cloneItemData(itemData,'Date'));}});});this.body.emitter.emit('_change');}}/**
* Move an item to another group
* @param {Item} item
* @param {string | number} groupId
* @private
*/_moveToGroup(item,groupId){const group=this.groups[groupId];if(group&&group.groupId!=item.data.group){const oldGroup=item.parent;oldGroup.remove(item);oldGroup.order();item.data.group=group.groupId;group.add(item);group.order();}}/**
* End of dragging selected items
* @param {Event} event
* @private
*/_onDragEnd(event){this.touchParams.itemIsDragging=false;if(this.touchParams.itemProps){event.stopPropagation();const me=this;const itemProps=this.touchParams.itemProps;this.touchParams.itemProps=null;itemProps.forEach(props=>{const id=props.item.id;const exists=me.itemsData.get(id)!=null;if(!exists){// add a new item
me.options.onAdd(props.item.data,itemData=>{me._removeItem(props.item);// remove temporary item
if(itemData){me.itemsData.add(itemData);}// force re-stacking of all items next redraw
me.body.emitter.emit('_change');});}else {// update existing item
const itemData=this._cloneItemData(props.item.data);// convert start and end to the correct type
me.options.onMove(itemData,itemData=>{if(itemData){// apply changes
itemData[this.itemsData.idProp]=id;// ensure the item contains its id (can be undefined)
this.itemsData.update(itemData);}else {// restore original values
props.item.setData(props.data);me.body.emitter.emit('_change');}});}});}}/**
* On group click
* @param {Event} event
* @private
*/_onGroupClick(event){const group=this.groupFromTarget(event);setTimeout(()=>{this.toggleGroupShowNested(group);},1);}/**
* Toggle show nested
* @param {object} group
* @param {boolean} force
*/toggleGroupShowNested(group,force=undefined){if(!group||!group.nestedGroups)return;const groupsData=this.groupsData.getDataSet();if(force!=undefined){group.showNested=!!force;}else {group.showNested=!group.showNested;}let nestingGroup=groupsData.get(group.groupId);nestingGroup.showNested=group.showNested;let fullNestedGroups=group.nestedGroups;let nextLevel=fullNestedGroups;while(nextLevel.length>0){let current=nextLevel;nextLevel=[];for(let i=0;i<current.length;i++){let node=groupsData.get(current[i]);if(node.nestedGroups){nextLevel=nextLevel.concat(node.nestedGroups);}}if(nextLevel.length>0){fullNestedGroups=fullNestedGroups.concat(nextLevel);}}var nestedGroups;if(nestingGroup.showNested){var showNestedGroups=groupsData.get(nestingGroup.nestedGroups);for(let i=0;i<showNestedGroups.length;i++){let group=showNestedGroups[i];if(group.nestedGroups&&group.nestedGroups.length>0&&(group.showNested==undefined||group.showNested==true)){showNestedGroups.push(...groupsData.get(group.nestedGroups));}}nestedGroups=showNestedGroups.map(function(nestedGroup){if(nestedGroup.visible==undefined){nestedGroup.visible=true;}nestedGroup.visible=!!nestingGroup.showNested;return nestedGroup;});}else {nestedGroups=groupsData.get(fullNestedGroups).map(function(nestedGroup){if(nestedGroup.visible==undefined){nestedGroup.visible=true;}nestedGroup.visible=!!nestingGroup.showNested;return nestedGroup;});}groupsData.update(nestedGroups.concat(nestingGroup));if(nestingGroup.showNested){availableUtils.removeClassName(group.dom.label,'collapsed');availableUtils.addClassName(group.dom.label,'expanded');}else {availableUtils.removeClassName(group.dom.label,'expanded');availableUtils.addClassName(group.dom.label,'collapsed');}}/**
* Toggle group drag classname
* @param {object} group
*/toggleGroupDragClassName(group){group.dom.label.classList.toggle('vis-group-is-dragging');group.dom.foreground.classList.toggle('vis-group-is-dragging');}/**
* on drag start
* @param {Event} event
* @return {void}
* @private
*/_onGroupDragStart(event){if(this.groupTouchParams.isDragging)return;if(this.options.groupEditable.order){this.groupTouchParams.group=this.groupFromTarget(event);if(this.groupTouchParams.group){event.stopPropagation();this.groupTouchParams.isDragging=true;this.toggleGroupDragClassName(this.groupTouchParams.group);this.groupTouchParams.originalOrder=this.groupsData.getIds({order:this.options.groupOrder});}}}/**
* on drag
* @param {Event} event
* @return {void}
* @private
*/_onGroupDrag(event){if(this.options.groupEditable.order&&this.groupTouchParams.group){event.stopPropagation();const groupsData=this.groupsData.getDataSet();// drag from one group to another
const group=this.groupFromTarget(event);// try to avoid toggling when groups differ in height
if(group&&group.height!=this.groupTouchParams.group.height){const movingUp=group.top<this.groupTouchParams.group.top;const clientY=event.center?event.center.y:event.clientY;const targetGroup=group.dom.foreground.getBoundingClientRect();const draggedGroupHeight=this.groupTouchParams.group.height;if(movingUp){// skip swapping the groups when the dragged group is not below clientY afterwards
if(targetGroup.top+draggedGroupHeight<clientY){return;}}else {const targetGroupHeight=group.height;// skip swapping the groups when the dragged group is not below clientY afterwards
if(targetGroup.top+targetGroupHeight-draggedGroupHeight>clientY){return;}}}if(group&&group!=this.groupTouchParams.group){const targetGroup=groupsData.get(group.groupId);const draggedGroup=groupsData.get(this.groupTouchParams.group.groupId);// switch groups
if(draggedGroup&&targetGroup){this.options.groupOrderSwap(draggedGroup,targetGroup,groupsData);groupsData.update(draggedGroup);groupsData.update(targetGroup);}// fetch current order of groups
const newOrder=groupsData.getIds({order:this.options.groupOrder});// in case of changes since _onGroupDragStart
if(!availableUtils.equalArray(newOrder,this.groupTouchParams.originalOrder)){const origOrder=this.groupTouchParams.originalOrder;const draggedId=this.groupTouchParams.group.groupId;const numGroups=Math.min(origOrder.length,newOrder.length);let curPos=0;let newOffset=0;let orgOffset=0;while(curPos<numGroups){// as long as the groups are where they should be step down along the groups order
while(curPos+newOffset<numGroups&&curPos+orgOffset<numGroups&&newOrder[curPos+newOffset]==origOrder[curPos+orgOffset]){curPos++;}// all ok
if(curPos+newOffset>=numGroups){break;}// not all ok
// if dragged group was move upwards everything below should have an offset
if(newOrder[curPos+newOffset]==draggedId){newOffset=1;}// if dragged group was move downwards everything above should have an offset
else if(origOrder[curPos+orgOffset]==draggedId){orgOffset=1;}// found a group (apart from dragged group) that has the wrong position -> switch with the
// group at the position where other one should be, fix index arrays and continue
else {const slippedPosition=newOrder.indexOf(origOrder[curPos+orgOffset]);const switchGroup=groupsData.get(newOrder[curPos+newOffset]);const shouldBeGroup=groupsData.get(origOrder[curPos+orgOffset]);this.options.groupOrderSwap(switchGroup,shouldBeGroup,groupsData);groupsData.update(switchGroup);groupsData.update(shouldBeGroup);const switchGroupId=newOrder[curPos+newOffset];newOrder[curPos+newOffset]=origOrder[curPos+orgOffset];newOrder[slippedPosition]=switchGroupId;curPos++;}}}}}}/**
* on drag end
* @param {Event} event
* @return {void}
* @private
*/_onGroupDragEnd(event){this.groupTouchParams.isDragging=false;if(this.options.groupEditable.order&&this.groupTouchParams.group){event.stopPropagation();// update existing group
const me=this;const id=me.groupTouchParams.group.groupId;const dataset=me.groupsData.getDataSet();const groupData=availableUtils.extend({},dataset.get(id));// clone the data
me.options.onMoveGroup(groupData,groupData=>{if(groupData){// apply changes
groupData[dataset._idProp]=id;// ensure the group contains its id (can be undefined)
dataset.update(groupData);}else {// fetch current order of groups
const newOrder=dataset.getIds({order:me.options.groupOrder});// restore original order
if(!availableUtils.equalArray(newOrder,me.groupTouchParams.originalOrder)){const origOrder=me.groupTouchParams.originalOrder;const numGroups=Math.min(origOrder.length,newOrder.length);let curPos=0;while(curPos<numGroups){// as long as the groups are where they should be step down along the groups order
while(curPos<numGroups&&newOrder[curPos]==origOrder[curPos]){curPos++;}// all ok
if(curPos>=numGroups){break;}// found a group that has the wrong position -> switch with the
// group at the position where other one should be, fix index arrays and continue
const slippedPosition=newOrder.indexOf(origOrder[curPos]);const switchGroup=dataset.get(newOrder[curPos]);const shouldBeGroup=dataset.get(origOrder[curPos]);me.options.groupOrderSwap(switchGroup,shouldBeGroup,dataset);dataset.update(switchGroup);dataset.update(shouldBeGroup);const switchGroupId=newOrder[curPos];newOrder[curPos]=origOrder[curPos];newOrder[slippedPosition]=switchGroupId;curPos++;}}}});me.body.emitter.emit('groupDragged',{groupId:id});this.toggleGroupDragClassName(this.groupTouchParams.group);this.groupTouchParams.group=null;}}/**
* Handle selecting/deselecting an item when tapping it
* @param {Event} event
* @private
*/_onSelectItem(event){if(!this.options.selectable)return;const ctrlKey=event.srcEvent&&(event.srcEvent.ctrlKey||event.srcEvent.metaKey);const shiftKey=event.srcEvent&&event.srcEvent.shiftKey;if(ctrlKey||shiftKey){this._onMultiSelectItem(event);return;}const oldSelection=this.getSelection();const item=this.itemFromTarget(event);const selection=item&&item.selectable?[item.id]:[];this.setSelection(selection);const newSelection=this.getSelection();// emit a select event,
// except when old selection is empty and new selection is still empty
if(newSelection.length>0||oldSelection.length>0){this.body.emitter.emit('select',{items:newSelection,event});}}/**
* Handle hovering an item
* @param {Event} event
* @private
*/_onMouseOver(event){const item=this.itemFromTarget(event);if(!item)return;// Item we just left
const related=this.itemFromRelatedTarget(event);if(item===related){// We haven't changed item, just element in the item
return;}const title=item.getTitle();if(this.options.showTooltips&&title){if(this.popup==null){this.popup=new Popup(this.body.dom.root,this.options.tooltip.overflowMethod||'flip');}this.popup.setText(title);const container=this.body.dom.centerContainer;const containerRect=container.getBoundingClientRect();this.popup.setPosition(event.clientX-containerRect.left+container.offsetLeft,event.clientY-containerRect.top+container.offsetTop);this.setPopupTimer(this.popup);}else {// Hovering over item without a title, hide popup
// Needed instead of _just_ in _onMouseOut due to #2572
this.clearPopupTimer();if(this.popup!=null){this.popup.hide();}}this.body.emitter.emit('itemover',{item:item.id,event});}/**
* on mouse start
* @param {Event} event
* @return {void}
* @private
*/_onMouseOut(event){const item=this.itemFromTarget(event);if(!item)return;// Item we are going to
const related=this.itemFromRelatedTarget(event);if(item===related){// We aren't changing item, just element in the item
return;}this.clearPopupTimer();if(this.popup!=null){this.popup.hide();}this.body.emitter.emit('itemout',{item:item.id,event});}/**
* on mouse move
* @param {Event} event
* @return {void}
* @private
*/_onMouseMove(event){const item=this.itemFromTarget(event);if(!item)return;if(this.popupTimer!=null){// restart timer
this.setPopupTimer(this.popup);}if(this.options.showTooltips&&this.options.tooltip.followMouse&&this.popup&&!this.popup.hidden){const container=this.body.dom.centerContainer;const containerRect=container.getBoundingClientRect();this.popup.setPosition(event.clientX-containerRect.left+container.offsetLeft,event.clientY-containerRect.top+container.offsetTop);this.popup.show();// Redraw
}}/**
* Handle mousewheel
* @param {Event} event The event
* @private
*/_onMouseWheel(event){if(this.touchParams.itemIsDragging){this._onDragEnd(event);}}/**
* Handle updates of an item on double tap
* @param {timeline.Item} item The item
* @private
*/_onUpdateItem(item){if(!this.options.selectable)return;if(!this.options.editable.updateTime&&!this.options.editable.updateGroup)return;const me=this;if(item){// execute async handler to update the item (or cancel it)
const itemData=me.itemsData.get(item.id);// get a clone of the data from the dataset
this.options.onUpdate(itemData,itemData=>{if(itemData){me.itemsData.update(itemData);}});}}/**
* Handle drop event of data on item
* Only called when `objectData.target === 'item'.
* @param {Event} event The event
* @private
*/_onDropObjectOnItem(event){const item=this.itemFromTarget(event);const objectData=JSON.parse(event.dataTransfer.getData("text"));this.options.onDropObjectOnItem(objectData,item);}/**
* Handle creation of an item on double tap or drop of a drag event
* @param {Event} event The event
* @private
*/_onAddItem(event){if(!this.options.selectable)return;if(!this.options.editable.add)return;const me=this;const snap=this.options.snap||null;// add item
const frameRect=this.dom.frame.getBoundingClientRect();const x=this.options.rtl?frameRect.right-event.center.x:event.center.x-frameRect.left;const start=this.body.util.toTime(x);const scale=this.body.util.getScale();const step=this.body.util.getStep();let end;let newItemData;if(event.type=='drop'){newItemData=JSON.parse(event.dataTransfer.getData("text"));newItemData.content=newItemData.content?newItemData.content:'new item';newItemData.start=newItemData.start?newItemData.start:snap?snap(start,scale,step):start;newItemData.type=newItemData.type||'box';newItemData[this.itemsData.idProp]=newItemData.id||v4();if(newItemData.type=='range'&&!newItemData.end){end=this.body.util.toTime(x+this.props.width/5);newItemData.end=snap?snap(end,scale,step):end;}}else {newItemData={start:snap?snap(start,scale,step):start,content:'new item'};newItemData[this.itemsData.idProp]=v4();// when default type is a range, add a default end date to the new item
if(this.options.type==='range'){end=this.body.util.toTime(x+this.props.width/5);newItemData.end=snap?snap(end,scale,step):end;}}const group=this.groupFromTarget(event);if(group){newItemData.group=group.groupId;}// execute async handler to customize (or cancel) adding an item
newItemData=this._cloneItemData(newItemData);// convert start and end to the correct type
this.options.onAdd(newItemData,item=>{if(item){me.itemsData.add(item);if(event.type=='drop'){me.setSelection([item.id]);}// TODO: need to trigger a redraw?
}});}/**
* Handle selecting/deselecting multiple items when holding an item
* @param {Event} event
* @private
*/_onMultiSelectItem(event){if(!this.options.selectable)return;const item=this.itemFromTarget(event);if(item){// multi select items (if allowed)
let selection=this.options.multiselect?this.getSelection()// take current selection
:[];// deselect current selection
const shiftKey=event.srcEvent&&event.srcEvent.shiftKey||false;if((shiftKey||this.options.sequentialSelection)&&this.options.multiselect){// select all items between the old selection and the tapped item
const itemGroup=this.itemsData.get(item.id).group;// when filtering get the group of the last selected item
let lastSelectedGroup=undefined;if(this.options.multiselectPerGroup){if(selection.length>0){lastSelectedGroup=this.itemsData.get(selection[0]).group;}}// determine the selection range
if(!this.options.multiselectPerGroup||lastSelectedGroup==undefined||lastSelectedGroup==itemGroup){selection.push(item.id);}const range=ItemSet._getItemRange(this.itemsData.get(selection));if(!this.options.multiselectPerGroup||lastSelectedGroup==itemGroup){// select all items within the selection range
selection=[];for(const id in this.items){if(this.items.hasOwnProperty(id)){const _item=this.items[id];const start=_item.data.start;const end=_item.data.end!==undefined?_item.data.end:start;if(start>=range.min&&end<=range.max&&(!this.options.multiselectPerGroup||lastSelectedGroup==this.itemsData.get(_item.id).group)&&!(_item instanceof BackgroundItem)){selection.push(_item.id);// do not use id but item.id, id itself is stringified
}}}}}else {// add/remove this item from the current selection
const index=selection.indexOf(item.id);if(index==-1){// item is not yet selected -> select it
selection.push(item.id);}else {// item is already selected -> deselect it
selection.splice(index,1);}}const filteredSelection=selection.filter(item=>this.getItemById(item).selectable);this.setSelection(filteredSelection);this.body.emitter.emit('select',{items:this.getSelection(),event});}}/**
* Calculate the time range of a list of items
* @param {Array.<Object>} itemsData
* @return {{min: Date, max: Date}} Returns the range of the provided items
* @private
*/static _getItemRange(itemsData){let max=null;let min=null;itemsData.forEach(data=>{if(min==null||data.start<min){min=data.start;}if(data.end!=undefined){if(max==null||data.end>max){max=data.end;}}else {if(max==null||data.start>max){max=data.start;}}});return {min,max};}/**
* Find an item from an element:
* searches for the attribute 'vis-item' in the element's tree
* @param {HTMLElement} element
* @return {Item | null} item
*/itemFromElement(element){let cur=element;while(cur){if(cur.hasOwnProperty('vis-item')){return cur['vis-item'];}cur=cur.parentNode;}return null;}/**
* Find an item from an event target:
* searches for the attribute 'vis-item' in the event target's element tree
* @param {Event} event
* @return {Item | null} item
*/itemFromTarget(event){return this.itemFromElement(event.target);}/**
* Find an item from an event's related target:
* searches for the attribute 'vis-item' in the related target's element tree
* @param {Event} event
* @return {Item | null} item
*/itemFromRelatedTarget(event){return this.itemFromElement(event.relatedTarget);}/**
* Find the Group from an event target:
* searches for the attribute 'vis-group' in the event target's element tree
* @param {Event} event
* @return {Group | null} group
*/groupFromTarget(event){const clientY=event.center?event.center.y:event.clientY;let groupIds=this.groupIds;if(groupIds.length<=0&&this.groupsData){groupIds=this.groupsData.getIds({order:this.options.groupOrder});}for(let i=0;i<groupIds.length;i++){const groupId=groupIds[i];const group=this.groups[groupId];const foreground=group.dom.foreground;const foregroundRect=foreground.getBoundingClientRect();if(clientY>=foregroundRect.top&&clientY<foregroundRect.top+foreground.offsetHeight){return group;}if(this.options.orientation.item==='top'){if(i===this.groupIds.length-1&&clientY>foregroundRect.top){return group;}}else {if(i===0&&clientY<foregroundRect.top+foreground.offset){return group;}}}return null;}/**
* Find the ItemSet from an event target:
* searches for the attribute 'vis-itemset' in the event target's element tree
* @param {Event} event
* @return {ItemSet | null} item
*/static itemSetFromTarget(event){let target=event.target;while(target){if(target.hasOwnProperty('vis-itemset')){return target['vis-itemset'];}target=target.parentNode;}return null;}/**
* Clone the data of an item, and "normalize" it: convert the start and end date
* to the type (Date, Moment, ...) configured in the DataSet. If not configured,
* start and end are converted to Date.
* @param {Object} itemData, typically `item.data`
* @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
* @return {Object} The cloned object
* @private
*/_cloneItemData(itemData,type){const clone=availableUtils.extend({},itemData);if(!type){// convert start and end date to the type (Date, Moment, ...) configured in the DataSet
type=this.itemsData.type;}if(clone.start!=undefined){clone.start=availableUtils.convert(clone.start,type&&type.start||'Date');}if(clone.end!=undefined){clone.end=availableUtils.convert(clone.end,type&&type.end||'Date');}return clone;}/**
* cluster items
* @return {void}
* @private
*/_clusterItems(){if(!this.options.cluster){return;}const{scale}=this.body.range.conversion(this.body.domProps.center.width);const clusters=this.clusterGenerator.getClusters(this.clusters,scale,this.options.cluster);if(this.clusters!=clusters){this._detachAllClusters();if(clusters){for(let cluster of clusters){cluster.attach();}this.clusters=clusters;}this._updateClusters(clusters);}}/**
* detach all cluster items
* @private
*/_detachAllClusters(){if(this.options.cluster){if(this.clusters&&this.clusters.length){for(let cluster of this.clusters){cluster.detach();}}}}/**
* update clusters
* @param {array} clusters
* @private
*/_updateClusters(clusters){if(this.clusters&&this.clusters.length){const newClustersIds=new Set(clusters.map(cluster=>cluster.id));const clustersToUnselect=this.clusters.filter(cluster=>!newClustersIds.has(cluster.id));let selectionChanged=false;for(let cluster of clustersToUnselect){const selectedIdx=this.selection.indexOf(cluster.id);if(selectedIdx!==-1){cluster.unselect();this.selection.splice(selectedIdx,1);selectionChanged=true;}}if(selectionChanged){const newSelection=this.getSelection();this.body.emitter.emit('select',{items:newSelection,event:event});}}this.clusters=clusters||[];}}// available item types will be registered here
ItemSet.types={background:BackgroundItem,box:BoxItem,range:RangeItem,point:PointItem};/**
* Handle added items
* @param {number[]} ids
* @protected
*/ItemSet.prototype._onAdd=ItemSet.prototype._onUpdate;let errorFound=false;let allOptions$2;let printStyle='background: #FFeeee; color: #dd0000';/**
* Used to validate options.
*/class Validator{/**
* @ignore
*/constructor(){}/**
* Main function to be called
* @param {Object} options
* @param {Object} referenceOptions
* @param {Object} subObject
* @returns {boolean}
* @static
*/static validate(options,referenceOptions,subObject){errorFound=false;allOptions$2=referenceOptions;let usedOptions=referenceOptions;if(subObject!==undefined){usedOptions=referenceOptions[subObject];}Validator.parse(options,usedOptions,[]);return errorFound;}/**
* Will traverse an object recursively and check every value
* @param {Object} options
* @param {Object} referenceOptions
* @param {array} path | where to look for the actual option
* @static
*/static parse(options,referenceOptions,path){for(let option in options){if(options.hasOwnProperty(option)){Validator.check(option,options,referenceOptions,path);}}}/**
* Check every value. If the value is an object, call the parse function on that object.
* @param {string} option
* @param {Object} options
* @param {Object} referenceOptions
* @param {array} path | where to look for the actual option
* @static
*/static check(option,options,referenceOptions,path){if(referenceOptions[option]===undefined&&referenceOptions.__any__===undefined){Validator.getSuggestion(option,referenceOptions,path);return;}let referenceOption=option;let is_object=true;if(referenceOptions[option]===undefined&&referenceOptions.__any__!==undefined){// NOTE: This only triggers if the __any__ is in the top level of the options object.
// THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
// TODO: Examine if needed, remove if possible
// __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
referenceOption='__any__';// if the any-subgroup is not a predefined object in the configurator,
// we do not look deeper into the object.
is_object=Validator.getType(options[option])==='object';}let refOptionObj=referenceOptions[referenceOption];if(is_object&&refOptionObj.__type__!==undefined){refOptionObj=refOptionObj.__type__;}Validator.checkFields(option,options,referenceOptions,referenceOption,refOptionObj,path);}/**
*
* @param {string} option | the option property
* @param {Object} options | The supplied options object
* @param {Object} referenceOptions | The reference options containing all options and their allowed formats
* @param {string} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
* @param {string} refOptionObj | This is the type object from the reference options
* @param {Array} path | where in the object is the option
* @static
*/static checkFields(option,options,referenceOptions,referenceOption,refOptionObj,path){let log=function(message){console.log('%c'+message+Validator.printLocation(path,option),printStyle);};let optionType=Validator.getType(options[option]);let refOptionType=refOptionObj[optionType];if(refOptionType!==undefined){// if the type is correct, we check if it is supposed to be one of a few select values
if(Validator.getType(refOptionType)==='array'&&refOptionType.indexOf(options[option])===-1){log('Invalid option detected in "'+option+'".'+' Allowed values are:'+Validator.print(refOptionType)+' not "'+options[option]+'". ');errorFound=true;}else if(optionType==='object'&&referenceOption!=="__any__"){path=availableUtils.copyAndExtendArray(path,option);Validator.parse(options[option],referenceOptions[referenceOption],path);}}else if(refOptionObj['any']===undefined){// type of the field is incorrect and the field cannot be any
log('Invalid type received for "'+option+'". Expected: '+Validator.print(Object.keys(refOptionObj))+'. Received ['+optionType+'] "'+options[option]+'"');errorFound=true;}}/**
*
* @param {Object|boolean|number|string|Array.<number>|Date|Node|Moment|undefined|null} object
* @returns {string}
* @static
*/static getType(object){var type=typeof object;if(type==='object'){if(object===null){return 'null';}if(object instanceof Boolean){return 'boolean';}if(object instanceof Number){return 'number';}if(object instanceof String){return 'string';}if(Array.isArray(object)){return 'array';}if(object instanceof Date){return 'date';}if(object.nodeType!==undefined){return 'dom';}if(object._isAMomentObject===true){return 'moment';}return 'object';}else if(type==='number'){return 'number';}else if(type==='boolean'){return 'boolean';}else if(type==='string'){return 'string';}else if(type===undefined){return 'undefined';}return type;}/**
* @param {string} option
* @param {Object} options
* @param {Array.<string>} path
* @static
*/static getSuggestion(option,options,path){let localSearch=Validator.findInOptions(option,options,path,false);let globalSearch=Validator.findInOptions(option,allOptions$2,[],true);let localSearchThreshold=8;let globalSearchThreshold=4;let msg;if(localSearch.indexMatch!==undefined){msg=' in '+Validator.printLocation(localSearch.path,option,'')+'Perhaps it was incomplete? Did you mean: "'+localSearch.indexMatch+'"?\n\n';}else if(globalSearch.distance<=globalSearchThreshold&&localSearch.distance>globalSearch.distance){msg=' in '+Validator.printLocation(localSearch.path,option,'')+'Perhaps it was misplaced? Matching option found at: '+Validator.printLocation(globalSearch.path,globalSearch.closestMatch,'');}else if(localSearch.distance<=localSearchThreshold){msg='. Did you mean "'+localSearch.closestMatch+'"?'+Validator.printLocation(localSearch.path,option);}else {msg='. Did you mean one of these: '+Validator.print(Object.keys(options))+Validator.printLocation(path,option);}console.log('%cUnknown option detected: "'+option+'"'+msg,printStyle);errorFound=true;}/**
* traverse the options in search for a match.
* @param {string} option
* @param {Object} options
* @param {Array} path | where to look for the actual option
* @param {boolean} [recursive=false]
* @returns {{closestMatch: string, path: Array, distance: number}}
* @static
*/static findInOptions(option,options,path,recursive=false){let min=1e9;let closestMatch='';let closestMatchPath=[];let lowerCaseOption=option.toLowerCase();let indexMatch=undefined;for(let op in options){// eslint-disable-line guard-for-in
let distance;if(options[op].__type__!==undefined&&recursive===true){let result=Validator.findInOptions(option,options[op],availableUtils.copyAndExtendArray(path,op));if(min>result.distance){closestMatch=result.closestMatch;closestMatchPath=result.path;min=result.distance;indexMatch=result.indexMatch;}}else {if(op.toLowerCase().indexOf(lowerCaseOption)!==-1){indexMatch=op;}distance=Validator.levenshteinDistance(option,op);if(min>distance){closestMatch=op;closestMatchPath=availableUtils.copyArray(path);min=distance;}}}return {closestMatch:closestMatch,path:closestMatchPath,distance:min,indexMatch:indexMatch};}/**
* @param {Array.<string>} path
* @param {Object} option
* @param {string} prefix
* @returns {String}
* @static
*/static printLocation(path,option,prefix='Problem value found at: \n'){let str='\n\n'+prefix+'options = {\n';for(let i=0;i<path.length;i++){for(let j=0;j<i+1;j++){str+=' ';}str+=path[i]+': {\n';}for(let j=0;j<path.length+1;j++){str+=' ';}str+=option+'\n';for(let i=0;i<path.length+1;i++){for(let j=0;j<path.length-i;j++){str+=' ';}str+='}\n';}return str+'\n\n';}/**
* @param {Object} options
* @returns {String}
* @static
*/static print(options){return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g,"").replace(/(\,)/g,', ');}/**
* Compute the edit distance between the two given strings
* http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
*
* Copyright (c) 2011 Andrei Mackenzie
*
* 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.
*
* @param {string} a
* @param {string} b
* @returns {Array.<Array.<number>>}}
* @static
*/static levenshteinDistance(a,b){if(a.length===0)return b.length;if(b.length===0)return a.length;var matrix=[];// increment along the first column of each row
var i;for(i=0;i<=b.length;i++){matrix[i]=[i];}// increment each column in the first row
var j;for(j=0;j<=a.length;j++){matrix[0][j]=j;}// Fill in the rest of the matrix
for(i=1;i<=b.length;i++){for(j=1;j<=a.length;j++){if(b.charAt(i-1)==a.charAt(j-1)){matrix[i][j]=matrix[i-1][j-1];}else {matrix[i][j]=Math.min(matrix[i-1][j-1]+1,// substitution
Math.min(matrix[i][j-1]+1,// insertion
matrix[i-1][j]+1));// deletion
}}}return matrix[b.length][a.length];}}/**
* This object contains all possible options. It will check if the types are correct, if required if the option is one
* of the allowed values.
*
* __any__ means that the name of the property does not matter.
* __type__ is a required field for all objects and contains the allowed types of all objects
*/let string$1='string';let bool$1='boolean';let number$1='number';let array$1='array';let date$1='date';let object$1='object';// should only be in a __type__ property
let dom$1='dom';let moment$1='moment';let any$1='any';let allOptions$1={configure:{enabled:{'boolean':bool$1},filter:{'boolean':bool$1,'function':'function'},container:{dom:dom$1},__type__:{object:object$1,'boolean':bool$1,'function':'function'}},//globals :
align:{string:string$1},alignCurrentTime:{string:string$1,'undefined':'undefined'},rtl:{'boolean':bool$1,'undefined':'undefined'},rollingMode:{follow:{'boolean':bool$1},offset:{number:number$1,'undefined':'undefined'},__type__:{object:object$1}},onTimeout:{timeoutMs:{number:number$1},callback:{'function':'function'},__type__:{object:object$1}},verticalScroll:{'boolean':bool$1,'undefined':'undefined'},horizontalScroll:{'boolean':bool$1,'undefined':'undefined'},autoResize:{'boolean':bool$1},throttleRedraw:{number:number$1},// TODO: DEPRICATED see https://github.com/almende/vis/issues/2511
clickToUse:{'boolean':bool$1},dataAttributes:{string:string$1,array:array$1},editable:{add:{'boolean':bool$1,'undefined':'undefined'},remove:{'boolean':bool$1,'undefined':'undefined'},updateGroup:{'boolean':bool$1,'undefined':'undefined'},updateTime:{'boolean':bool$1,'undefined':'undefined'},overrideItems:{'boolean':bool$1,'undefined':'undefined'},__type__:{'boolean':bool$1,object:object$1}},end:{number:number$1,date:date$1,string:string$1,moment:moment$1},format:{minorLabels:{millisecond:{string:string$1,'undefined':'undefined'},second:{string:string$1,'undefined':'undefined'},minute:{string:string$1,'undefined':'undefined'},hour:{string:string$1,'undefined':'undefined'},weekday:{string:string$1,'undefined':'undefined'},day:{string:string$1,'undefined':'undefined'},week:{string:string$1,'undefined':'undefined'},month:{string:string$1,'undefined':'undefined'},year:{string:string$1,'undefined':'undefined'},__type__:{object:object$1,'function':'function'}},majorLabels:{millisecond:{string:string$1,'undefined':'undefined'},second:{string:string$1,'undefined':'undefined'},minute:{string:string$1,'undefined':'undefined'},hour:{string:string$1,'undefined':'undefined'},weekday:{string:string$1,'undefined':'undefined'},day:{string:string$1,'undefined':'undefined'},week:{string:string$1,'undefined':'undefined'},month:{string:string$1,'undefined':'undefined'},year:{string:string$1,'undefined':'undefined'},__type__:{object:object$1,'function':'function'}},__type__:{object:object$1}},moment:{'function':'function'},groupHeightMode:{string:string$1},groupOrder:{string:string$1,'function':'function'},groupEditable:{add:{'boolean':bool$1,'undefined':'undefined'},remove:{'boolean':bool$1,'undefined':'undefined'},order:{'boolean':bool$1,'undefined':'undefined'},__type__:{'boolean':bool$1,object:object$1}},groupOrderSwap:{'function':'function'},height:{string:string$1,number:number$1},hiddenDates:{start:{date:date$1,number:number$1,string:string$1,moment:moment$1},end:{date:date$1,number:number$1,string:string$1,moment:moment$1},repeat:{string:string$1},__type__:{object:object$1,array:array$1}},itemsAlwaysDraggable:{item:{'boolean':bool$1,'undefined':'undefined'},range:{'boolean':bool$1,'undefined':'undefined'},__type__:{'boolean':bool$1,object:object$1}},limitSize:{'boolean':bool$1},locale:{string:string$1},locales:{__any__:{any:any$1},__type__:{object:object$1}},longSelectPressTime:{number:number$1},margin:{axis:{number:number$1},item:{horizontal:{number:number$1,'undefined':'undefined'},vertical:{number:number$1,'undefined':'undefined'},__type__:{object:object$1,number:number$1}},__type__:{object:object$1,number:number$1}},max:{date:date$1,number:number$1,string:string$1,moment:moment$1},maxHeight:{number:number$1,string:string$1},maxMinorChars:{number:number$1},min:{date:date$1,number:number$1,string:string$1,moment:moment$1},minHeight:{number:number$1,string:string$1},moveable:{'boolean':bool$1},multiselect:{'boolean':bool$1},multiselectPerGroup:{'boolean':bool$1},onAdd:{'function':'function'},onDropObjectOnItem:{'function':'function'},onUpdate:{'function':'function'},onMove:{'function':'function'},onMoving:{'function':'function'},onRemove:{'function':'function'},onAddGroup:{'function':'function'},onMoveGroup:{'function':'function'},onRemoveGroup:{'function':'function'},onInitialDrawComplete:{'function':'function'},order:{'function':'function'},orientation:{axis:{string:string$1,'undefined':'undefined'},item:{string:string$1,'undefined':'undefined'},__type__:{string:string$1,object:object$1}},selectable:{'boolean':bool$1},sequentialSelection:{'boolean':bool$1},showCurrentTime:{'boolean':bool$1},showMajorLabels:{'boolean':bool$1},showMinorLabels:{'boolean':bool$1},showWeekScale:{'boolean':bool$1},stack:{'boolean':bool$1},stackSubgroups:{'boolean':bool$1},cluster:{maxItems:{'number':number$1,'undefined':'undefined'},titleTemplate:{'string':string$1,'undefined':'undefined'},clusterCriteria:{'function':'function','undefined':'undefined'},showStipes:{'boolean':bool$1,'undefined':'undefined'},fitOnDoubleClick:{'boolean':bool$1,'undefined':'undefined'},__type__:{'boolean':bool$1,object:object$1}},snap:{'function':'function','null':'null'},start:{date:date$1,number:number$1,string:string$1,moment:moment$1},template:{'function':'function'},loadingScreenTemplate:{'function':'function'},groupTemplate:{'function':'function'},visibleFrameTemplate:{string:string$1,'function':'function'},showTooltips:{'boolean':bool$1},tooltip:{followMouse:{'boolean':bool$1},overflowMethod:{'string':['cap','flip','none']},delay:{number:number$1},template:{'function':'function'},__type__:{object:object$1}},tooltipOnItemUpdateTime:{template:{'function':'function'},__type__:{'boolean':bool$1,object:object$1}},timeAxis:{scale:{string:string$1,'undefined':'undefined'},step:{number:number$1,'undefined':'undefined'},__type__:{object:object$1}},type:{string:string$1},width:{string:string$1,number:number$1},preferZoom:{'boolean':bool$1},zoomable:{'boolean':bool$1},zoomKey:{string:['ctrlKey','altKey','shiftKey','metaKey','']},zoomFriction:{number:number$1},zoomMax:{number:number$1},zoomMin:{number:number$1},xss:{disabled:{boolean:bool$1},filterOptions:{__any__:{any:any$1},__type__:{object:object$1}},__type__:{object:object$1}},__type__:{object:object$1}};let configureOptions$1={global:{align:['center','left','right'],alignCurrentTime:['none','year','month','quarter','week','isoWeek','day','date','hour','minute','second'],direction:false,autoResize:true,clickToUse:false,// dataAttributes: ['all'], // FIXME: can be 'all' or string[]
editable:{add:false,remove:false,updateGroup:false,updateTime:false},end:'',format:{minorLabels:{millisecond:'SSS',second:'s',minute:'HH:mm',hour:'HH:mm',weekday:'ddd D',day:'D',week:'w',month:'MMM',year:'YYYY'},majorLabels:{millisecond:'HH:mm:ss',second:'D MMMM HH:mm',minute:'ddd D MMMM',hour:'ddd D MMMM',weekday:'MMMM YYYY',day:'MMMM YYYY',week:'MMMM YYYY',month:'YYYY',year:''}},groupHeightMode:['auto','fixed','fitItems'],//groupOrder: {string, 'function': 'function'},
groupsDraggable:false,height:'',//hiddenDates: {object, array},
locale:'',longSelectPressTime:251,margin:{axis:[20,0,100,1],item:{horizontal:[10,0,100,1],vertical:[10,0,100,1]}},max:'',maxHeight:'',maxMinorChars:[7,0,20,1],min:'',minHeight:'',moveable:false,multiselect:false,multiselectPerGroup:false,//onAdd: {'function': 'function'},
//onUpdate: {'function': 'function'},
//onMove: {'function': 'function'},
//onMoving: {'function': 'function'},
//onRename: {'function': 'function'},
//order: {'function': 'function'},
orientation:{axis:['both','bottom','top'],item:['bottom','top']},preferZoom:false,selectable:true,showCurrentTime:false,showMajorLabels:true,showMinorLabels:true,stack:true,stackSubgroups:true,cluster:false,//snap: {'function': 'function', nada},
start:'',//template: {'function': 'function'},
//timeAxis: {
// scale: ['millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'],
// step: [1, 1, 10, 1]
//},
showTooltips:true,tooltip:{followMouse:false,overflowMethod:'flip',delay:[500,0,99999,100]},tooltipOnItemUpdateTime:false,type:['box','point','range','background'],width:'100%',zoomable:true,zoomKey:['ctrlKey','altKey','shiftKey','metaKey',''],zoomMax:[315360000000000,10,315360000000000,1],zoomMin:[10,10,315360000000000,1],xss:{disabled:false}}};var htmlColors={black:'#000000',navy:'#000080',darkblue:'#00008B',mediumblue:'#0000CD',blue:'#0000FF',darkgreen:'#006400',green:'#008000',teal:'#008080',darkcyan:'#008B8B',deepskyblue:'#00BFFF',darkturquoise:'#00CED1',mediumspringgreen:'#00FA9A',lime:'#00FF00',springgreen:'#00FF7F',aqua:'#00FFFF',cyan:'#00FFFF',midnightblue:'#191970',dodgerblue:'#1E90FF',lightseagreen:'#20B2AA',forestgreen:'#228B22',seagreen:'#2E8B57',darkslategray:'#2F4F4F',limegreen:'#32CD32',mediumseagreen:'#3CB371',turquoise:'#40E0D0',royalblue:'#4169E1',steelblue:'#4682B4',darkslateblue:'#483D8B',mediumturquoise:'#48D1CC',indigo:'#4B0082',darkolivegreen:'#556B2F',cadetblue:'#5F9EA0',cornflowerblue:'#6495ED',mediumaquamarine:'#66CDAA',dimgray:'#696969',slateblue:'#6A5ACD',olivedrab:'#6B8E23',slategray:'#708090',lightslategray:'#778899',mediumslateblue:'#7B68EE',lawngreen:'#7CFC00',chartreuse:'#7FFF00',aquamarine:'#7FFFD4',maroon:'#800000',purple:'#800080',olive:'#808000',gray:'#808080',skyblue:'#87CEEB',lightskyblue:'#87CEFA',blueviolet:'#8A2BE2',darkred:'#8B0000',darkmagenta:'#8B008B',saddlebrown:'#8B4513',darkseagreen:'#8FBC8F',lightgreen:'#90EE90',mediumpurple:'#9370D8',darkviolet:'#9400D3',palegreen:'#98FB98',darkorchid:'#9932CC',yellowgreen:'#9ACD32',sienna:'#A0522D',brown:'#A52A2A',darkgray:'#A9A9A9',lightblue:'#ADD8E6',greenyellow:'#ADFF2F',paleturquoise:'#AFEEEE',lightsteelblue:'#B0C4DE',powderblue:'#B0E0E6',firebrick:'#B22222',darkgoldenrod:'#B8860B',mediumorchid:'#BA55D3',rosybrown:'#BC8F8F',darkkhaki:'#BDB76B',silver:'#C0C0C0',mediumvioletred:'#C71585',indianred:'#CD5C5C',peru:'#CD853F',chocolate:'#D2691E',tan:'#D2B48C',lightgrey:'#D3D3D3',palevioletred:'#D87093',thistle:'#D8BFD8',orchid:'#DA70D6',goldenrod:'#DAA520',crimson:'#DC143C',gainsboro:'#DCDCDC',plum:'#DDA0DD',burlywood:'#DEB887',lightcyan:'#E0FFFF',lavender:'#E6E6FA',darksalmon:'#E9967A',violet:'#EE82EE',palegoldenrod:'#EEE8AA',lightcoral:'#F08080',khaki:'#F0E68C',aliceblue:'#F0F8FF',honeydew:'#F0FFF0',azure:'#F0FFFF',sandybrown:'#F4A460',wheat:'#F5DEB3',beige:'#F5F5DC',whitesmoke:'#F5F5F5',mintcream:'#F5FFFA',ghostwhite:'#F8F8FF',salmon:'#FA8072',antiquewhite:'#FAEBD7',linen:'#FAF0E6',lightgoldenrodyellow:'#FAFAD2',oldlace:'#FDF5E6',red:'#FF0000',fuchsia:'#FF00FF',magenta:'#FF00FF',deeppink:'#FF1493',orangered:'#FF4500',tomato:'#FF6347',hotpink:'#FF69B4',coral:'#FF7F50',darkorange:'#FF8C00',lightsalmon:'#FFA07A',orange:'#FFA500',lightpink:'#FFB6C1',pink:'#FFC0CB',gold:'#FFD700',peachpuff:'#FFDAB9',navajowhite:'#FFDEAD',moccasin:'#FFE4B5',bisque:'#FFE4C4',mistyrose:'#FFE4E1',blanchedalmond:'#FFEBCD',papayawhip:'#FFEFD5',lavenderblush:'#FFF0F5',seashell:'#FFF5EE',cornsilk:'#FFF8DC',lemonchiffon:'#FFFACD',floralwhite:'#FFFAF0',snow:'#FFFAFA',yellow:'#FFFF00',lightyellow:'#FFFFE0',ivory:'#FFFFF0',white:'#FFFFFF'};/**
* @param {number} [pixelRatio=1]
*/class ColorPicker{/**
* @param {number} [pixelRatio=1]
*/constructor(pixelRatio=1){this.pixelRatio=pixelRatio;this.generated=false;this.centerCoordinates={x:289/2,y:289/2};this.r=289*0.49;this.color={r:255,g:255,b:255,a:1.0};this.hueCircle=undefined;this.initialColor={r:255,g:255,b:255,a:1.0};this.previousColor=undefined;this.applied=false;// bound by
this.updateCallback=()=>{};this.closeCallback=()=>{};// create all DOM elements
this._create();}/**
* this inserts the colorPicker into a div from the DOM
* @param {Element} container
*/insertTo(container){if(this.hammer!==undefined){this.hammer.destroy();this.hammer=undefined;}this.container=container;this.container.appendChild(this.frame);this._bindHammer();this._setSize();}/**
* the callback is executed on apply and save. Bind it to the application
* @param {function} callback
*/setUpdateCallback(callback){if(typeof callback==='function'){this.updateCallback=callback;}else {throw new Error("Function attempted to set as colorPicker update callback is not a function.");}}/**
* the callback is executed on apply and save. Bind it to the application
* @param {function} callback
*/setCloseCallback(callback){if(typeof callback==='function'){this.closeCallback=callback;}else {throw new Error("Function attempted to set as colorPicker closing callback is not a function.");}}/**
*
* @param {string} color
* @returns {String}
* @private
*/_isColorString(color){if(typeof color==='string'){return htmlColors[color];}}/**
* Set the color of the colorPicker
* Supported formats:
* 'red' --> HTML color string
* '#ffffff' --> hex string
* 'rgb(255,255,255)' --> rgb string
* 'rgba(255,255,255,1.0)' --> rgba string
* {r:255,g:255,b:255} --> rgb object
* {r:255,g:255,b:255,a:1.0} --> rgba object
* @param {string|Object} color
* @param {boolean} [setInitial=true]
*/setColor(color,setInitial=true){if(color==='none'){return;}let rgba;// if a html color shorthand is used, convert to hex
var htmlColor=this._isColorString(color);if(htmlColor!==undefined){color=htmlColor;}// check format
if(availableUtils.isString(color)===true){if(availableUtils.isValidRGB(color)===true){let rgbaArray=color.substr(4).substr(0,color.length-5).split(',');rgba={r:rgbaArray[0],g:rgbaArray[1],b:rgbaArray[2],a:1.0};}else if(availableUtils.isValidRGBA(color)===true){let rgbaArray=color.substr(5).substr(0,color.length-6).split(',');rgba={r:rgbaArray[0],g:rgbaArray[1],b:rgbaArray[2],a:rgbaArray[3]};}else if(availableUtils.isValidHex(color)===true){let rgbObj=availableUtils.hexToRGB(color);rgba={r:rgbObj.r,g:rgbObj.g,b:rgbObj.b,a:1.0};}}else {if(color instanceof Object){if(color.r!==undefined&&color.g!==undefined&&color.b!==undefined){let alpha=color.a!==undefined?color.a:'1.0';rgba={r:color.r,g:color.g,b:color.b,a:alpha};}}}// set color
if(rgba===undefined){throw new Error("Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: "+JSON.stringify(color));}else {this._setColor(rgba,setInitial);}}/**
* this shows the color picker.
* The hue circle is constructed once and stored.
*/show(){if(this.closeCallback!==undefined){this.closeCallback();this.closeCallback=undefined;}this.applied=false;this.frame.style.display='block';this._generateHueCircle();}// ------------------------------------------ PRIVATE ----------------------------- //
/**
* Hide the picker. Is called by the cancel button.
* Optional boolean to store the previous color for easy access later on.
* @param {boolean} [storePrevious=true]
* @private
*/_hide(storePrevious=true){// store the previous color for next time;
if(storePrevious===true){this.previousColor=availableUtils.extend({},this.color);}if(this.applied===true){this.updateCallback(this.initialColor);}this.frame.style.display='none';// call the closing callback, restoring the onclick method.
// this is in a setTimeout because it will trigger the show again before the click is done.
setTimeout(()=>{if(this.closeCallback!==undefined){this.closeCallback();this.closeCallback=undefined;}},0);}/**
* bound to the save button. Saves and hides.
* @private
*/_save(){this.updateCallback(this.color);this.applied=false;this._hide();}/**
* Bound to apply button. Saves but does not close. Is undone by the cancel button.
* @private
*/_apply(){this.applied=true;this.updateCallback(this.color);this._updatePicker(this.color);}/**
* load the color from the previous session.
* @private
*/_loadLast(){if(this.previousColor!==undefined){this.setColor(this.previousColor,false);}else {alert("There is no last color to load...");}}/**
* set the color, place the picker
* @param {Object} rgba
* @param {boolean} [setInitial=true]
* @private
*/_setColor(rgba,setInitial=true){// store the initial color
if(setInitial===true){this.initialColor=availableUtils.extend({},rgba);}this.color=rgba;let hsv=availableUtils.RGBToHSV(rgba.r,rgba.g,rgba.b);let angleConvert=2*Math.PI;let radius=this.r*hsv.s;let x=this.centerCoordinates.x+radius*Math.sin(angleConvert*hsv.h);let y=this.centerCoordinates.y+radius*Math.cos(angleConvert*hsv.h);this.colorPickerSelector.style.left=x-0.5*this.colorPickerSelector.clientWidth+'px';this.colorPickerSelector.style.top=y-0.5*this.colorPickerSelector.clientHeight+'px';this._updatePicker(rgba);}/**
* bound to opacity control
* @param {number} value
* @private
*/_setOpacity(value){this.color.a=value/100;this._updatePicker(this.color);}/**
* bound to brightness control
* @param {number} value
* @private
*/_setBrightness(value){let hsv=availableUtils.RGBToHSV(this.color.r,this.color.g,this.color.b);hsv.v=value/100;let rgba=availableUtils.HSVToRGB(hsv.h,hsv.s,hsv.v);rgba['a']=this.color.a;this.color=rgba;this._updatePicker();}/**
* update the color picker. A black circle overlays the hue circle to mimic the brightness decreasing.
* @param {Object} rgba
* @private
*/_updatePicker(rgba=this.color){let hsv=availableUtils.RGBToHSV(rgba.r,rgba.g,rgba.b);let ctx=this.colorPickerCanvas.getContext('2d');if(this.pixelRation===undefined){this.pixelRatio=(window.devicePixelRatio||1)/(ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1);}ctx.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);// clear the canvas
let w=this.colorPickerCanvas.clientWidth;let h=this.colorPickerCanvas.clientHeight;ctx.clearRect(0,0,w,h);ctx.putImageData(this.hueCircle,0,0);ctx.fillStyle='rgba(0,0,0,'+(1-hsv.v)+')';ctx.circle(this.centerCoordinates.x,this.centerCoordinates.y,this.r);ctx.fill();this.brightnessRange.value=100*hsv.v;this.opacityRange.value=100*rgba.a;this.initialColorDiv.style.backgroundColor='rgba('+this.initialColor.r+','+this.initialColor.g+','+this.initialColor.b+','+this.initialColor.a+')';this.newColorDiv.style.backgroundColor='rgba('+this.color.r+','+this.color.g+','+this.color.b+','+this.color.a+')';}/**
* used by create to set the size of the canvas.
* @private
*/_setSize(){this.colorPickerCanvas.style.width='100%';this.colorPickerCanvas.style.height='100%';this.colorPickerCanvas.width=289*this.pixelRatio;this.colorPickerCanvas.height=289*this.pixelRatio;}/**
* create all dom elements
* TODO: cleanup, lots of similar dom elements
* @private
*/_create(){this.frame=document.createElement('div');this.frame.className='vis-color-picker';this.colorPickerDiv=document.createElement('div');this.colorPickerSelector=document.createElement('div');this.colorPickerSelector.className='vis-selector';this.colorPickerDiv.appendChild(this.colorPickerSelector);this.colorPickerCanvas=document.createElement('canvas');this.colorPickerDiv.appendChild(this.colorPickerCanvas);if(!this.colorPickerCanvas.getContext){let noCanvas=document.createElement('DIV');noCanvas.style.color='red';noCanvas.style.fontWeight='bold';noCanvas.style.padding='10px';noCanvas.innerHTML='Error: your browser does not support HTML canvas';this.colorPickerCanvas.appendChild(noCanvas);}else {let ctx=this.colorPickerCanvas.getContext("2d");this.pixelRatio=(window.devicePixelRatio||1)/(ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1);this.colorPickerCanvas.getContext("2d").setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);}this.colorPickerDiv.className='vis-color';this.opacityDiv=document.createElement('div');this.opacityDiv.className='vis-opacity';this.brightnessDiv=document.createElement('div');this.brightnessDiv.className='vis-brightness';this.arrowDiv=document.createElement('div');this.arrowDiv.className='vis-arrow';this.opacityRange=document.createElement('input');try{this.opacityRange.type='range';// Not supported on IE9
this.opacityRange.min='0';this.opacityRange.max='100';}// TODO: Add some error handling and remove this lint exception
catch(err){}// eslint-disable-line no-empty
this.opacityRange.value='100';this.opacityRange.className='vis-range';this.brightnessRange=document.createElement('input');try{this.brightnessRange.type='range';// Not supported on IE9
this.brightnessRange.min='0';this.brightnessRange.max='100';}// TODO: Add some error handling and remove this lint exception
catch(err){}// eslint-disable-line no-empty
this.brightnessRange.value='100';this.brightnessRange.className='vis-range';this.opacityDiv.appendChild(this.opacityRange);this.brightnessDiv.appendChild(this.brightnessRange);var me=this;this.opacityRange.onchange=function(){me._setOpacity(this.value);};this.opacityRange.oninput=function(){me._setOpacity(this.value);};this.brightnessRange.onchange=function(){me._setBrightness(this.value);};this.brightnessRange.oninput=function(){me._setBrightness(this.value);};this.brightnessLabel=document.createElement("div");this.brightnessLabel.className="vis-label vis-brightness";this.brightnessLabel.innerHTML='brightness:';this.opacityLabel=document.createElement("div");this.opacityLabel.className="vis-label vis-opacity";this.opacityLabel.innerHTML='opacity:';this.newColorDiv=document.createElement("div");this.newColorDiv.className="vis-new-color";this.newColorDiv.innerHTML='new';this.initialColorDiv=document.createElement("div");this.initialColorDiv.className="vis-initial-color";this.initialColorDiv.innerHTML='initial';this.cancelButton=document.createElement("div");this.cancelButton.className="vis-button vis-cancel";this.cancelButton.innerHTML='cancel';this.cancelButton.onclick=this._hide.bind(this,false);this.applyButton=document.createElement("div");this.applyButton.className="vis-button vis-apply";this.applyButton.innerHTML='apply';this.applyButton.onclick=this._apply.bind(this);this.saveButton=document.createElement("div");this.saveButton.className="vis-button vis-save";this.saveButton.innerHTML='save';this.saveButton.onclick=this._save.bind(this);this.loadButton=document.createElement("div");this.loadButton.className="vis-button vis-load";this.loadButton.innerHTML='load last';this.loadButton.onclick=this._loadLast.bind(this);this.frame.appendChild(this.colorPickerDiv);this.frame.appendChild(this.arrowDiv);this.frame.appendChild(this.brightnessLabel);this.frame.appendChild(this.brightnessDiv);this.frame.appendChild(this.opacityLabel);this.frame.appendChild(this.opacityDiv);this.frame.appendChild(this.newColorDiv);this.frame.appendChild(this.initialColorDiv);this.frame.appendChild(this.cancelButton);this.frame.appendChild(this.applyButton);this.frame.appendChild(this.saveButton);this.frame.appendChild(this.loadButton);}/**
* bind hammer to the color picker
* @private
*/_bindHammer(){this.drag={};this.pinch={};this.hammer=new Hammer(this.colorPickerCanvas);this.hammer.get('pinch').set({enable:true});onTouch$1(this.hammer,event=>{this._moveSelector(event);});this.hammer.on('tap',event=>{this._moveSelector(event);});this.hammer.on('panstart',event=>{this._moveSelector(event);});this.hammer.on('panmove',event=>{this._moveSelector(event);});this.hammer.on('panend',event=>{this._moveSelector(event);});}/**
* generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
* @private
*/_generateHueCircle(){if(this.generated===false){let ctx=this.colorPickerCanvas.getContext('2d');if(this.pixelRation===undefined){this.pixelRatio=(window.devicePixelRatio||1)/(ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1);}ctx.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);// clear the canvas
let w=this.colorPickerCanvas.clientWidth;let h=this.colorPickerCanvas.clientHeight;ctx.clearRect(0,0,w,h);// draw hue circle
let x,y,hue,sat;this.centerCoordinates={x:w*0.5,y:h*0.5};this.r=0.49*w;let angleConvert=2*Math.PI/360;let hfac=1/360;let sfac=1/this.r;let rgb;for(hue=0;hue<360;hue++){for(sat=0;sat<this.r;sat++){x=this.centerCoordinates.x+sat*Math.sin(angleConvert*hue);y=this.centerCoordinates.y+sat*Math.cos(angleConvert*hue);rgb=availableUtils.HSVToRGB(hue*hfac,sat*sfac,1);ctx.fillStyle='rgb('+rgb.r+','+rgb.g+','+rgb.b+')';ctx.fillRect(x-0.5,y-0.5,2,2);}}ctx.strokeStyle='rgba(0,0,0,1)';ctx.circle(this.centerCoordinates.x,this.centerCoordinates.y,this.r);ctx.stroke();this.hueCircle=ctx.getImageData(0,0,w,h);}this.generated=true;}/**
* move the selector. This is called by hammer functions.
*
* @param {Event} event The event
* @private
*/_moveSelector(event){let rect=this.colorPickerDiv.getBoundingClientRect();let left=event.center.x-rect.left;let top=event.center.y-rect.top;let centerY=0.5*this.colorPickerDiv.clientHeight;let centerX=0.5*this.colorPickerDiv.clientWidth;let x=left-centerX;let y=top-centerY;let angle=Math.atan2(x,y);let radius=0.98*Math.min(Math.sqrt(x*x+y*y),centerX);let newTop=Math.cos(angle)*radius+centerY;let newLeft=Math.sin(angle)*radius+centerX;this.colorPickerSelector.style.top=newTop-0.5*this.colorPickerSelector.clientHeight+'px';this.colorPickerSelector.style.left=newLeft-0.5*this.colorPickerSelector.clientWidth+'px';// set color
let h=angle/(2*Math.PI);h=h<0?h+1:h;let s=radius/this.r;let hsv=availableUtils.RGBToHSV(this.color.r,this.color.g,this.color.b);hsv.h=h;hsv.s=s;let rgba=availableUtils.HSVToRGB(hsv.h,hsv.s,hsv.v);rgba['a']=this.color.a;this.color=rgba;// update previews
this.initialColorDiv.style.backgroundColor='rgba('+this.initialColor.r+','+this.initialColor.g+','+this.initialColor.b+','+this.initialColor.a+')';this.newColorDiv.style.backgroundColor='rgba('+this.color.r+','+this.color.g+','+this.color.b+','+this.color.a+')';}}/**
* The way this works is for all properties of this.possible options, you can supply the property name in any form to list the options.
* Boolean options are recognised as Boolean
* Number options should be written as array: [default value, min value, max value, stepsize]
* Colors should be written as array: ['color', '#ffffff']
* Strings with should be written as array: [option1, option2, option3, ..]
*
* The options are matched with their counterparts in each of the modules and the values used in the configuration are
*/class Configurator{/**
* @param {Object} parentModule | the location where parentModule.setOptions() can be called
* @param {Object} defaultContainer | the default container of the module
* @param {Object} configureOptions | the fully configured and predefined options set found in allOptions.js
* @param {number} pixelRatio | canvas pixel ratio
*/constructor(parentModule,defaultContainer,configureOptions,pixelRatio=1){this.parent=parentModule;this.changedOptions=[];this.container=defaultContainer;this.allowCreation=false;this.options={};this.initialized=false;this.popupCounter=0;this.defaultOptions={enabled:false,filter:true,container:undefined,showButton:true};availableUtils.extend(this.options,this.defaultOptions);this.configureOptions=configureOptions;this.moduleOptions={};this.domElements=[];this.popupDiv={};this.popupLimit=5;this.popupHistory={};this.colorPicker=new ColorPicker(pixelRatio);this.wrapper=undefined;}/**
* refresh all options.
* Because all modules parse their options by themselves, we just use their options. We copy them here.
*
* @param {Object} options
*/setOptions(options){if(options!==undefined){// reset the popup history because the indices may have been changed.
this.popupHistory={};this._removePopup();let enabled=true;if(typeof options==='string'){this.options.filter=options;}else if(Array.isArray(options)){this.options.filter=options.join();}else if(typeof options==='object'){if(options==null){throw new TypeError('options cannot be null');}if(options.container!==undefined){this.options.container=options.container;}if(options.filter!==undefined){this.options.filter=options.filter;}if(options.showButton!==undefined){this.options.showButton=options.showButton;}if(options.enabled!==undefined){enabled=options.enabled;}}else if(typeof options==='boolean'){this.options.filter=true;enabled=options;}else if(typeof options==='function'){this.options.filter=options;enabled=true;}if(this.options.filter===false){enabled=false;}this.options.enabled=enabled;}this._clean();}/**
*
* @param {Object} moduleOptions
*/setModuleOptions(moduleOptions){this.moduleOptions=moduleOptions;if(this.options.enabled===true){this._clean();if(this.options.container!==undefined){this.container=this.options.container;}this._create();}}/**
* Create all DOM elements
* @private
*/_create(){this._clean();this.changedOptions=[];let filter=this.options.filter;let counter=0;let show=false;for(let option in this.configureOptions){if(this.configureOptions.hasOwnProperty(option)){this.allowCreation=false;show=false;if(typeof filter==='function'){show=filter(option,[]);show=show||this._handleObject(this.configureOptions[option],[option],true);}else if(filter===true||filter.indexOf(option)!==-1){show=true;}if(show!==false){this.allowCreation=true;// linebreak between categories
if(counter>0){this._makeItem([]);}// a header for the category
this._makeHeader(option);// get the sub options
this._handleObject(this.configureOptions[option],[option]);}counter++;}}this._makeButton();this._push();//~ this.colorPicker.insertTo(this.container);
}/**
* draw all DOM elements on the screen
* @private
*/_push(){this.wrapper=document.createElement('div');this.wrapper.className='vis-configuration-wrapper';this.container.appendChild(this.wrapper);for(var i=0;i<this.domElements.length;i++){this.wrapper.appendChild(this.domElements[i]);}this._showPopupIfNeeded();}/**
* delete all DOM elements
* @private
*/_clean(){for(var i=0;i<this.domElements.length;i++){this.wrapper.removeChild(this.domElements[i]);}if(this.wrapper!==undefined){this.container.removeChild(this.wrapper);this.wrapper=undefined;}this.domElements=[];this._removePopup();}/**
* get the value from the actualOptions if it exists
* @param {array} path | where to look for the actual option
* @returns {*}
* @private
*/_getValue(path){let base=this.moduleOptions;for(let i=0;i<path.length;i++){if(base[path[i]]!==undefined){base=base[path[i]];}else {base=undefined;break;}}return base;}/**
* all option elements are wrapped in an item
* @param {Array} path | where to look for the actual option
* @param {Array.<Element>} domElements
* @returns {number}
* @private
*/_makeItem(path,...domElements){if(this.allowCreation===true){let item=document.createElement('div');item.className='vis-configuration vis-config-item vis-config-s'+path.length;domElements.forEach(element=>{item.appendChild(element);});this.domElements.push(item);return this.domElements.length;}return 0;}/**
* header for major subjects
* @param {string} name
* @private
*/_makeHeader(name){let div=document.createElement('div');div.className='vis-configuration vis-config-header';div.innerHTML=availableUtils.xss(name);this._makeItem([],div);}/**
* make a label, if it is an object label, it gets different styling.
* @param {string} name
* @param {array} path | where to look for the actual option
* @param {string} objectLabel
* @returns {HTMLElement}
* @private
*/_makeLabel(name,path,objectLabel=false){let div=document.createElement('div');div.className='vis-configuration vis-config-label vis-config-s'+path.length;if(objectLabel===true){div.innerHTML=availableUtils.xss('<i><b>'+name+':</b></i>');}else {div.innerHTML=availableUtils.xss(name+':');}return div;}/**
* make a dropdown list for multiple possible string optoins
* @param {Array.<number>} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/_makeDropdown(arr,value,path){let select=document.createElement('select');select.className='vis-configuration vis-config-select';let selectedValue=0;if(value!==undefined){if(arr.indexOf(value)!==-1){selectedValue=arr.indexOf(value);}}for(let i=0;i<arr.length;i++){let option=document.createElement('option');option.value=arr[i];if(i===selectedValue){option.selected='selected';}option.innerHTML=arr[i];select.appendChild(option);}let me=this;select.onchange=function(){me._update(this.value,path);};let label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,select);}/**
* make a range object for numeric options
* @param {Array.<number>} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/_makeRange(arr,value,path){let defaultValue=arr[0];let min=arr[1];let max=arr[2];let step=arr[3];let range=document.createElement('input');range.className='vis-configuration vis-config-range';try{range.type='range';// not supported on IE9
range.min=min;range.max=max;}// TODO: Add some error handling and remove this lint exception
catch(err){}// eslint-disable-line no-empty
range.step=step;// set up the popup settings in case they are needed.
let popupString='';let popupValue=0;if(value!==undefined){let factor=1.20;if(value<0&&value*factor<min){range.min=Math.ceil(value*factor);popupValue=range.min;popupString='range increased';}else if(value/factor<min){range.min=Math.ceil(value/factor);popupValue=range.min;popupString='range increased';}if(value*factor>max&&max!==1){range.max=Math.ceil(value*factor);popupValue=range.max;popupString='range increased';}range.value=value;}else {range.value=defaultValue;}let input=document.createElement('input');input.className='vis-configuration vis-config-rangeinput';input.value=Number(range.value);var me=this;range.onchange=function(){input.value=this.value;me._update(Number(this.value),path);};range.oninput=function(){input.value=this.value;};let label=this._makeLabel(path[path.length-1],path);let itemIndex=this._makeItem(path,label,range,input);// if a popup is needed AND it has not been shown for this value, show it.
if(popupString!==''&&this.popupHistory[itemIndex]!==popupValue){this.popupHistory[itemIndex]=popupValue;this._setupPopup(popupString,itemIndex);}}/**
* make a button object
* @private
*/_makeButton(){if(this.options.showButton===true){let generateButton=document.createElement('div');generateButton.className='vis-configuration vis-config-button';generateButton.innerHTML='generate options';generateButton.onclick=()=>{this._printOptions();};generateButton.onmouseover=()=>{generateButton.className='vis-configuration vis-config-button hover';};generateButton.onmouseout=()=>{generateButton.className='vis-configuration vis-config-button';};this.optionsContainer=document.createElement('div');this.optionsContainer.className='vis-configuration vis-config-option-container';this.domElements.push(this.optionsContainer);this.domElements.push(generateButton);}}/**
* prepare the popup
* @param {string} string
* @param {number} index
* @private
*/_setupPopup(string,index){if(this.initialized===true&&this.allowCreation===true&&this.popupCounter<this.popupLimit){let div=document.createElement("div");div.id="vis-configuration-popup";div.className="vis-configuration-popup";div.innerHTML=availableUtils.xss(string);div.onclick=()=>{this._removePopup();};this.popupCounter+=1;this.popupDiv={html:div,index:index};}}/**
* remove the popup from the dom
* @private
*/_removePopup(){if(this.popupDiv.html!==undefined){this.popupDiv.html.parentNode.removeChild(this.popupDiv.html);clearTimeout(this.popupDiv.hideTimeout);clearTimeout(this.popupDiv.deleteTimeout);this.popupDiv={};}}/**
* Show the popup if it is needed.
* @private
*/_showPopupIfNeeded(){if(this.popupDiv.html!==undefined){let correspondingElement=this.domElements[this.popupDiv.index];let rect=correspondingElement.getBoundingClientRect();this.popupDiv.html.style.left=rect.left+"px";this.popupDiv.html.style.top=rect.top-30+"px";// 30 is the height;
document.body.appendChild(this.popupDiv.html);this.popupDiv.hideTimeout=setTimeout(()=>{this.popupDiv.html.style.opacity=0;},1500);this.popupDiv.deleteTimeout=setTimeout(()=>{this._removePopup();},1800);}}/**
* make a checkbox for boolean options.
* @param {number} defaultValue
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/_makeCheckbox(defaultValue,value,path){var checkbox=document.createElement('input');checkbox.type='checkbox';checkbox.className='vis-configuration vis-config-checkbox';checkbox.checked=defaultValue;if(value!==undefined){checkbox.checked=value;if(value!==defaultValue){if(typeof defaultValue==='object'){if(value!==defaultValue.enabled){this.changedOptions.push({path:path,value:value});}}else {this.changedOptions.push({path:path,value:value});}}}let me=this;checkbox.onchange=function(){me._update(this.checked,path);};let label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,checkbox);}/**
* make a text input field for string options.
* @param {number} defaultValue
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/_makeTextInput(defaultValue,value,path){var checkbox=document.createElement('input');checkbox.type='text';checkbox.className='vis-configuration vis-config-text';checkbox.value=value;if(value!==defaultValue){this.changedOptions.push({path:path,value:value});}let me=this;checkbox.onchange=function(){me._update(this.value,path);};let label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,checkbox);}/**
* make a color field with a color picker for color fields
* @param {Array.<number>} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/_makeColorField(arr,value,path){let defaultColor=arr[1];let div=document.createElement('div');value=value===undefined?defaultColor:value;if(value!=='none'){div.className='vis-configuration vis-config-colorBlock';div.style.backgroundColor=value;}else {div.className='vis-configuration vis-config-colorBlock none';}value=value===undefined?defaultColor:value;div.onclick=()=>{this._showColorPicker(value,div,path);};let label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,div);}/**
* used by the color buttons to call the color picker.
* @param {number} value
* @param {HTMLElement} div
* @param {array} path | where to look for the actual option
* @private
*/_showColorPicker(value,div,path){// clear the callback from this div
div.onclick=function(){};this.colorPicker.insertTo(div);this.colorPicker.show();this.colorPicker.setColor(value);this.colorPicker.setUpdateCallback(color=>{let colorString='rgba('+color.r+','+color.g+','+color.b+','+color.a+')';div.style.backgroundColor=colorString;this._update(colorString,path);});// on close of the colorpicker, restore the callback.
this.colorPicker.setCloseCallback(()=>{div.onclick=()=>{this._showColorPicker(value,div,path);};});}/**
* parse an object and draw the correct items
* @param {Object} obj
* @param {array} [path=[]] | where to look for the actual option
* @param {boolean} [checkOnly=false]
* @returns {boolean}
* @private
*/_handleObject(obj,path=[],checkOnly=false){let show=false;let filter=this.options.filter;let visibleInSet=false;for(let subObj in obj){if(obj.hasOwnProperty(subObj)){show=true;let item=obj[subObj];let newPath=availableUtils.copyAndExtendArray(path,subObj);if(typeof filter==='function'){show=filter(subObj,path);// if needed we must go deeper into the object.
if(show===false){if(!Array.isArray(item)&&typeof item!=='string'&&typeof item!=='boolean'&&item instanceof Object){this.allowCreation=false;show=this._handleObject(item,newPath,true);this.allowCreation=checkOnly===false;}}}if(show!==false){visibleInSet=true;let value=this._getValue(newPath);if(Array.isArray(item)){this._handleArray(item,value,newPath);}else if(typeof item==='string'){this._makeTextInput(item,value,newPath);}else if(typeof item==='boolean'){this._makeCheckbox(item,value,newPath);}else if(item instanceof Object){// collapse the physics options that are not enabled
let draw=true;if(path.indexOf('physics')!==-1){if(this.moduleOptions.physics.solver!==subObj){draw=false;}}if(draw===true){// initially collapse options with an disabled enabled option.
if(item.enabled!==undefined){let enabledPath=availableUtils.copyAndExtendArray(newPath,'enabled');let enabledValue=this._getValue(enabledPath);if(enabledValue===true){let label=this._makeLabel(subObj,newPath,true);this._makeItem(newPath,label);visibleInSet=this._handleObject(item,newPath)||visibleInSet;}else {this._makeCheckbox(item,enabledValue,newPath);}}else {let label=this._makeLabel(subObj,newPath,true);this._makeItem(newPath,label);visibleInSet=this._handleObject(item,newPath)||visibleInSet;}}}else {console.error('dont know how to handle',item,subObj,newPath);}}}}return visibleInSet;}/**
* handle the array type of option
* @param {Array.<number>} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/_handleArray(arr,value,path){if(typeof arr[0]==='string'&&arr[0]==='color'){this._makeColorField(arr,value,path);if(arr[1]!==value){this.changedOptions.push({path:path,value:value});}}else if(typeof arr[0]==='string'){this._makeDropdown(arr,value,path);if(arr[0]!==value){this.changedOptions.push({path:path,value:value});}}else if(typeof arr[0]==='number'){this._makeRange(arr,value,path);if(arr[0]!==value){this.changedOptions.push({path:path,value:Number(value)});}}}/**
* called to update the network with the new settings.
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/_update(value,path){let options=this._constructOptions(value,path);if(this.parent.body&&this.parent.body.emitter&&this.parent.body.emitter.emit){this.parent.body.emitter.emit("configChange",options);}this.initialized=true;this.parent.setOptions(options);}/**
*
* @param {string|Boolean} value
* @param {Array.<string>} path
* @param {{}} optionsObj
* @returns {{}}
* @private
*/_constructOptions(value,path,optionsObj={}){let pointer=optionsObj;// when dropdown boxes can be string or boolean, we typecast it into correct types
value=value==='true'?true:value;value=value==='false'?false:value;for(let i=0;i<path.length;i++){if(path[i]!=='global'){if(pointer[path[i]]===undefined){pointer[path[i]]={};}if(i!==path.length-1){pointer=pointer[path[i]];}else {pointer[path[i]]=value;}}}return optionsObj;}/**
* @private
*/_printOptions(){let options=this.getOptions();this.optionsContainer.innerHTML='<pre>var options = '+JSON.stringify(options,null,2)+'</pre>';}/**
*
* @returns {{}} options
*/getOptions(){let options={};for(var i=0;i<this.changedOptions.length;i++){this._constructOptions(this.changedOptions[i].value,this.changedOptions[i].path,options);}return options;}}/**
* Create a timeline visualization
* @extends Core
*/class Timeline extends Core{/**
* @param {HTMLElement} container
* @param {vis.DataSet | vis.DataView | Array} [items]
* @param {vis.DataSet | vis.DataView | Array} [groups]
* @param {Object} [options] See Timeline.setOptions for the available options.
* @constructor Timeline
*/constructor(container,items,groups,options){super();this.initTime=new Date();this.itemsDone=false;if(!(this instanceof Timeline)){throw new SyntaxError('Constructor must be called with the new operator');}// if the third element is options, the forth is groups (optionally);
if(!(Array.isArray(groups)||isDataViewLike(groups))&&groups instanceof Object){const forthArgument=options;options=groups;groups=forthArgument;}// TODO: REMOVE THIS in the next MAJOR release
// see https://github.com/almende/vis/issues/2511
if(options&&options.throttleRedraw){console.warn("Timeline option \"throttleRedraw\" is DEPRICATED and no longer supported. It will be removed in the next MAJOR release.");}const me=this;this.defaultOptions={autoResize:true,longSelectPressTime:251,orientation:{axis:'bottom',// axis orientation: 'bottom', 'top', or 'both'
item:'bottom'// not relevant
},moment:moment$3};this.options=availableUtils.deepExtend({},this.defaultOptions);options&&availableUtils.setupXSSProtection(options.xss);// Create the DOM, props, and emitter
this._create(container);if(!options||options&&typeof options.rtl=="undefined"){this.dom.root.style.visibility='hidden';let directionFromDom;let domNode=this.dom.root;while(!directionFromDom&&domNode){directionFromDom=window.getComputedStyle(domNode,null).direction;domNode=domNode.parentElement;}this.options.rtl=directionFromDom&&directionFromDom.toLowerCase()=="rtl";}else {this.options.rtl=options.rtl;}if(options){if(options.rollingMode){this.options.rollingMode=options.rollingMode;}if(options.onInitialDrawComplete){this.options.onInitialDrawComplete=options.onInitialDrawComplete;}if(options.onTimeout){this.options.onTimeout=options.onTimeout;}if(options.loadingScreenTemplate){this.options.loadingScreenTemplate=options.loadingScreenTemplate;}}// Prepare loading screen
const loadingScreenFragment=document.createElement('div');if(this.options.loadingScreenTemplate){const templateFunction=this.options.loadingScreenTemplate.bind(this);const loadingScreen=templateFunction(this.dom.loadingScreen);if(loadingScreen instanceof Object&&!(loadingScreen instanceof Element)){templateFunction(loadingScreenFragment);}else {if(loadingScreen instanceof Element){loadingScreenFragment.innerHTML='';loadingScreenFragment.appendChild(loadingScreen);}else if(loadingScreen!=undefined){loadingScreenFragment.innerHTML=availableUtils.xss(loadingScreen);}}}this.dom.loadingScreen.appendChild(loadingScreenFragment);// all components listed here will be repainted automatically
this.components=[];this.body={dom:this.dom,domProps:this.props,emitter:{on:this.on.bind(this),off:this.off.bind(this),emit:this.emit.bind(this)},hiddenDates:[],util:{getScale(){return me.timeAxis.step.scale;},getStep(){return me.timeAxis.step.step;},toScreen:me._toScreen.bind(me),toGlobalScreen:me._toGlobalScreen.bind(me),// this refers to the root.width
toTime:me._toTime.bind(me),toGlobalTime:me._toGlobalTime.bind(me)}};// range
this.range=new Range(this.body,this.options);this.components.push(this.range);this.body.range=this.range;// time axis
this.timeAxis=new TimeAxis(this.body,this.options);this.timeAxis2=null;// used in case of orientation option 'both'
this.components.push(this.timeAxis);// current time bar
this.currentTime=new CurrentTime(this.body,this.options);this.components.push(this.currentTime);// item set
this.itemSet=new ItemSet(this.body,this.options);this.components.push(this.itemSet);this.itemsData=null;// DataSet
this.groupsData=null;// DataSet
function emit(eventName,event){if(!me.hasListeners(eventName)){return;}me.emit(eventName,me.getEventProperties(event));}this.dom.root.onclick=event=>{emit('click',event);};this.dom.root.ondblclick=event=>{emit('doubleClick',event);};this.dom.root.oncontextmenu=event=>{emit('contextmenu',event);};this.dom.root.onmouseover=event=>{emit('mouseOver',event);};if(window.PointerEvent){this.dom.root.onpointerdown=event=>{emit('mouseDown',event);};this.dom.root.onpointermove=event=>{emit('mouseMove',event);};this.dom.root.onpointerup=event=>{emit('mouseUp',event);};}else {this.dom.root.onmousemove=event=>{emit('mouseMove',event);};this.dom.root.onmousedown=event=>{emit('mouseDown',event);};this.dom.root.onmouseup=event=>{emit('mouseUp',event);};}//Single time autoscale/fit
this.initialFitDone=false;this.on('changed',()=>{if(me.itemsData==null)return;if(!me.initialFitDone&&!me.options.rollingMode){me.initialFitDone=true;if(me.options.start!=undefined||me.options.end!=undefined){if(me.options.start==undefined||me.options.end==undefined){var range=me.getItemRange();}const start=me.options.start!=undefined?me.options.start:range.min;const end=me.options.end!=undefined?me.options.end:range.max;me.setWindow(start,end,{animation:false});}else {me.fit({animation:false});}}if(!me.initialDrawDone&&(me.initialRangeChangeDone||!me.options.start&&!me.options.end||me.options.rollingMode)){me.initialDrawDone=true;me.itemSet.initialDrawDone=true;me.dom.root.style.visibility='visible';me.dom.loadingScreen.parentNode.removeChild(me.dom.loadingScreen);if(me.options.onInitialDrawComplete){setTimeout(()=>{return me.options.onInitialDrawComplete();},0);}}});this.on('destroyTimeline',()=>{me.destroy();});// apply options
if(options){this.setOptions(options);}this.body.emitter.on('fit',args=>{this._onFit(args);this.redraw();});// IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
if(groups){this.setGroups(groups);}// create itemset
if(items){this.setItems(items);}// draw for the first time
this._redraw();}/**
* Load a configurator
* @return {Object}
* @private
*/_createConfigurator(){return new Configurator(this,this.dom.container,configureOptions$1);}/**
* Force a redraw. The size of all items will be recalculated.
* Can be useful to manually redraw when option autoResize=false and the window
* has been resized, or when the items CSS has been changed.
*
* Note: this function will be overridden on construction with a trottled version
*/redraw(){this.itemSet&&this.itemSet.markDirty({refreshItems:true});this._redraw();}/**
* Remove an item from the group
* @param {object} options
*/setOptions(options){// validate options
let errorFound=Validator.validate(options,allOptions$1);if(errorFound===true){console.log('%cErrors have been found in the supplied options object.',printStyle);}Core.prototype.setOptions.call(this,options);if('type'in options){if(options.type!==this.options.type){this.options.type=options.type;// force recreation of all items
const itemsData=this.itemsData;if(itemsData){const selection=this.getSelection();this.setItems(null);// remove all
this.setItems(itemsData.rawDS);// add all
this.setSelection(selection);// restore selection
}}}}/**
* Set items
* @param {vis.DataSet | Array | null} items
*/setItems(items){this.itemsDone=false;// convert to type DataSet when needed
let newDataSet;if(!items){newDataSet=null;}else if(isDataViewLike(items)){newDataSet=typeCoerceDataSet(items);}else {// turn an array into a dataset
newDataSet=typeCoerceDataSet(new DataSet(items));}// set items
if(this.itemsData){// stop maintaining a coerced version of the old data set
this.itemsData.dispose();}this.itemsData=newDataSet;this.itemSet&&this.itemSet.setItems(newDataSet!=null?newDataSet.rawDS:null);}/**
* Set groups
* @param {vis.DataSet | Array} groups
*/setGroups(groups){// convert to type DataSet when needed
let newDataSet;const filter=group=>group.visible!==false;if(!groups){newDataSet=null;}else {// If groups is array, turn to DataSet & build dataview from that
if(Array.isArray(groups))groups=new DataSet(groups);newDataSet=new DataView(groups,{filter});}// This looks weird but it's necessary to prevent memory leaks.
//
// The problem is that the DataView will exist as long as the DataSet it's
// connected to. This will force it to swap the groups DataSet for it's own
// DataSet. In this arrangement it will become unreferenced from the outside
// and garbage collected.
//
// IMPORTANT NOTE: If `this.groupsData` is a DataView was created in this
// method. Even if the original is a DataView already a new one has been
// created and assigned to `this.groupsData`. In case this changes in the
// future it will be necessary to rework this!!!!
if(this.groupsData!=null&&typeof this.groupsData.setData==="function"){this.groupsData.setData(null);}this.groupsData=newDataSet;this.itemSet.setGroups(newDataSet);}/**
* Set both items and groups in one go
* @param {{items: (Array | vis.DataSet), groups: (Array | vis.DataSet)}} data
*/setData(data){if(data&&data.groups){this.setGroups(data.groups);}if(data&&data.items){this.setItems(data.items);}}/**
* Set selected items by their id. Replaces the current selection
* Unknown id's are silently ignored.
* @param {string[] | string} [ids] An array with zero or more id's of the items to be
* selected. If ids is an empty array, all items will be
* unselected.
* @param {Object} [options] Available options:
* `focus: boolean`
* If true, focus will be set to the selected item(s)
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* Only applicable when option focus is true.
*/setSelection(ids,options){this.itemSet&&this.itemSet.setSelection(ids);if(options&&options.focus){this.focus(ids,options);}}/**
* Get the selected items by their id
* @return {Array} ids The ids of the selected items
*/getSelection(){return this.itemSet&&this.itemSet.getSelection()||[];}/**
* Adjust the visible window such that the selected item (or multiple items)
* are centered on screen.
* @param {string | String[]} id An item id or array with item ids
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* `zoom: boolean`
* If true (default), the timeline will
* zoom on the element after focus it.
*/focus(id,options){if(!this.itemsData||id==undefined)return;const ids=Array.isArray(id)?id:[id];// get the specified item(s)
const itemsData=this.itemsData.get(ids);// calculate minimum start and maximum end of specified items
let start=null;let end=null;itemsData.forEach(itemData=>{const s=itemData.start.valueOf();const e='end'in itemData?itemData.end.valueOf():itemData.start.valueOf();if(start===null||s<start){start=s;}if(end===null||e>end){end=e;}});if(start!==null&&end!==null){const me=this;// Use the first item for the vertical focus
const item=this.itemSet.items[ids[0]];let startPos=this._getScrollTop()*-1;let initialVerticalScroll=null;// Setup a handler for each frame of the vertical scroll
const verticalAnimationFrame=(ease,willDraw,done)=>{const verticalScroll=getItemVerticalScroll(me,item);if(verticalScroll===false){return;// We don't need to scroll, so do nothing
}if(!initialVerticalScroll){initialVerticalScroll=verticalScroll;}if(initialVerticalScroll.itemTop==verticalScroll.itemTop&&!initialVerticalScroll.shouldScroll){return;// We don't need to scroll, so do nothing
}else if(initialVerticalScroll.itemTop!=verticalScroll.itemTop&&verticalScroll.shouldScroll){// The redraw shifted elements, so reset the animation to correct
initialVerticalScroll=verticalScroll;startPos=me._getScrollTop()*-1;}const from=startPos;const to=initialVerticalScroll.scrollOffset;const scrollTop=done?to:from+(to-from)*ease;me._setScrollTop(-scrollTop);if(!willDraw){me._redraw();}};// Enforces the final vertical scroll position
const setFinalVerticalPosition=()=>{const finalVerticalScroll=getItemVerticalScroll(me,item);if(finalVerticalScroll.shouldScroll&&finalVerticalScroll.itemTop!=initialVerticalScroll.itemTop){me._setScrollTop(-finalVerticalScroll.scrollOffset);me._redraw();}};// Perform one last check at the end to make sure the final vertical
// position is correct
const finalVerticalCallback=()=>{// Double check we ended at the proper scroll position
setFinalVerticalPosition();// Let the redraw settle and finalize the position.
setTimeout(setFinalVerticalPosition,100);};// calculate the new middle and interval for the window
const zoom=options&&options.zoom!==undefined?options.zoom:true;const middle=(start+end)/2;const interval=zoom?(end-start)*1.1:Math.max(this.range.end-this.range.start,(end-start)*1.1);const animation=options&&options.animation!==undefined?options.animation:true;if(!animation){// We aren't animating so set a default so that the final callback forces the vertical location
initialVerticalScroll={shouldScroll:false,scrollOffset:-1,itemTop:-1};}this.range.setRange(middle-interval/2,middle+interval/2,{animation},finalVerticalCallback,verticalAnimationFrame);}}/**
* Set Timeline window such that it fits all items
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback]
*/fit(options,callback){const animation=options&&options.animation!==undefined?options.animation:true;let range;if(this.itemsData.length===1&&this.itemsData.get()[0].end===undefined){// a single item -> don't fit, just show a range around the item from -4 to +3 days
range=this.getDataRange();this.moveTo(range.min.valueOf(),{animation},callback);}else {// exactly fit the items (plus a small margin)
range=this.getItemRange();this.range.setRange(range.min,range.max,{animation},callback);}}/**
* Determine the range of the items, taking into account their actual width
* and a margin of 10 pixels on both sides.
*
* @returns {{min: Date, max: Date}}
*/getItemRange(){// get a rough approximation for the range based on the items start and end dates
const range=this.getDataRange();let min=range.min!==null?range.min.valueOf():null;let max=range.max!==null?range.max.valueOf():null;let minItem=null;let maxItem=null;if(min!=null&&max!=null){let interval=max-min;// ms
if(interval<=0){interval=10;}const factor=interval/this.props.center.width;const redrawQueue={};let redrawQueueLength=0;// collect redraw functions
availableUtils.forEach(this.itemSet.items,(item,key)=>{if(item.groupShowing){const returnQueue=true;redrawQueue[key]=item.redraw(returnQueue);redrawQueueLength=redrawQueue[key].length;}});const needRedraw=redrawQueueLength>0;if(needRedraw){// redraw all regular items
for(let i=0;i<redrawQueueLength;i++){availableUtils.forEach(redrawQueue,fns=>{fns[i]();});}}// calculate the date of the left side and right side of the items given
availableUtils.forEach(this.itemSet.items,item=>{const start=getStart(item);const end=getEnd(item);let startSide;let endSide;if(this.options.rtl){startSide=start-(item.getWidthRight()+10)*factor;endSide=end+(item.getWidthLeft()+10)*factor;}else {startSide=start-(item.getWidthLeft()+10)*factor;endSide=end+(item.getWidthRight()+10)*factor;}if(startSide<min){min=startSide;minItem=item;}if(endSide>max){max=endSide;maxItem=item;}});if(minItem&&maxItem){const lhs=minItem.getWidthLeft()+10;const rhs=maxItem.getWidthRight()+10;const delta=this.props.center.width-lhs-rhs;// px
if(delta>0){if(this.options.rtl){min=getStart(minItem)-rhs*interval/delta;// ms
max=getEnd(maxItem)+lhs*interval/delta;// ms
}else {min=getStart(minItem)-lhs*interval/delta;// ms
max=getEnd(maxItem)+rhs*interval/delta;// ms
}}}}return {min:min!=null?new Date(min):null,max:max!=null?new Date(max):null};}/**
* Calculate the data range of the items start and end dates
* @returns {{min: Date, max: Date}}
*/getDataRange(){let min=null;let max=null;if(this.itemsData){this.itemsData.forEach(item=>{const start=availableUtils.convert(item.start,'Date').valueOf();const end=availableUtils.convert(item.end!=undefined?item.end:item.start,'Date').valueOf();if(min===null||start<min){min=start;}if(max===null||end>max){max=end;}});}return {min:min!=null?new Date(min):null,max:max!=null?new Date(max):null};}/**
* Generate Timeline related information from an event
* @param {Event} event
* @return {Object} An object with related information, like on which area
* The event happened, whether clicked on an item, etc.
*/getEventProperties(event){const clientX=event.center?event.center.x:event.clientX;const clientY=event.center?event.center.y:event.clientY;const centerContainerRect=this.dom.centerContainer.getBoundingClientRect();const x=this.options.rtl?centerContainerRect.right-clientX:clientX-centerContainerRect.left;const y=clientY-centerContainerRect.top;const item=this.itemSet.itemFromTarget(event);const group=this.itemSet.groupFromTarget(event);const customTime=CustomTime.customTimeFromTarget(event);const snap=this.itemSet.options.snap||null;const scale=this.body.util.getScale();const step=this.body.util.getStep();const time=this._toTime(x);const snappedTime=snap?snap(time,scale,step):time;const element=availableUtils.getTarget(event);let what=null;if(item!=null){what='item';}else if(customTime!=null){what='custom-time';}else if(availableUtils.hasParent(element,this.timeAxis.dom.foreground)){what='axis';}else if(this.timeAxis2&&availableUtils.hasParent(element,this.timeAxis2.dom.foreground)){what='axis';}else if(availableUtils.hasParent(element,this.itemSet.dom.labelSet)){what='group-label';}else if(availableUtils.hasParent(element,this.currentTime.bar)){what='current-time';}else if(availableUtils.hasParent(element,this.dom.center)){what='background';}return {event,item:item?item.id:null,isCluster:item?!!item.isCluster:false,items:item?item.items||[]:null,group:group?group.groupId:null,customTime:customTime?customTime.options.id:null,what,pageX:event.srcEvent?event.srcEvent.pageX:event.pageX,pageY:event.srcEvent?event.srcEvent.pageY:event.pageY,x,y,time,snappedTime};}/**
* Toggle Timeline rolling mode
*/toggleRollingMode(){if(this.range.rolling){this.range.stopRolling();}else {if(this.options.rollingMode==undefined){this.setOptions(this.options);}this.range.startRolling();}}/**
* redraw
* @private
*/_redraw(){Core.prototype._redraw.call(this);}/**
* on fit callback
* @param {object} args
* @private
*/_onFit(args){const{start,end,animation}=args;if(!end){this.moveTo(start.valueOf(),{animation});}else {this.range.setRange(start,end,{animation:animation});}}}/**
*
* @param {timeline.Item} item
* @returns {number}
*/function getStart(item){return availableUtils.convert(item.data.start,'Date').valueOf();}/**
*
* @param {timeline.Item} item
* @returns {number}
*/function getEnd(item){const end=item.data.end!=undefined?item.data.end:item.data.start;return availableUtils.convert(end,'Date').valueOf();}/**
* @param {vis.Timeline} timeline
* @param {timeline.Item} item
* @return {{shouldScroll: bool, scrollOffset: number, itemTop: number}}
*/function getItemVerticalScroll(timeline,item){if(!item.parent){// The item no longer exists, so ignore this focus.
return false;}const itemsetHeight=timeline.options.rtl?timeline.props.rightContainer.height:timeline.props.leftContainer.height;const contentHeight=timeline.props.center.height;const group=item.parent;let offset=group.top;let shouldScroll=true;const orientation=timeline.timeAxis.options.orientation.axis;const itemTop=()=>{if(orientation=="bottom"){return group.height-item.top-item.height;}else {return item.top;}};const currentScrollHeight=timeline._getScrollTop()*-1;const targetOffset=offset+itemTop();const height=item.height;if(targetOffset<currentScrollHeight){if(offset+itemsetHeight<=offset+itemTop()+height){offset+=itemTop()-timeline.itemSet.options.margin.item.vertical;}}else if(targetOffset+height>currentScrollHeight+itemsetHeight){offset+=itemTop()+height-itemsetHeight+timeline.itemSet.options.margin.item.vertical;}else {shouldScroll=false;}offset=Math.min(offset,contentHeight-itemsetHeight);return {shouldScroll,scrollOffset:offset,itemTop:targetOffset};}// DOM utility methods
/**
* this prepares the JSON container for allocating SVG elements
* @param {Object} JSONcontainer
* @private
*/function prepareElements(JSONcontainer){// cleanup the redundant svgElements;
for(var elementType in JSONcontainer){if(JSONcontainer.hasOwnProperty(elementType)){JSONcontainer[elementType].redundant=JSONcontainer[elementType].used;JSONcontainer[elementType].used=[];}}}/**
* this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
* which to remove the redundant elements.
*
* @param {Object} JSONcontainer
* @private
*/function cleanupElements(JSONcontainer){// cleanup the redundant svgElements;
for(var elementType in JSONcontainer){if(JSONcontainer.hasOwnProperty(elementType)){if(JSONcontainer[elementType].redundant){for(var i=0;i<JSONcontainer[elementType].redundant.length;i++){JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);}JSONcontainer[elementType].redundant=[];}}}}/**
* Ensures that all elements are removed first up so they can be recreated cleanly
* @param {Object} JSONcontainer
*/function resetElements(JSONcontainer){prepareElements(JSONcontainer);cleanupElements(JSONcontainer);prepareElements(JSONcontainer);}/**
* Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
* the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
*
* @param {string} elementType
* @param {Object} JSONcontainer
* @param {Object} svgContainer
* @returns {Element}
* @private
*/function getSVGElement(elementType,JSONcontainer,svgContainer){var element;// allocate SVG element, if it doesnt yet exist, create one.
if(JSONcontainer.hasOwnProperty(elementType)){// this element has been created before
// check if there is an redundant element
if(JSONcontainer[elementType].redundant.length>0){element=JSONcontainer[elementType].redundant[0];JSONcontainer[elementType].redundant.shift();}else {// create a new element and add it to the SVG
element=document.createElementNS('http://www.w3.org/2000/svg',elementType);svgContainer.appendChild(element);}}else {// create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
element=document.createElementNS('http://www.w3.org/2000/svg',elementType);JSONcontainer[elementType]={used:[],redundant:[]};svgContainer.appendChild(element);}JSONcontainer[elementType].used.push(element);return element;}/**
* Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
* the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
*
* @param {string} elementType
* @param {Object} JSONcontainer
* @param {Element} DOMContainer
* @param {Element} insertBefore
* @returns {*}
*/function getDOMElement(elementType,JSONcontainer,DOMContainer,insertBefore){var element;// allocate DOM element, if it doesnt yet exist, create one.
if(JSONcontainer.hasOwnProperty(elementType)){// this element has been created before
// check if there is an redundant element
if(JSONcontainer[elementType].redundant.length>0){element=JSONcontainer[elementType].redundant[0];JSONcontainer[elementType].redundant.shift();}else {// create a new element and add it to the SVG
element=document.createElement(elementType);if(insertBefore!==undefined){DOMContainer.insertBefore(element,insertBefore);}else {DOMContainer.appendChild(element);}}}else {// create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
element=document.createElement(elementType);JSONcontainer[elementType]={used:[],redundant:[]};if(insertBefore!==undefined){DOMContainer.insertBefore(element,insertBefore);}else {DOMContainer.appendChild(element);}}JSONcontainer[elementType].used.push(element);return element;}/**
* Draw a point object. This is a separate function because it can also be called by the legend.
* The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
* as well.
*
* @param {number} x
* @param {number} y
* @param {Object} groupTemplate: A template containing the necessary information to draw the datapoint e.g., {style: 'circle', size: 5, className: 'className' }
* @param {Object} JSONcontainer
* @param {Object} svgContainer
* @param {Object} labelObj
* @returns {vis.PointItem}
*/function drawPoint(x,y,groupTemplate,JSONcontainer,svgContainer,labelObj){var point;if(groupTemplate.style=='circle'){point=getSVGElement('circle',JSONcontainer,svgContainer);point.setAttributeNS(null,"cx",x);point.setAttributeNS(null,"cy",y);point.setAttributeNS(null,"r",0.5*groupTemplate.size);}else {point=getSVGElement('rect',JSONcontainer,svgContainer);point.setAttributeNS(null,"x",x-0.5*groupTemplate.size);point.setAttributeNS(null,"y",y-0.5*groupTemplate.size);point.setAttributeNS(null,"width",groupTemplate.size);point.setAttributeNS(null,"height",groupTemplate.size);}if(groupTemplate.styles!==undefined){point.setAttributeNS(null,"style",groupTemplate.styles);}point.setAttributeNS(null,"class",groupTemplate.className+" vis-point");//handle label
if(labelObj){var label=getSVGElement('text',JSONcontainer,svgContainer);if(labelObj.xOffset){x=x+labelObj.xOffset;}if(labelObj.yOffset){y=y+labelObj.yOffset;}if(labelObj.content){label.textContent=labelObj.content;}if(labelObj.className){label.setAttributeNS(null,"class",labelObj.className+" vis-label");}label.setAttributeNS(null,"x",x);label.setAttributeNS(null,"y",y);}return point;}/**
* draw a bar SVG element centered on the X coordinate
*
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {string} className
* @param {Object} JSONcontainer
* @param {Object} svgContainer
* @param {string} style
*/function drawBar(x,y,width,height,className,JSONcontainer,svgContainer,style){if(height!=0){if(height<0){height*=-1;y-=height;}var rect=getSVGElement('rect',JSONcontainer,svgContainer);rect.setAttributeNS(null,"x",x-0.5*width);rect.setAttributeNS(null,"y",y);rect.setAttributeNS(null,"width",width);rect.setAttributeNS(null,"height",height);rect.setAttributeNS(null,"class",className);if(style){rect.setAttributeNS(null,"style",style);}}}/**
* get default language
* @returns {string}
*/function getNavigatorLanguage(){try{if(!navigator)return 'en';if(navigator.languages&&navigator.languages.length){return navigator.languages;}else {return navigator.userLanguage||navigator.language||navigator.browserLanguage||'en';}}catch(error){return 'en';}}/** DataScale */class DataScale{/**
*
* @param {number} start
* @param {number} end
* @param {boolean} autoScaleStart
* @param {boolean} autoScaleEnd
* @param {number} containerHeight
* @param {number} majorCharHeight
* @param {boolean} zeroAlign
* @param {function} formattingFunction
* @constructor DataScale
*/constructor(start,end,autoScaleStart,autoScaleEnd,containerHeight,majorCharHeight,zeroAlign=false,formattingFunction=false){this.majorSteps=[1,2,5,10];this.minorSteps=[0.25,0.5,1,2];this.customLines=null;this.containerHeight=containerHeight;this.majorCharHeight=majorCharHeight;this._start=start;this._end=end;this.scale=1;this.minorStepIdx=-1;this.magnitudefactor=1;this.determineScale();this.zeroAlign=zeroAlign;this.autoScaleStart=autoScaleStart;this.autoScaleEnd=autoScaleEnd;this.formattingFunction=formattingFunction;if(autoScaleStart||autoScaleEnd){const me=this;const roundToMinor=value=>{const rounded=value-value%(me.magnitudefactor*me.minorSteps[me.minorStepIdx]);if(value%(me.magnitudefactor*me.minorSteps[me.minorStepIdx])>0.5*(me.magnitudefactor*me.minorSteps[me.minorStepIdx])){return rounded+me.magnitudefactor*me.minorSteps[me.minorStepIdx];}else {return rounded;}};if(autoScaleStart){this._start-=this.magnitudefactor*2*this.minorSteps[this.minorStepIdx];this._start=roundToMinor(this._start);}if(autoScaleEnd){this._end+=this.magnitudefactor*this.minorSteps[this.minorStepIdx];this._end=roundToMinor(this._end);}this.determineScale();}}/**
* set chart height
* @param {number} majorCharHeight
*/setCharHeight(majorCharHeight){this.majorCharHeight=majorCharHeight;}/**
* set height
* @param {number} containerHeight
*/setHeight(containerHeight){this.containerHeight=containerHeight;}/**
* determine scale
*/determineScale(){const range=this._end-this._start;this.scale=this.containerHeight/range;const minimumStepValue=this.majorCharHeight/this.scale;const orderOfMagnitude=range>0?Math.round(Math.log(range)/Math.LN10):0;this.minorStepIdx=-1;this.magnitudefactor=Math.pow(10,orderOfMagnitude);let start=0;if(orderOfMagnitude<0){start=orderOfMagnitude;}let solutionFound=false;for(let l=start;Math.abs(l)<=Math.abs(orderOfMagnitude);l++){this.magnitudefactor=Math.pow(10,l);for(let j=0;j<this.minorSteps.length;j++){const stepSize=this.magnitudefactor*this.minorSteps[j];if(stepSize>=minimumStepValue){solutionFound=true;this.minorStepIdx=j;break;}}if(solutionFound===true){break;}}}/**
* returns if value is major
* @param {number} value
* @returns {boolean}
*/is_major(value){return value%(this.magnitudefactor*this.majorSteps[this.minorStepIdx])===0;}/**
* returns step size
* @returns {number}
*/getStep(){return this.magnitudefactor*this.minorSteps[this.minorStepIdx];}/**
* returns first major
* @returns {number}
*/getFirstMajor(){const majorStep=this.magnitudefactor*this.majorSteps[this.minorStepIdx];return this.convertValue(this._start+(majorStep-this._start%majorStep)%majorStep);}/**
* returns first major
* @param {date} current
* @returns {date} formatted date
*/formatValue(current){let returnValue=current.toPrecision(5);if(typeof this.formattingFunction==='function'){returnValue=this.formattingFunction(current);}if(typeof returnValue==='number'){return `${returnValue}`;}else if(typeof returnValue==='string'){return returnValue;}else {return current.toPrecision(5);}}/**
* returns lines
* @returns {object} lines
*/getLines(){const lines=[];const step=this.getStep();const bottomOffset=(step-this._start%step)%step;for(let i=this._start+bottomOffset;this._end-i>0.00001;i+=step){if(i!=this._start){//Skip the bottom line
lines.push({major:this.is_major(i),y:this.convertValue(i),val:this.formatValue(i)});}}return lines;}/**
* follow scale
* @param {object} other
*/followScale(other){const oldStepIdx=this.minorStepIdx;const oldStart=this._start;const oldEnd=this._end;const me=this;const increaseMagnitude=()=>{me.magnitudefactor*=2;};const decreaseMagnitude=()=>{me.magnitudefactor/=2;};if(other.minorStepIdx<=1&&this.minorStepIdx<=1||other.minorStepIdx>1&&this.minorStepIdx>1);else if(other.minorStepIdx<this.minorStepIdx){//I'm 5, they are 4 per major.
this.minorStepIdx=1;if(oldStepIdx==2){increaseMagnitude();}else {increaseMagnitude();increaseMagnitude();}}else {//I'm 4, they are 5 per major
this.minorStepIdx=2;if(oldStepIdx==1){decreaseMagnitude();}else {decreaseMagnitude();decreaseMagnitude();}}//Get masters stats:
const otherZero=other.convertValue(0);const otherStep=other.getStep()*other.scale;let done=false;let count=0;//Loop until magnitude is correct for given constrains.
while(!done&&count++<5){//Get my stats:
this.scale=otherStep/(this.minorSteps[this.minorStepIdx]*this.magnitudefactor);const newRange=this.containerHeight/this.scale;//For the case the magnitudefactor has changed:
this._start=oldStart;this._end=this._start+newRange;const myOriginalZero=this._end*this.scale;const majorStep=this.magnitudefactor*this.majorSteps[this.minorStepIdx];const majorOffset=this.getFirstMajor()-other.getFirstMajor();if(this.zeroAlign){const zeroOffset=otherZero-myOriginalZero;this._end+=zeroOffset/this.scale;this._start=this._end-newRange;}else {if(!this.autoScaleStart){this._start+=majorStep-majorOffset/this.scale;this._end=this._start+newRange;}else {this._start-=majorOffset/this.scale;this._end=this._start+newRange;}}if(!this.autoScaleEnd&&this._end>oldEnd+0.00001){//Need to decrease magnitude to prevent scale overshoot! (end)
decreaseMagnitude();done=false;continue;}if(!this.autoScaleStart&&this._start<oldStart-0.00001){if(this.zeroAlign&&oldStart>=0){console.warn("Can't adhere to given 'min' range, due to zeroalign");}else {//Need to decrease magnitude to prevent scale overshoot! (start)
decreaseMagnitude();done=false;continue;}}if(this.autoScaleStart&&this.autoScaleEnd&&newRange<oldEnd-oldStart){increaseMagnitude();done=false;continue;}done=true;}}/**
* convert value
* @param {number} value
* @returns {number}
*/convertValue(value){return this.containerHeight-(value-this._start)*this.scale;}/**
* returns screen to value
* @param {number} pixels
* @returns {number}
*/screenToValue(pixels){return (this.containerHeight-pixels)/this.scale+this._start;}}/** A horizontal time axis */class DataAxis extends Component{/**
* @param {Object} body
* @param {Object} [options] See DataAxis.setOptions for the available
* options.
* @param {SVGElement} svg
* @param {timeline.LineGraph.options} linegraphOptions
* @constructor DataAxis
* @extends Component
*/constructor(body,options,svg,linegraphOptions){super();this.id=v4();this.body=body;this.defaultOptions={orientation:'left',// supported: 'left', 'right'
showMinorLabels:true,showMajorLabels:true,showWeekScale:false,icons:false,majorLinesOffset:7,minorLinesOffset:4,labelOffsetX:10,labelOffsetY:2,iconWidth:20,width:'40px',visible:true,alignZeros:true,left:{range:{min:undefined,max:undefined},format(value){return `${parseFloat(value.toPrecision(3))}`;},title:{text:undefined,style:undefined}},right:{range:{min:undefined,max:undefined},format(value){return `${parseFloat(value.toPrecision(3))}`;},title:{text:undefined,style:undefined}}};this.linegraphOptions=linegraphOptions;this.linegraphSVG=svg;this.props={};this.DOMelements={// dynamic elements
lines:{},labels:{},title:{}};this.dom={};this.scale=undefined;this.range={start:0,end:0};this.options=availableUtils.extend({},this.defaultOptions);this.conversionFactor=1;this.setOptions(options);this.width=Number(`${this.options.width}`.replace("px",""));this.minWidth=this.width;this.height=this.linegraphSVG.getBoundingClientRect().height;this.hidden=false;this.stepPixels=25;this.zeroCrossing=-1;this.amountOfSteps=-1;this.lineOffset=0;this.master=true;this.masterAxis=null;this.svgElements={};this.iconsRemoved=false;this.groups={};this.amountOfGroups=0;// create the HTML DOM
this._create();if(this.scale==undefined){this._redrawLabels();}this.framework={svg:this.svg,svgElements:this.svgElements,options:this.options,groups:this.groups};const me=this;this.body.emitter.on("verticalDrag",()=>{me.dom.lineContainer.style.top=`${me.body.domProps.scrollTop}px`;});}/**
* Adds group to data axis
* @param {string} label
* @param {object} graphOptions
*/addGroup(label,graphOptions){if(!this.groups.hasOwnProperty(label)){this.groups[label]=graphOptions;}this.amountOfGroups+=1;}/**
* updates group of data axis
* @param {string} label
* @param {object} graphOptions
*/updateGroup(label,graphOptions){if(!this.groups.hasOwnProperty(label)){this.amountOfGroups+=1;}this.groups[label]=graphOptions;}/**
* removes group of data axis
* @param {string} label
*/removeGroup(label){if(this.groups.hasOwnProperty(label)){delete this.groups[label];this.amountOfGroups-=1;}}/**
* sets options
* @param {object} options
*/setOptions(options){if(options){let redraw=false;if(this.options.orientation!=options.orientation&&options.orientation!==undefined){redraw=true;}const fields=['orientation','showMinorLabels','showMajorLabels','icons','majorLinesOffset','minorLinesOffset','labelOffsetX','labelOffsetY','iconWidth','width','visible','left','right','alignZeros'];availableUtils.selectiveDeepExtend(fields,this.options,options);this.minWidth=Number(`${this.options.width}`.replace("px",""));if(redraw===true&&this.dom.frame){this.hide();this.show();}}}/**
* Create the HTML DOM for the DataAxis
*/_create(){this.dom.frame=document.createElement('div');this.dom.frame.style.width=this.options.width;this.dom.frame.style.height=this.height;this.dom.lineContainer=document.createElement('div');this.dom.lineContainer.style.width='100%';this.dom.lineContainer.style.height=this.height;this.dom.lineContainer.style.position='relative';this.dom.lineContainer.style.visibility='visible';this.dom.lineContainer.style.display='block';// create svg element for graph drawing.
this.svg=document.createElementNS('http://www.w3.org/2000/svg',"svg");this.svg.style.position="absolute";this.svg.style.top='0px';this.svg.style.height='100%';this.svg.style.width='100%';this.svg.style.display="block";this.dom.frame.appendChild(this.svg);}/**
* redraws groups icons
*/_redrawGroupIcons(){prepareElements(this.svgElements);let x;const iconWidth=this.options.iconWidth;const iconHeight=15;const iconOffset=4;let y=iconOffset+0.5*iconHeight;if(this.options.orientation==='left'){x=iconOffset;}else {x=this.width-iconWidth-iconOffset;}const groupArray=Object.keys(this.groups);groupArray.sort((a,b)=>a<b?-1:1);for(const groupId of groupArray){if(this.groups[groupId].visible===true&&(this.linegraphOptions.visibility[groupId]===undefined||this.linegraphOptions.visibility[groupId]===true)){this.groups[groupId].getLegend(iconWidth,iconHeight,this.framework,x,y);y+=iconHeight+iconOffset;}}cleanupElements(this.svgElements);this.iconsRemoved=false;}/**
* Cleans up icons
*/_cleanupIcons(){if(this.iconsRemoved===false){prepareElements(this.svgElements);cleanupElements(this.svgElements);this.iconsRemoved=true;}}/**
* Create the HTML DOM for the DataAxis
*/show(){this.hidden=false;if(!this.dom.frame.parentNode){if(this.options.orientation==='left'){this.body.dom.left.appendChild(this.dom.frame);}else {this.body.dom.right.appendChild(this.dom.frame);}}if(!this.dom.lineContainer.parentNode){this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);}this.dom.lineContainer.style.display='block';}/**
* Create the HTML DOM for the DataAxis
*/hide(){this.hidden=true;if(this.dom.frame.parentNode){this.dom.frame.parentNode.removeChild(this.dom.frame);}this.dom.lineContainer.style.display='none';}/**
* Set a range (start and end)
* @param {number} start
* @param {number} end
*/setRange(start,end){this.range.start=start;this.range.end=end;}/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/redraw(){let resized=false;let activeGroups=0;// Make sure the line container adheres to the vertical scrolling.
this.dom.lineContainer.style.top=`${this.body.domProps.scrollTop}px`;for(const groupId in this.groups){if(this.groups.hasOwnProperty(groupId)){if(this.groups[groupId].visible===true&&(this.linegraphOptions.visibility[groupId]===undefined||this.linegraphOptions.visibility[groupId]===true)){activeGroups++;}}}if(this.amountOfGroups===0||activeGroups===0){this.hide();}else {this.show();this.height=Number(this.linegraphSVG.style.height.replace("px",""));// svg offsetheight did not work in firefox and explorer...
this.dom.lineContainer.style.height=`${this.height}px`;this.width=this.options.visible===true?Number(`${this.options.width}`.replace("px","")):0;const props=this.props;const frame=this.dom.frame;// update classname
frame.className='vis-data-axis';// calculate character width and height
this._calculateCharSize();const orientation=this.options.orientation;const showMinorLabels=this.options.showMinorLabels;const showMajorLabels=this.options.showMajorLabels;const backgroundHorizontalOffsetWidth=this.body.dom.backgroundHorizontal.offsetWidth;// determine the width and height of the elements for the axis
props.minorLabelHeight=showMinorLabels?props.minorCharHeight:0;props.majorLabelHeight=showMajorLabels?props.majorCharHeight:0;props.minorLineWidth=backgroundHorizontalOffsetWidth-this.lineOffset-this.width+2*this.options.minorLinesOffset;props.minorLineHeight=1;props.majorLineWidth=backgroundHorizontalOffsetWidth-this.lineOffset-this.width+2*this.options.majorLinesOffset;props.majorLineHeight=1;// take frame offline while updating (is almost twice as fast)
if(orientation==='left'){frame.style.top='0';frame.style.left='0';frame.style.bottom='';frame.style.width=`${this.width}px`;frame.style.height=`${this.height}px`;this.props.width=this.body.domProps.left.width;this.props.height=this.body.domProps.left.height;}else {// right
frame.style.top='';frame.style.bottom='0';frame.style.left='0';frame.style.width=`${this.width}px`;frame.style.height=`${this.height}px`;this.props.width=this.body.domProps.right.width;this.props.height=this.body.domProps.right.height;}resized=this._redrawLabels();resized=this._isResized()||resized;if(this.options.icons===true){this._redrawGroupIcons();}else {this._cleanupIcons();}this._redrawTitle(orientation);}return resized;}/**
* Repaint major and minor text labels and vertical grid lines
*
* @returns {boolean}
* @private
*/_redrawLabels(){let resized=false;prepareElements(this.DOMelements.lines);prepareElements(this.DOMelements.labels);const orientation=this.options['orientation'];const customRange=this.options[orientation].range!=undefined?this.options[orientation].range:{};//Override range with manual options:
let autoScaleEnd=true;if(customRange.max!=undefined){this.range.end=customRange.max;autoScaleEnd=false;}let autoScaleStart=true;if(customRange.min!=undefined){this.range.start=customRange.min;autoScaleStart=false;}this.scale=new DataScale(this.range.start,this.range.end,autoScaleStart,autoScaleEnd,this.dom.frame.offsetHeight,this.props.majorCharHeight,this.options.alignZeros,this.options[orientation].format);if(this.master===false&&this.masterAxis!=undefined){this.scale.followScale(this.masterAxis.scale);this.dom.lineContainer.style.display='none';}else {this.dom.lineContainer.style.display='block';}//Is updated in side-effect of _redrawLabel():
this.maxLabelSize=0;const lines=this.scale.getLines();lines.forEach(line=>{const y=line.y;const isMajor=line.major;if(this.options['showMinorLabels']&&isMajor===false){this._redrawLabel(y-2,line.val,orientation,'vis-y-axis vis-minor',this.props.minorCharHeight);}if(isMajor){if(y>=0){this._redrawLabel(y-2,line.val,orientation,'vis-y-axis vis-major',this.props.majorCharHeight);}}if(this.master===true){if(isMajor){this._redrawLine(y,orientation,'vis-grid vis-horizontal vis-major',this.options.majorLinesOffset,this.props.majorLineWidth);}else {this._redrawLine(y,orientation,'vis-grid vis-horizontal vis-minor',this.options.minorLinesOffset,this.props.minorLineWidth);}}});// Note that title is rotated, so we're using the height, not width!
let titleWidth=0;if(this.options[orientation].title!==undefined&&this.options[orientation].title.text!==undefined){titleWidth=this.props.titleCharHeight;}const offset=this.options.icons===true?Math.max(this.options.iconWidth,titleWidth)+this.options.labelOffsetX+15:titleWidth+this.options.labelOffsetX+15;// this will resize the yAxis to accommodate the labels.
if(this.maxLabelSize>this.width-offset&&this.options.visible===true){this.width=this.maxLabelSize+offset;this.options.width=`${this.width}px`;cleanupElements(this.DOMelements.lines);cleanupElements(this.DOMelements.labels);this.redraw();resized=true;}// this will resize the yAxis if it is too big for the labels.
else if(this.maxLabelSize<this.width-offset&&this.options.visible===true&&this.width>this.minWidth){this.width=Math.max(this.minWidth,this.maxLabelSize+offset);this.options.width=`${this.width}px`;cleanupElements(this.DOMelements.lines);cleanupElements(this.DOMelements.labels);this.redraw();resized=true;}else {cleanupElements(this.DOMelements.lines);cleanupElements(this.DOMelements.labels);resized=false;}return resized;}/**
* converts value
* @param {number} value
* @returns {number} converted number
*/convertValue(value){return this.scale.convertValue(value);}/**
* converts value
* @param {number} x
* @returns {number} screen value
*/screenToValue(x){return this.scale.screenToValue(x);}/**
* Create a label for the axis at position x
*
* @param {number} y
* @param {string} text
* @param {'top'|'right'|'bottom'|'left'} orientation
* @param {string} className
* @param {number} characterHeight
* @private
*/_redrawLabel(y,text,orientation,className,characterHeight){// reuse redundant label
const label=getDOMElement('div',this.DOMelements.labels,this.dom.frame);//this.dom.redundant.labels.shift();
label.className=className;label.innerHTML=availableUtils.xss(text);if(orientation==='left'){label.style.left=`-${this.options.labelOffsetX}px`;label.style.textAlign="right";}else {label.style.right=`-${this.options.labelOffsetX}px`;label.style.textAlign="left";}label.style.top=`${y-0.5*characterHeight+this.options.labelOffsetY}px`;text+='';const largestWidth=Math.max(this.props.majorCharWidth,this.props.minorCharWidth);if(this.maxLabelSize<text.length*largestWidth){this.maxLabelSize=text.length*largestWidth;}}/**
* Create a minor line for the axis at position y
* @param {number} y
* @param {'top'|'right'|'bottom'|'left'} orientation
* @param {string} className
* @param {number} offset
* @param {number} width
*/_redrawLine(y,orientation,className,offset,width){if(this.master===true){const line=getDOMElement('div',this.DOMelements.lines,this.dom.lineContainer);//this.dom.redundant.lines.shift();
line.className=className;line.innerHTML='';if(orientation==='left'){line.style.left=`${this.width-offset}px`;}else {line.style.right=`${this.width-offset}px`;}line.style.width=`${width}px`;line.style.top=`${y}px`;}}/**
* Create a title for the axis
* @private
* @param {'top'|'right'|'bottom'|'left'} orientation
*/_redrawTitle(orientation){prepareElements(this.DOMelements.title);// Check if the title is defined for this axes
if(this.options[orientation].title!==undefined&&this.options[orientation].title.text!==undefined){const title=getDOMElement('div',this.DOMelements.title,this.dom.frame);title.className=`vis-y-axis vis-title vis-${orientation}`;title.innerHTML=availableUtils.xss(this.options[orientation].title.text);// Add style - if provided
if(this.options[orientation].title.style!==undefined){availableUtils.addCssText(title,this.options[orientation].title.style);}if(orientation==='left'){title.style.left=`${this.props.titleCharHeight}px`;}else {title.style.right=`${this.props.titleCharHeight}px`;}title.style.width=`${this.height}px`;}// we need to clean up in case we did not use all elements.
cleanupElements(this.DOMelements.title);}/**
* Determine the size of text on the axis (both major and minor axis).
* The size is calculated only once and then cached in this.props.
* @private
*/_calculateCharSize(){// determine the char width and height on the minor axis
if(!('minorCharHeight'in this.props)){const textMinor=document.createTextNode('0');const measureCharMinor=document.createElement('div');measureCharMinor.className='vis-y-axis vis-minor vis-measure';measureCharMinor.appendChild(textMinor);this.dom.frame.appendChild(measureCharMinor);this.props.minorCharHeight=measureCharMinor.clientHeight;this.props.minorCharWidth=measureCharMinor.clientWidth;this.dom.frame.removeChild(measureCharMinor);}if(!('majorCharHeight'in this.props)){const textMajor=document.createTextNode('0');const measureCharMajor=document.createElement('div');measureCharMajor.className='vis-y-axis vis-major vis-measure';measureCharMajor.appendChild(textMajor);this.dom.frame.appendChild(measureCharMajor);this.props.majorCharHeight=measureCharMajor.clientHeight;this.props.majorCharWidth=measureCharMajor.clientWidth;this.dom.frame.removeChild(measureCharMajor);}if(!('titleCharHeight'in this.props)){const textTitle=document.createTextNode('0');const measureCharTitle=document.createElement('div');measureCharTitle.className='vis-y-axis vis-title vis-measure';measureCharTitle.appendChild(textTitle);this.dom.frame.appendChild(measureCharTitle);this.props.titleCharHeight=measureCharTitle.clientHeight;this.props.titleCharWidth=measureCharTitle.clientWidth;this.dom.frame.removeChild(measureCharTitle);}}}/**
*
* @param {number | string} groupId
* @param {Object} options // TODO: Describe options
*
* @constructor Points
*/function Points(groupId,options){// eslint-disable-line no-unused-vars
}/**
* draw the data points
*
* @param {Array} dataset
* @param {GraphGroup} group
* @param {Object} framework | SVG DOM element
* @param {number} [offset]
*/Points.draw=function(dataset,group,framework,offset){offset=offset||0;var callback=getCallback(framework,group);for(var i=0;i<dataset.length;i++){if(!callback){// draw the point the simple way.
drawPoint(dataset[i].screen_x+offset,dataset[i].screen_y,getGroupTemplate(group),framework.svgElements,framework.svg,dataset[i].label);}else {var callbackResult=callback(dataset[i],group);// result might be true, false or an object
if(callbackResult===true||typeof callbackResult==='object'){drawPoint(dataset[i].screen_x+offset,dataset[i].screen_y,getGroupTemplate(group,callbackResult),framework.svgElements,framework.svg,dataset[i].label);}}}};Points.drawIcon=function(group,x,y,iconWidth,iconHeight,framework){var fillHeight=iconHeight*0.5;var outline=getSVGElement("rect",framework.svgElements,framework.svg);outline.setAttributeNS(null,"x",x);outline.setAttributeNS(null,"y",y-fillHeight);outline.setAttributeNS(null,"width",iconWidth);outline.setAttributeNS(null,"height",2*fillHeight);outline.setAttributeNS(null,"class","vis-outline");//Don't call callback on icon
drawPoint(x+0.5*iconWidth,y,getGroupTemplate(group),framework.svgElements,framework.svg);};/**
*
* @param {vis.Group} group
* @param {any} callbackResult
* @returns {{style: *, styles: (*|string), size: *, className: *}}
*/function getGroupTemplate(group,callbackResult){callbackResult=typeof callbackResult==='undefined'?{}:callbackResult;return {style:callbackResult.style||group.options.drawPoints.style,styles:callbackResult.styles||group.options.drawPoints.styles,size:callbackResult.size||group.options.drawPoints.size,className:callbackResult.className||group.className};}/**
*
* @param {Object} framework | SVG DOM element
* @param {vis.Group} group
* @returns {function}
*/function getCallback(framework,group){var callback=undefined;// check for the graph2d onRender
if(framework.options&&framework.options.drawPoints&&framework.options.drawPoints.onRender&&typeof framework.options.drawPoints.onRender=='function'){callback=framework.options.drawPoints.onRender;}// override it with the group onRender if defined
if(group.group.options&&group.group.options.drawPoints&&group.group.options.drawPoints.onRender&&typeof group.group.options.drawPoints.onRender=='function'){callback=group.group.options.drawPoints.onRender;}return callback;}/**
*
* @param {vis.GraphGroup.id} groupId
* @param {Object} options // TODO: Describe options
* @constructor Bargraph
*/function Bargraph(groupId,options){// eslint-disable-line no-unused-vars
}Bargraph.drawIcon=function(group,x,y,iconWidth,iconHeight,framework){var fillHeight=iconHeight*0.5;var outline=getSVGElement("rect",framework.svgElements,framework.svg);outline.setAttributeNS(null,"x",x);outline.setAttributeNS(null,"y",y-fillHeight);outline.setAttributeNS(null,"width",iconWidth);outline.setAttributeNS(null,"height",2*fillHeight);outline.setAttributeNS(null,"class","vis-outline");var barWidth=Math.round(0.3*iconWidth);var originalWidth=group.options.barChart.width;var scale=originalWidth/barWidth;var bar1Height=Math.round(0.4*iconHeight);var bar2Height=Math.round(0.75*iconHeight);var offset=Math.round((iconWidth-2*barWidth)/3);drawBar(x+0.5*barWidth+offset,y+fillHeight-bar1Height-1,barWidth,bar1Height,group.className+' vis-bar',framework.svgElements,framework.svg,group.style);drawBar(x+1.5*barWidth+offset+2,y+fillHeight-bar2Height-1,barWidth,bar2Height,group.className+' vis-bar',framework.svgElements,framework.svg,group.style);if(group.options.drawPoints.enabled==true){var groupTemplate={style:group.options.drawPoints.style,styles:group.options.drawPoints.styles,size:group.options.drawPoints.size/scale,className:group.className};drawPoint(x+0.5*barWidth+offset,y+fillHeight-bar1Height-1,groupTemplate,framework.svgElements,framework.svg);drawPoint(x+1.5*barWidth+offset+2,y+fillHeight-bar2Height-1,groupTemplate,framework.svgElements,framework.svg);}};/**
* draw a bar graph
*
* @param {Array.<vis.GraphGroup.id>} groupIds
* @param {Object} processedGroupData
* @param {{svg: Object, svgElements: Array.<Object>, options: Object, groups: Array.<vis.Group>}} framework
*/Bargraph.draw=function(groupIds,processedGroupData,framework){var combinedData=[];var intersections={};var coreDistance;var key,drawData;var group;var i,j;var barPoints=0;// combine all barchart data
for(i=0;i<groupIds.length;i++){group=framework.groups[groupIds[i]];if(group.options.style==='bar'){if(group.visible===true&&(framework.options.groups.visibility[groupIds[i]]===undefined||framework.options.groups.visibility[groupIds[i]]===true)){for(j=0;j<processedGroupData[groupIds[i]].length;j++){combinedData.push({screen_x:processedGroupData[groupIds[i]][j].screen_x,screen_end:processedGroupData[groupIds[i]][j].screen_end,screen_y:processedGroupData[groupIds[i]][j].screen_y,x:processedGroupData[groupIds[i]][j].x,end:processedGroupData[groupIds[i]][j].end,y:processedGroupData[groupIds[i]][j].y,groupId:groupIds[i],label:processedGroupData[groupIds[i]][j].label});barPoints+=1;}}}}if(barPoints===0){return;}// sort by time and by group
combinedData.sort(function(a,b){if(a.screen_x===b.screen_x){return a.groupId<b.groupId?-1:1;}else {return a.screen_x-b.screen_x;}});// get intersections
Bargraph._getDataIntersections(intersections,combinedData);// plot barchart
for(i=0;i<combinedData.length;i++){group=framework.groups[combinedData[i].groupId];var minWidth=group.options.barChart.minWidth!=undefined?group.options.barChart.minWidth:0.1*group.options.barChart.width;key=combinedData[i].screen_x;var heightOffset=0;if(intersections[key]===undefined){if(i+1<combinedData.length){coreDistance=Math.abs(combinedData[i+1].screen_x-key);}drawData=Bargraph._getSafeDrawData(coreDistance,group,minWidth);}else {var nextKey=i+(intersections[key].amount-intersections[key].resolved);if(nextKey<combinedData.length){coreDistance=Math.abs(combinedData[nextKey].screen_x-key);}drawData=Bargraph._getSafeDrawData(coreDistance,group,minWidth);intersections[key].resolved+=1;if(group.options.stack===true&&group.options.excludeFromStacking!==true){if(combinedData[i].screen_y<group.zeroPosition){heightOffset=intersections[key].accumulatedNegative;intersections[key].accumulatedNegative+=group.zeroPosition-combinedData[i].screen_y;}else {heightOffset=intersections[key].accumulatedPositive;intersections[key].accumulatedPositive+=group.zeroPosition-combinedData[i].screen_y;}}else if(group.options.barChart.sideBySide===true){drawData.width=drawData.width/intersections[key].amount;drawData.offset+=intersections[key].resolved*drawData.width-0.5*drawData.width*(intersections[key].amount+1);}}let dataWidth=drawData.width;let start=combinedData[i].screen_x;// are we drawing explicit boxes? (we supplied an end value)
if(combinedData[i].screen_end!=undefined){dataWidth=combinedData[i].screen_end-combinedData[i].screen_x;start+=dataWidth*0.5;}else {start+=drawData.offset;}drawBar(start,combinedData[i].screen_y-heightOffset,dataWidth,group.zeroPosition-combinedData[i].screen_y,group.className+' vis-bar',framework.svgElements,framework.svg,group.style);// draw points
if(group.options.drawPoints.enabled===true){let pointData={screen_x:combinedData[i].screen_x,screen_y:combinedData[i].screen_y-heightOffset,x:combinedData[i].x,y:combinedData[i].y,groupId:combinedData[i].groupId,label:combinedData[i].label};Points.draw([pointData],group,framework,drawData.offset);//DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg);
}}};/**
* Fill the intersections object with counters of how many datapoints share the same x coordinates
* @param {Object} intersections
* @param {Array.<Object>} combinedData
* @private
*/Bargraph._getDataIntersections=function(intersections,combinedData){// get intersections
var coreDistance;for(var i=0;i<combinedData.length;i++){if(i+1<combinedData.length){coreDistance=Math.abs(combinedData[i+1].screen_x-combinedData[i].screen_x);}if(i>0){coreDistance=Math.min(coreDistance,Math.abs(combinedData[i-1].screen_x-combinedData[i].screen_x));}if(coreDistance===0){if(intersections[combinedData[i].screen_x]===undefined){intersections[combinedData[i].screen_x]={amount:0,resolved:0,accumulatedPositive:0,accumulatedNegative:0};}intersections[combinedData[i].screen_x].amount+=1;}}};/**
* Get the width and offset for bargraphs based on the coredistance between datapoints
*
* @param {number} coreDistance
* @param {vis.Group} group
* @param {number} minWidth
* @returns {{width: number, offset: number}}
* @private
*/Bargraph._getSafeDrawData=function(coreDistance,group,minWidth){var width,offset;if(coreDistance<group.options.barChart.width&&coreDistance>0){width=coreDistance<minWidth?minWidth:coreDistance;offset=0;// recalculate offset with the new width;
if(group.options.barChart.align==='left'){offset-=0.5*coreDistance;}else if(group.options.barChart.align==='right'){offset+=0.5*coreDistance;}}else {// default settings
width=group.options.barChart.width;offset=0;if(group.options.barChart.align==='left'){offset-=0.5*group.options.barChart.width;}else if(group.options.barChart.align==='right'){offset+=0.5*group.options.barChart.width;}}return {width:width,offset:offset};};Bargraph.getStackedYRange=function(combinedData,groupRanges,groupIds,groupLabel,orientation){if(combinedData.length>0){// sort by time and by group
combinedData.sort(function(a,b){if(a.screen_x===b.screen_x){return a.groupId<b.groupId?-1:1;}else {return a.screen_x-b.screen_x;}});var intersections={};Bargraph._getDataIntersections(intersections,combinedData);groupRanges[groupLabel]=Bargraph._getStackedYRange(intersections,combinedData);groupRanges[groupLabel].yAxisOrientation=orientation;groupIds.push(groupLabel);}};Bargraph._getStackedYRange=function(intersections,combinedData){var key;var yMin=combinedData[0].screen_y;var yMax=combinedData[0].screen_y;for(var i=0;i<combinedData.length;i++){key=combinedData[i].screen_x;if(intersections[key]===undefined){yMin=yMin>combinedData[i].screen_y?combinedData[i].screen_y:yMin;yMax=yMax<combinedData[i].screen_y?combinedData[i].screen_y:yMax;}else {if(combinedData[i].screen_y<0){intersections[key].accumulatedNegative+=combinedData[i].screen_y;}else {intersections[key].accumulatedPositive+=combinedData[i].screen_y;}}}for(var xpos in intersections){if(intersections.hasOwnProperty(xpos)){yMin=yMin>intersections[xpos].accumulatedNegative?intersections[xpos].accumulatedNegative:yMin;yMin=yMin>intersections[xpos].accumulatedPositive?intersections[xpos].accumulatedPositive:yMin;yMax=yMax<intersections[xpos].accumulatedNegative?intersections[xpos].accumulatedNegative:yMax;yMax=yMax<intersections[xpos].accumulatedPositive?intersections[xpos].accumulatedPositive:yMax;}}return {min:yMin,max:yMax};};/**
*
* @param {vis.GraphGroup.id} groupId
* @param {Object} options // TODO: Describe options
* @constructor Line
*/function Line(groupId,options){// eslint-disable-line no-unused-vars
}Line.calcPath=function(dataset,group){if(dataset!=null){if(dataset.length>0){var d=[];// construct path from dataset
if(group.options.interpolation.enabled==true){d=Line._catmullRom(dataset,group);}else {d=Line._linear(dataset);}return d;}}};Line.drawIcon=function(group,x,y,iconWidth,iconHeight,framework){var fillHeight=iconHeight*0.5;var path,fillPath;var outline=getSVGElement("rect",framework.svgElements,framework.svg);outline.setAttributeNS(null,"x",x);outline.setAttributeNS(null,"y",y-fillHeight);outline.setAttributeNS(null,"width",iconWidth);outline.setAttributeNS(null,"height",2*fillHeight);outline.setAttributeNS(null,"class","vis-outline");path=getSVGElement("path",framework.svgElements,framework.svg);path.setAttributeNS(null,"class",group.className);if(group.style!==undefined){path.setAttributeNS(null,"style",group.style);}path.setAttributeNS(null,"d","M"+x+","+y+" L"+(x+iconWidth)+","+y+"");if(group.options.shaded.enabled==true){fillPath=getSVGElement("path",framework.svgElements,framework.svg);if(group.options.shaded.orientation=='top'){fillPath.setAttributeNS(null,"d","M"+x+", "+(y-fillHeight)+"L"+x+","+y+" L"+(x+iconWidth)+","+y+" L"+(x+iconWidth)+","+(y-fillHeight));}else {fillPath.setAttributeNS(null,"d","M"+x+","+y+" "+"L"+x+","+(y+fillHeight)+" "+"L"+(x+iconWidth)+","+(y+fillHeight)+"L"+(x+iconWidth)+","+y);}fillPath.setAttributeNS(null,"class",group.className+" vis-icon-fill");if(group.options.shaded.style!==undefined&&group.options.shaded.style!==""){fillPath.setAttributeNS(null,"style",group.options.shaded.style);}}if(group.options.drawPoints.enabled==true){var groupTemplate={style:group.options.drawPoints.style,styles:group.options.drawPoints.styles,size:group.options.drawPoints.size,className:group.className};drawPoint(x+0.5*iconWidth,y,groupTemplate,framework.svgElements,framework.svg);}};Line.drawShading=function(pathArray,group,subPathArray,framework){// append shading to the path
if(group.options.shaded.enabled==true){var svgHeight=Number(framework.svg.style.height.replace('px',''));var fillPath=getSVGElement('path',framework.svgElements,framework.svg);var type="L";if(group.options.interpolation.enabled==true){type="C";}var dFill;var zero=0;if(group.options.shaded.orientation=='top'){zero=0;}else if(group.options.shaded.orientation=='bottom'){zero=svgHeight;}else {zero=Math.min(Math.max(0,group.zeroPosition),svgHeight);}if(group.options.shaded.orientation=='group'&&subPathArray!=null&&subPathArray!=undefined){dFill='M'+pathArray[0][0]+","+pathArray[0][1]+" "+this.serializePath(pathArray,type,false)+' L'+subPathArray[subPathArray.length-1][0]+","+subPathArray[subPathArray.length-1][1]+" "+this.serializePath(subPathArray,type,true)+subPathArray[0][0]+","+subPathArray[0][1]+" Z";}else {dFill='M'+pathArray[0][0]+","+pathArray[0][1]+" "+this.serializePath(pathArray,type,false)+' V'+zero+' H'+pathArray[0][0]+" Z";}fillPath.setAttributeNS(null,'class',group.className+' vis-fill');if(group.options.shaded.style!==undefined){fillPath.setAttributeNS(null,'style',group.options.shaded.style);}fillPath.setAttributeNS(null,'d',dFill);}};/**
* draw a line graph
*
* @param {Array.<Object>} pathArray
* @param {vis.Group} group
* @param {{svg: Object, svgElements: Array.<Object>, options: Object, groups: Array.<vis.Group>}} framework
*/Line.draw=function(pathArray,group,framework){if(pathArray!=null&&pathArray!=undefined){var path=getSVGElement('path',framework.svgElements,framework.svg);path.setAttributeNS(null,"class",group.className);if(group.style!==undefined){path.setAttributeNS(null,"style",group.style);}var type="L";if(group.options.interpolation.enabled==true){type="C";}// copy properties to path for drawing.
path.setAttributeNS(null,'d','M'+pathArray[0][0]+","+pathArray[0][1]+" "+this.serializePath(pathArray,type,false));}};Line.serializePath=function(pathArray,type,inverse){if(pathArray.length<2){//Too little data to create a path.
return "";}var d=type;var i;if(inverse){for(i=pathArray.length-2;i>0;i--){d+=pathArray[i][0]+","+pathArray[i][1]+" ";}}else {for(i=1;i<pathArray.length;i++){d+=pathArray[i][0]+","+pathArray[i][1]+" ";}}return d;};/**
* This uses an uniform parametrization of the interpolation algorithm:
* 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al.
* @param {Array.<Object>} data
* @returns {string}
* @private
*/Line._catmullRomUniform=function(data){// catmull rom
var p0,p1,p2,p3,bp1,bp2;var d=[];d.push([Math.round(data[0].screen_x),Math.round(data[0].screen_y)]);var normalization=1/6;var length=data.length;for(var i=0;i<length-1;i++){p0=i==0?data[0]:data[i-1];p1=data[i];p2=data[i+1];p3=i+2<length?data[i+2]:p2;// Catmull-Rom to Cubic Bezier conversion matrix
// 0 1 0 0
// -1/6 1 1/6 0
// 0 1/6 1 -1/6
// 0 0 1 0
// bp0 = { x: p1.x, y: p1.y };
bp1={screen_x:(-p0.screen_x+6*p1.screen_x+p2.screen_x)*normalization,screen_y:(-p0.screen_y+6*p1.screen_y+p2.screen_y)*normalization};bp2={screen_x:(p1.screen_x+6*p2.screen_x-p3.screen_x)*normalization,screen_y:(p1.screen_y+6*p2.screen_y-p3.screen_y)*normalization};// bp0 = { x: p2.x, y: p2.y };
d.push([bp1.screen_x,bp1.screen_y]);d.push([bp2.screen_x,bp2.screen_y]);d.push([p2.screen_x,p2.screen_y]);}return d;};/**
* This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
* By default, the centripetal parameterization is used because this gives the nicest results.
* These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
*
* One optimization can be used to reuse distances since this is a sliding window approach.
* @param {Array.<Object>} data
* @param {vis.GraphGroup} group
* @returns {string}
* @private
*/Line._catmullRom=function(data,group){var alpha=group.options.interpolation.alpha;if(alpha==0||alpha===undefined){return this._catmullRomUniform(data);}else {var p0,p1,p2,p3,bp1,bp2,d1,d2,d3,A,B,N,M;var d3powA,d2powA,d3pow2A,d2pow2A,d1pow2A,d1powA;var d=[];d.push([Math.round(data[0].screen_x),Math.round(data[0].screen_y)]);var length=data.length;for(var i=0;i<length-1;i++){p0=i==0?data[0]:data[i-1];p1=data[i];p2=data[i+1];p3=i+2<length?data[i+2]:p2;d1=Math.sqrt(Math.pow(p0.screen_x-p1.screen_x,2)+Math.pow(p0.screen_y-p1.screen_y,2));d2=Math.sqrt(Math.pow(p1.screen_x-p2.screen_x,2)+Math.pow(p1.screen_y-p2.screen_y,2));d3=Math.sqrt(Math.pow(p2.screen_x-p3.screen_x,2)+Math.pow(p2.screen_y-p3.screen_y,2));// Catmull-Rom to Cubic Bezier conversion matrix
// A = 2d1^2a + 3d1^a * d2^a + d3^2a
// B = 2d3^2a + 3d3^a * d2^a + d2^2a
// [ 0 1 0 0 ]
// [ -d2^2a /N A/N d1^2a /N 0 ]
// [ 0 d3^2a /M B/M -d2^2a /M ]
// [ 0 0 1 0 ]
d3powA=Math.pow(d3,alpha);d3pow2A=Math.pow(d3,2*alpha);d2powA=Math.pow(d2,alpha);d2pow2A=Math.pow(d2,2*alpha);d1powA=Math.pow(d1,alpha);d1pow2A=Math.pow(d1,2*alpha);A=2*d1pow2A+3*d1powA*d2powA+d2pow2A;B=2*d3pow2A+3*d3powA*d2powA+d2pow2A;N=3*d1powA*(d1powA+d2powA);if(N>0){N=1/N;}M=3*d3powA*(d3powA+d2powA);if(M>0){M=1/M;}bp1={screen_x:(-d2pow2A*p0.screen_x+A*p1.screen_x+d1pow2A*p2.screen_x)*N,screen_y:(-d2pow2A*p0.screen_y+A*p1.screen_y+d1pow2A*p2.screen_y)*N};bp2={screen_x:(d3pow2A*p1.screen_x+B*p2.screen_x-d2pow2A*p3.screen_x)*M,screen_y:(d3pow2A*p1.screen_y+B*p2.screen_y-d2pow2A*p3.screen_y)*M};if(bp1.screen_x==0&&bp1.screen_y==0){bp1=p1;}if(bp2.screen_x==0&&bp2.screen_y==0){bp2=p2;}d.push([bp1.screen_x,bp1.screen_y]);d.push([bp2.screen_x,bp2.screen_y]);d.push([p2.screen_x,p2.screen_y]);}return d;}};/**
* this generates the SVG path for a linear drawing between datapoints.
* @param {Array.<Object>} data
* @returns {string}
* @private
*/Line._linear=function(data){// linear
var d=[];for(var i=0;i<data.length;i++){d.push([data[i].screen_x,data[i].screen_y]);}return d;};/**
* /**
* @param {object} group | the object of the group from the dataset
* @param {string} groupId | ID of the group
* @param {object} options | the default options
* @param {array} groupsUsingDefaultStyles | this array has one entree.
* It is passed as an array so it is passed by reference.
* It enumerates through the default styles
* @constructor GraphGroup
*/function GraphGroup(group,groupId,options,groupsUsingDefaultStyles){this.id=groupId;var fields=['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','interpolation','zIndex','excludeFromStacking','excludeFromLegend'];this.options=availableUtils.selectiveBridgeObject(fields,options);this.usingDefaultStyle=group.className===undefined;this.groupsUsingDefaultStyles=groupsUsingDefaultStyles;this.zeroPosition=0;this.update(group);if(this.usingDefaultStyle==true){this.groupsUsingDefaultStyles[0]+=1;}this.itemsData=[];this.visible=group.visible===undefined?true:group.visible;}/**
* this loads a reference to all items in this group into this group.
* @param {array} items
*/GraphGroup.prototype.setItems=function(items){if(items!=null){this.itemsData=items;if(this.options.sort==true){availableUtils.insertSort(this.itemsData,function(a,b){return a.x>b.x?1:-1;});}}else {this.itemsData=[];}};GraphGroup.prototype.getItems=function(){return this.itemsData;};/**
* this is used for barcharts and shading, this way, we only have to calculate it once.
* @param {number} pos
*/GraphGroup.prototype.setZeroPosition=function(pos){this.zeroPosition=pos;};/**
* set the options of the graph group over the default options.
* @param {Object} options
*/GraphGroup.prototype.setOptions=function(options){if(options!==undefined){var fields=['sampling','style','sort','yAxisOrientation','barChart','zIndex','excludeFromStacking','excludeFromLegend'];availableUtils.selectiveDeepExtend(fields,this.options,options);// if the group's drawPoints is a function delegate the callback to the onRender property
if(typeof options.drawPoints=='function'){options.drawPoints={onRender:options.drawPoints};}availableUtils.mergeOptions(this.options,options,'interpolation');availableUtils.mergeOptions(this.options,options,'drawPoints');availableUtils.mergeOptions(this.options,options,'shaded');if(options.interpolation){if(typeof options.interpolation=='object'){if(options.interpolation.parametrization){if(options.interpolation.parametrization=='uniform'){this.options.interpolation.alpha=0;}else if(options.interpolation.parametrization=='chordal'){this.options.interpolation.alpha=1.0;}else {this.options.interpolation.parametrization='centripetal';this.options.interpolation.alpha=0.5;}}}}}};/**
* this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
* @param {vis.Group} group
*/GraphGroup.prototype.update=function(group){this.group=group;this.content=group.content||'graph';this.className=group.className||this.className||'vis-graph-group'+this.groupsUsingDefaultStyles[0]%10;this.visible=group.visible===undefined?true:group.visible;this.style=group.style;this.setOptions(group.options);};/**
* return the legend entree for this group.
*
* @param {number} iconWidth
* @param {number} iconHeight
* @param {{svg: (*|Element), svgElements: Object, options: Object, groups: Array.<Object>}} framework
* @param {number} x
* @param {number} y
* @returns {{icon: (*|Element), label: (*|string), orientation: *}}
*/GraphGroup.prototype.getLegend=function(iconWidth,iconHeight,framework,x,y){if(framework==undefined||framework==null){var svg=document.createElementNS('http://www.w3.org/2000/svg',"svg");framework={svg:svg,svgElements:{},options:this.options,groups:[this]};}if(x==undefined||x==null){x=0;}if(y==undefined||y==null){y=0.5*iconHeight;}switch(this.options.style){case"line":Line.drawIcon(this,x,y,iconWidth,iconHeight,framework);break;case"points"://explicit no break
case"point":Points.drawIcon(this,x,y,iconWidth,iconHeight,framework);break;case"bar":Bargraph.drawIcon(this,x,y,iconWidth,iconHeight,framework);break;}return {icon:framework.svg,label:this.content,orientation:this.options.yAxisOrientation};};GraphGroup.prototype.getYRange=function(groupData){var yMin=groupData[0].y;var yMax=groupData[0].y;for(var j=0;j<groupData.length;j++){yMin=yMin>groupData[j].y?groupData[j].y:yMin;yMax=yMax<groupData[j].y?groupData[j].y:yMax;}return {min:yMin,max:yMax,yAxisOrientation:this.options.yAxisOrientation};};/**
* Legend for Graph2d
*
* @param {vis.Graph2d.body} body
* @param {vis.Graph2d.options} options
* @param {number} side
* @param {vis.LineGraph.options} linegraphOptions
* @constructor Legend
* @extends Component
*/function Legend(body,options,side,linegraphOptions){this.body=body;this.defaultOptions={enabled:false,icons:true,iconSize:20,iconSpacing:6,left:{visible:true,position:'top-left'// top/bottom - left,center,right
},right:{visible:true,position:'top-right'// top/bottom - left,center,right
}};this.side=side;this.options=availableUtils.extend({},this.defaultOptions);this.linegraphOptions=linegraphOptions;this.svgElements={};this.dom={};this.groups={};this.amountOfGroups=0;this._create();this.framework={svg:this.svg,svgElements:this.svgElements,options:this.options,groups:this.groups};this.setOptions(options);}Legend.prototype=new Component();Legend.prototype.clear=function(){this.groups={};this.amountOfGroups=0;};Legend.prototype.addGroup=function(label,graphOptions){// Include a group only if the group option 'excludeFromLegend: false' is not set.
if(graphOptions.options.excludeFromLegend!=true){if(!this.groups.hasOwnProperty(label)){this.groups[label]=graphOptions;}this.amountOfGroups+=1;}};Legend.prototype.updateGroup=function(label,graphOptions){this.groups[label]=graphOptions;};Legend.prototype.removeGroup=function(label){if(this.groups.hasOwnProperty(label)){delete this.groups[label];this.amountOfGroups-=1;}};Legend.prototype._create=function(){this.dom.frame=document.createElement('div');this.dom.frame.className='vis-legend';this.dom.frame.style.position="absolute";this.dom.frame.style.top="10px";this.dom.frame.style.display="block";this.dom.textArea=document.createElement('div');this.dom.textArea.className='vis-legend-text';this.dom.textArea.style.position="relative";this.dom.textArea.style.top="0px";this.svg=document.createElementNS('http://www.w3.org/2000/svg',"svg");this.svg.style.position='absolute';this.svg.style.top=0+'px';this.svg.style.width=this.options.iconSize+5+'px';this.svg.style.height='100%';this.dom.frame.appendChild(this.svg);this.dom.frame.appendChild(this.dom.textArea);};/**
* Hide the component from the DOM
*/Legend.prototype.hide=function(){// remove the frame containing the items
if(this.dom.frame.parentNode){this.dom.frame.parentNode.removeChild(this.dom.frame);}};/**
* Show the component in the DOM (when not already visible).
*/Legend.prototype.show=function(){// show frame containing the items
if(!this.dom.frame.parentNode){this.body.dom.center.appendChild(this.dom.frame);}};Legend.prototype.setOptions=function(options){var fields=['enabled','orientation','icons','left','right'];availableUtils.selectiveDeepExtend(fields,this.options,options);};Legend.prototype.redraw=function(){var activeGroups=0;var groupArray=Object.keys(this.groups);groupArray.sort(function(a,b){return a<b?-1:1;});for(var i=0;i<groupArray.length;i++){var groupId=groupArray[i];if(this.groups[groupId].visible==true&&(this.linegraphOptions.visibility[groupId]===undefined||this.linegraphOptions.visibility[groupId]==true)){activeGroups++;}}if(this.options[this.side].visible==false||this.amountOfGroups==0||this.options.enabled==false||activeGroups==0){this.hide();}else {this.show();if(this.options[this.side].position=='top-left'||this.options[this.side].position=='bottom-left'){this.dom.frame.style.left='4px';this.dom.frame.style.textAlign="left";this.dom.textArea.style.textAlign="left";this.dom.textArea.style.left=this.options.iconSize+15+'px';this.dom.textArea.style.right='';this.svg.style.left=0+'px';this.svg.style.right='';}else {this.dom.frame.style.right='4px';this.dom.frame.style.textAlign="right";this.dom.textArea.style.textAlign="right";this.dom.textArea.style.right=this.options.iconSize+15+'px';this.dom.textArea.style.left='';this.svg.style.right=0+'px';this.svg.style.left='';}if(this.options[this.side].position=='top-left'||this.options[this.side].position=='top-right'){this.dom.frame.style.top=4-Number(this.body.dom.center.style.top.replace("px",""))+'px';this.dom.frame.style.bottom='';}else {var scrollableHeight=this.body.domProps.center.height-this.body.domProps.centerContainer.height;this.dom.frame.style.bottom=4+scrollableHeight+Number(this.body.dom.center.style.top.replace("px",""))+'px';this.dom.frame.style.top='';}if(this.options.icons==false){this.dom.frame.style.width=this.dom.textArea.offsetWidth+10+'px';this.dom.textArea.style.right='';this.dom.textArea.style.left='';this.svg.style.width='0px';}else {this.dom.frame.style.width=this.options.iconSize+15+this.dom.textArea.offsetWidth+10+'px';this.drawLegendIcons();}var content='';for(i=0;i<groupArray.length;i++){groupId=groupArray[i];if(this.groups[groupId].visible==true&&(this.linegraphOptions.visibility[groupId]===undefined||this.linegraphOptions.visibility[groupId]==true)){content+=this.groups[groupId].content+'<br />';}}this.dom.textArea.innerHTML=availableUtils.xss(content);this.dom.textArea.style.lineHeight=0.75*this.options.iconSize+this.options.iconSpacing+'px';}};Legend.prototype.drawLegendIcons=function(){if(this.dom.frame.parentNode){var groupArray=Object.keys(this.groups);groupArray.sort(function(a,b){return a<b?-1:1;});// this resets the elements so the order is maintained
resetElements(this.svgElements);var padding=window.getComputedStyle(this.dom.frame).paddingTop;var iconOffset=Number(padding.replace('px',''));var x=iconOffset;var iconWidth=this.options.iconSize;var iconHeight=0.75*this.options.iconSize;var y=iconOffset+0.5*iconHeight+3;this.svg.style.width=iconWidth+5+iconOffset+'px';for(var i=0;i<groupArray.length;i++){var groupId=groupArray[i];if(this.groups[groupId].visible==true&&(this.linegraphOptions.visibility[groupId]===undefined||this.linegraphOptions.visibility[groupId]==true)){this.groups[groupId].getLegend(iconWidth,iconHeight,this.framework,x,y);y+=iconHeight+this.options.iconSpacing;}}}};var UNGROUPED='__ungrouped__';// reserved group id for ungrouped items
/**
* This is the constructor of the LineGraph. It requires a Timeline body and options.
*
* @param {vis.Timeline.body} body
* @param {Object} options
* @constructor LineGraph
* @extends Component
*/function LineGraph(body,options){this.id=v4();this.body=body;this.defaultOptions={yAxisOrientation:'left',defaultGroup:'default',sort:true,sampling:true,stack:false,graphHeight:'400px',shaded:{enabled:false,orientation:'bottom'// top, bottom, zero
},style:'line',// line, bar
barChart:{width:50,sideBySide:false,align:'center'// left, center, right
},interpolation:{enabled:true,parametrization:'centripetal',// uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
alpha:0.5},drawPoints:{enabled:true,size:6,style:'square'// square, circle
},dataAxis:{},//Defaults are done on DataAxis level
legend:{},//Defaults are done on Legend level
groups:{visibility:{}}};// options is shared by this lineGraph and all its items
this.options=availableUtils.extend({},this.defaultOptions);this.dom={};this.props={};this.hammer=null;this.groups={};this.abortedGraphUpdate=false;this.updateSVGheight=false;this.updateSVGheightOnResize=false;this.forceGraphUpdate=true;var me=this;this.itemsData=null;// DataSet
this.groupsData=null;// DataSet
// listeners for the DataSet of the items
this.itemListeners={'add':function(event,params,senderId){// eslint-disable-line no-unused-vars
me._onAdd(params.items);},'update':function(event,params,senderId){// eslint-disable-line no-unused-vars
me._onUpdate(params.items);},'remove':function(event,params,senderId){// eslint-disable-line no-unused-vars
me._onRemove(params.items);}};// listeners for the DataSet of the groups
this.groupListeners={'add':function(event,params,senderId){// eslint-disable-line no-unused-vars
me._onAddGroups(params.items);},'update':function(event,params,senderId){// eslint-disable-line no-unused-vars
me._onUpdateGroups(params.items);},'remove':function(event,params,senderId){// eslint-disable-line no-unused-vars
me._onRemoveGroups(params.items);}};this.items={};// object with an Item for every data item
this.selection=[];// list with the ids of all selected nodes
this.lastStart=this.body.range.start;this.touchParams={};// stores properties while dragging
this.svgElements={};this.setOptions(options);this.groupsUsingDefaultStyles=[0];this.body.emitter.on('rangechanged',function(){me.svg.style.left=availableUtils.option.asSize(-me.props.width);me.forceGraphUpdate=true;//Is this local redraw necessary? (Core also does a change event!)
me.redraw.call(me);});// create the HTML DOM
this._create();this.framework={svg:this.svg,svgElements:this.svgElements,options:this.options,groups:this.groups};}LineGraph.prototype=new Component();/**
* Create the HTML DOM for the ItemSet
*/LineGraph.prototype._create=function(){var frame=document.createElement('div');frame.className='vis-line-graph';this.dom.frame=frame;// create svg element for graph drawing.
this.svg=document.createElementNS('http://www.w3.org/2000/svg','svg');this.svg.style.position='relative';this.svg.style.height=(''+this.options.graphHeight).replace('px','')+'px';this.svg.style.display='block';frame.appendChild(this.svg);// data axis
this.options.dataAxis.orientation='left';this.yAxisLeft=new DataAxis(this.body,this.options.dataAxis,this.svg,this.options.groups);this.options.dataAxis.orientation='right';this.yAxisRight=new DataAxis(this.body,this.options.dataAxis,this.svg,this.options.groups);delete this.options.dataAxis.orientation;// legends
this.legendLeft=new Legend(this.body,this.options.legend,'left',this.options.groups);this.legendRight=new Legend(this.body,this.options.legend,'right',this.options.groups);this.show();};/**
* set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
* @param {object} options
*/LineGraph.prototype.setOptions=function(options){if(options){var fields=['sampling','defaultGroup','stack','height','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort','groups'];if(options.graphHeight===undefined&&options.height!==undefined){this.updateSVGheight=true;this.updateSVGheightOnResize=true;}else if(this.body.domProps.centerContainer.height!==undefined&&options.graphHeight!==undefined){if(parseInt((options.graphHeight+'').replace("px",''))<this.body.domProps.centerContainer.height){this.updateSVGheight=true;}}availableUtils.selectiveDeepExtend(fields,this.options,options);availableUtils.mergeOptions(this.options,options,'interpolation');availableUtils.mergeOptions(this.options,options,'drawPoints');availableUtils.mergeOptions(this.options,options,'shaded');availableUtils.mergeOptions(this.options,options,'legend');if(options.interpolation){if(typeof options.interpolation=='object'){if(options.interpolation.parametrization){if(options.interpolation.parametrization=='uniform'){this.options.interpolation.alpha=0;}else if(options.interpolation.parametrization=='chordal'){this.options.interpolation.alpha=1.0;}else {this.options.interpolation.parametrization='centripetal';this.options.interpolation.alpha=0.5;}}}}if(this.yAxisLeft){if(options.dataAxis!==undefined){this.yAxisLeft.setOptions(this.options.dataAxis);this.yAxisRight.setOptions(this.options.dataAxis);}}if(this.legendLeft){if(options.legend!==undefined){this.legendLeft.setOptions(this.options.legend);this.legendRight.setOptions(this.options.legend);}}if(this.groups.hasOwnProperty(UNGROUPED)){this.groups[UNGROUPED].setOptions(options);}}// this is used to redraw the graph if the visibility of the groups is changed.
if(this.dom.frame){//not on initial run?
this.forceGraphUpdate=true;this.body.emitter.emit("_change",{queue:true});}};/**
* Hide the component from the DOM
*/LineGraph.prototype.hide=function(){// remove the frame containing the items
if(this.dom.frame.parentNode){this.dom.frame.parentNode.removeChild(this.dom.frame);}};/**
* Show the component in the DOM (when not already visible).
*/LineGraph.prototype.show=function(){// show frame containing the items
if(!this.dom.frame.parentNode){this.body.dom.center.appendChild(this.dom.frame);}};/**
* Set items
* @param {vis.DataSet | null} items
*/LineGraph.prototype.setItems=function(items){var me=this,ids,oldItemsData=this.itemsData;// replace the dataset
if(!items){this.itemsData=null;}else if(isDataViewLike(items)){this.itemsData=typeCoerceDataSet(items);}else {throw new TypeError('Data must implement the interface of DataSet or DataView');}if(oldItemsData){// unsubscribe from old dataset
availableUtils.forEach(this.itemListeners,function(callback,event){oldItemsData.off(event,callback);});// stop maintaining a coerced version of the old data set
oldItemsData.dispose();// remove all drawn items
ids=oldItemsData.getIds();this._onRemove(ids);}if(this.itemsData){// subscribe to new dataset
var id=this.id;availableUtils.forEach(this.itemListeners,function(callback,event){me.itemsData.on(event,callback,id);});// add all new items
ids=this.itemsData.getIds();this._onAdd(ids);}};/**
* Set groups
* @param {vis.DataSet} groups
*/LineGraph.prototype.setGroups=function(groups){var me=this;var ids;// unsubscribe from current dataset
if(this.groupsData){availableUtils.forEach(this.groupListeners,function(callback,event){me.groupsData.off(event,callback);});// remove all drawn groups
ids=this.groupsData.getIds();this.groupsData=null;for(var i=0;i<ids.length;i++){this._removeGroup(ids[i]);}}// replace the dataset
if(!groups){this.groupsData=null;}else if(isDataViewLike(groups)){this.groupsData=groups;}else {throw new TypeError('Data must implement the interface of DataSet or DataView');}if(this.groupsData){// subscribe to new dataset
var id=this.id;availableUtils.forEach(this.groupListeners,function(callback,event){me.groupsData.on(event,callback,id);});// draw all ms
ids=this.groupsData.getIds();this._onAddGroups(ids);}};LineGraph.prototype._onUpdate=function(ids){this._updateAllGroupData(ids);};LineGraph.prototype._onAdd=function(ids){this._onUpdate(ids);};LineGraph.prototype._onRemove=function(ids){this._onUpdate(ids);};LineGraph.prototype._onUpdateGroups=function(groupIds){this._updateAllGroupData(null,groupIds);};LineGraph.prototype._onAddGroups=function(groupIds){this._onUpdateGroups(groupIds);};/**
* this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
* @param {Array} groupIds
* @private
*/LineGraph.prototype._onRemoveGroups=function(groupIds){for(var i=0;i<groupIds.length;i++){this._removeGroup(groupIds[i]);}this.forceGraphUpdate=true;this.body.emitter.emit("_change",{queue:true});};/**
* this cleans the group out off the legends and the dataaxis
* @param {vis.GraphGroup.id} groupId
* @private
*/LineGraph.prototype._removeGroup=function(groupId){if(this.groups.hasOwnProperty(groupId)){if(this.groups[groupId].options.yAxisOrientation=='right'){this.yAxisRight.removeGroup(groupId);this.legendRight.removeGroup(groupId);this.legendRight.redraw();}else {this.yAxisLeft.removeGroup(groupId);this.legendLeft.removeGroup(groupId);this.legendLeft.redraw();}delete this.groups[groupId];}};/**
* update a group object with the group dataset entree
*
* @param {vis.GraphGroup} group
* @param {vis.GraphGroup.id} groupId
* @private
*/LineGraph.prototype._updateGroup=function(group,groupId){if(!this.groups.hasOwnProperty(groupId)){this.groups[groupId]=new GraphGroup(group,groupId,this.options,this.groupsUsingDefaultStyles);if(this.groups[groupId].options.yAxisOrientation=='right'){this.yAxisRight.addGroup(groupId,this.groups[groupId]);this.legendRight.addGroup(groupId,this.groups[groupId]);}else {this.yAxisLeft.addGroup(groupId,this.groups[groupId]);this.legendLeft.addGroup(groupId,this.groups[groupId]);}}else {this.groups[groupId].update(group);if(this.groups[groupId].options.yAxisOrientation=='right'){this.yAxisRight.updateGroup(groupId,this.groups[groupId]);this.legendRight.updateGroup(groupId,this.groups[groupId]);//If yAxisOrientation changed, clean out the group from the other axis.
this.yAxisLeft.removeGroup(groupId);this.legendLeft.removeGroup(groupId);}else {this.yAxisLeft.updateGroup(groupId,this.groups[groupId]);this.legendLeft.updateGroup(groupId,this.groups[groupId]);//If yAxisOrientation changed, clean out the group from the other axis.
this.yAxisRight.removeGroup(groupId);this.legendRight.removeGroup(groupId);}}this.legendLeft.redraw();this.legendRight.redraw();};/**
* this updates all groups, it is used when there is an update the the itemset.
*
* @param {Array} ids
* @param {Array} groupIds
* @private
*/LineGraph.prototype._updateAllGroupData=function(ids,groupIds){if(this.itemsData!=null){var groupsContent={};var items=this.itemsData.get();var fieldId=this.itemsData.idProp;var idMap={};if(ids){ids.map(function(id){idMap[id]=id;});}//pre-Determine array sizes, for more efficient memory claim
var groupCounts={};for(var i=0;i<items.length;i++){var item=items[i];var groupId=item.group;if(groupId===null||groupId===undefined){groupId=UNGROUPED;}groupCounts.hasOwnProperty(groupId)?groupCounts[groupId]++:groupCounts[groupId]=1;}//Pre-load arrays from existing groups if items are not changed (not in ids)
var existingItemsMap={};if(!groupIds&&ids){for(groupId in this.groups){if(this.groups.hasOwnProperty(groupId)){group=this.groups[groupId];var existing_items=group.getItems();groupsContent[groupId]=existing_items.filter(function(item){existingItemsMap[item[fieldId]]=item[fieldId];return item[fieldId]!==idMap[item[fieldId]];});var newLength=groupCounts[groupId];groupCounts[groupId]-=groupsContent[groupId].length;if(groupsContent[groupId].length<newLength){groupsContent[groupId][newLength-1]={};}}}}//Now insert data into the arrays.
for(i=0;i<items.length;i++){item=items[i];groupId=item.group;if(groupId===null||groupId===undefined){groupId=UNGROUPED;}if(!groupIds&&ids&&item[fieldId]!==idMap[item[fieldId]]&&existingItemsMap.hasOwnProperty(item[fieldId])){continue;}if(!groupsContent.hasOwnProperty(groupId)){groupsContent[groupId]=new Array(groupCounts[groupId]);}//Copy data (because of unmodifiable DataView input.
var extended=availableUtils.bridgeObject(item);extended.x=availableUtils.convert(item.x,'Date');extended.end=availableUtils.convert(item.end,'Date');extended.orginalY=item.y;//real Y
extended.y=Number(item.y);extended[fieldId]=item[fieldId];var index=groupsContent[groupId].length-groupCounts[groupId]--;groupsContent[groupId][index]=extended;}//Make sure all groups are present, to allow removal of old groups
for(groupId in this.groups){if(this.groups.hasOwnProperty(groupId)){if(!groupsContent.hasOwnProperty(groupId)){groupsContent[groupId]=new Array(0);}}}//Update legendas, style and axis
for(groupId in groupsContent){if(groupsContent.hasOwnProperty(groupId)){if(groupsContent[groupId].length==0){if(this.groups.hasOwnProperty(groupId)){this._removeGroup(groupId);}}else {var group=undefined;if(this.groupsData!=undefined){group=this.groupsData.get(groupId);}if(group==undefined){group={id:groupId,content:this.options.defaultGroup+groupId};}this._updateGroup(group,groupId);this.groups[groupId].setItems(groupsContent[groupId]);}}}this.forceGraphUpdate=true;this.body.emitter.emit("_change",{queue:true});}};/**
* Redraw the component, mandatory function
* @return {boolean} Returns true if the component is resized
*/LineGraph.prototype.redraw=function(){var resized=false;// calculate actual size and position
this.props.width=this.dom.frame.offsetWidth;this.props.height=this.body.domProps.centerContainer.height-this.body.domProps.border.top-this.body.domProps.border.bottom;// check if this component is resized
resized=this._isResized()||resized;// check whether zoomed (in that case we need to re-stack everything)
var visibleInterval=this.body.range.end-this.body.range.start;var zoomed=visibleInterval!=this.lastVisibleInterval;this.lastVisibleInterval=visibleInterval;// the svg element is three times as big as the width, this allows for fully dragging left and right
// without reloading the graph. the controls for this are bound to events in the constructor
if(resized==true){this.svg.style.width=availableUtils.option.asSize(3*this.props.width);this.svg.style.left=availableUtils.option.asSize(-this.props.width);// if the height of the graph is set as proportional, change the height of the svg
if((this.options.height+'').indexOf("%")!=-1||this.updateSVGheightOnResize==true){this.updateSVGheight=true;}}// update the height of the graph on each redraw of the graph.
if(this.updateSVGheight==true){if(this.options.graphHeight!=this.props.height+'px'){this.options.graphHeight=this.props.height+'px';this.svg.style.height=this.props.height+'px';}this.updateSVGheight=false;}else {this.svg.style.height=(''+this.options.graphHeight).replace('px','')+'px';}// zoomed is here to ensure that animations are shown correctly.
if(resized==true||zoomed==true||this.abortedGraphUpdate==true||this.forceGraphUpdate==true){resized=this._updateGraph()||resized;this.forceGraphUpdate=false;this.lastStart=this.body.range.start;this.svg.style.left=-this.props.width+'px';}else {// move the whole svg while dragging
if(this.lastStart!=0){var offset=this.body.range.start-this.lastStart;var range=this.body.range.end-this.body.range.start;if(this.props.width!=0){var rangePerPixelInv=this.props.width/range;var xOffset=offset*rangePerPixelInv;this.svg.style.left=-this.props.width-xOffset+'px';}}}this.legendLeft.redraw();this.legendRight.redraw();return resized;};LineGraph.prototype._getSortedGroupIds=function(){// getting group Ids
var grouplist=[];for(var groupId in this.groups){if(this.groups.hasOwnProperty(groupId)){var group=this.groups[groupId];if(group.visible==true&&(this.options.groups.visibility[groupId]===undefined||this.options.groups.visibility[groupId]==true)){grouplist.push({id:groupId,zIndex:group.options.zIndex});}}}availableUtils.insertSort(grouplist,function(a,b){var az=a.zIndex;var bz=b.zIndex;if(az===undefined)az=0;if(bz===undefined)bz=0;return az==bz?0:az<bz?-1:1;});var groupIds=new Array(grouplist.length);for(var i=0;i<grouplist.length;i++){groupIds[i]=grouplist[i].id;}return groupIds;};/**
* Update and redraw the graph.
*
* @returns {boolean}
* @private
*/LineGraph.prototype._updateGraph=function(){// reset the svg elements
prepareElements(this.svgElements);if(this.props.width!=0&&this.itemsData!=null){var group,i;var groupRanges={};var changeCalled=false;// this is the range of the SVG canvas
var minDate=this.body.util.toGlobalTime(-this.body.domProps.root.width);var maxDate=this.body.util.toGlobalTime(2*this.body.domProps.root.width);// getting group Ids
var groupIds=this._getSortedGroupIds();if(groupIds.length>0){var groupsData={};// fill groups data, this only loads the data we require based on the timewindow
this._getRelevantData(groupIds,groupsData,minDate,maxDate);// apply sampling, if disabled, it will pass through this function.
this._applySampling(groupIds,groupsData);// we transform the X coordinates to detect collisions
for(i=0;i<groupIds.length;i++){this._convertXcoordinates(groupsData[groupIds[i]]);}// now all needed data has been collected we start the processing.
this._getYRanges(groupIds,groupsData,groupRanges);// update the Y axis first, we use this data to draw at the correct Y points
changeCalled=this._updateYAxis(groupIds,groupRanges);// at changeCalled, abort this update cycle as the graph needs another update with new Width input from the Redraw container.
// Cleanup SVG elements on abort.
if(changeCalled==true){cleanupElements(this.svgElements);this.abortedGraphUpdate=true;return true;}this.abortedGraphUpdate=false;// With the yAxis scaled correctly, use this to get the Y values of the points.
var below=undefined;for(i=0;i<groupIds.length;i++){group=this.groups[groupIds[i]];if(this.options.stack===true&&this.options.style==='line'){if(group.options.excludeFromStacking==undefined||!group.options.excludeFromStacking){if(below!=undefined){this._stack(groupsData[group.id],groupsData[below.id]);if(group.options.shaded.enabled==true&&group.options.shaded.orientation!=="group"){if(group.options.shaded.orientation=="top"&&below.options.shaded.orientation!=="group"){below.options.shaded.orientation="group";below.options.shaded.groupId=group.id;}else {group.options.shaded.orientation="group";group.options.shaded.groupId=below.id;}}}below=group;}}this._convertYcoordinates(groupsData[groupIds[i]],group);}//Precalculate paths and draw shading if appropriate. This will make sure the shading is always behind any lines.
var paths={};for(i=0;i<groupIds.length;i++){group=this.groups[groupIds[i]];if(group.options.style==='line'&&group.options.shaded.enabled==true){var dataset=groupsData[groupIds[i]];if(dataset==null||dataset.length==0){continue;}if(!paths.hasOwnProperty(groupIds[i])){paths[groupIds[i]]=Line.calcPath(dataset,group);}if(group.options.shaded.orientation==="group"){var subGroupId=group.options.shaded.groupId;if(groupIds.indexOf(subGroupId)===-1){console.log(group.id+": Unknown shading group target given:"+subGroupId);continue;}if(!paths.hasOwnProperty(subGroupId)){paths[subGroupId]=Line.calcPath(groupsData[subGroupId],this.groups[subGroupId]);}Line.drawShading(paths[groupIds[i]],group,paths[subGroupId],this.framework);}else {Line.drawShading(paths[groupIds[i]],group,undefined,this.framework);}}}// draw the groups, calculating paths if still necessary.
Bargraph.draw(groupIds,groupsData,this.framework);for(i=0;i<groupIds.length;i++){group=this.groups[groupIds[i]];if(groupsData[groupIds[i]].length>0){switch(group.options.style){case"line":if(!paths.hasOwnProperty(groupIds[i])){paths[groupIds[i]]=Line.calcPath(groupsData[groupIds[i]],group);}Line.draw(paths[groupIds[i]],group,this.framework);// eslint-disable-line no-fallthrough
case"point":// eslint-disable-line no-fallthrough
case"points":if(group.options.style=="point"||group.options.style=="points"||group.options.drawPoints.enabled==true){Points.draw(groupsData[groupIds[i]],group,this.framework);}break;//do nothing...
}}}}}// cleanup unused svg elements
cleanupElements(this.svgElements);return false;};LineGraph.prototype._stack=function(data,subData){var index,dx,dy,subPrevPoint,subNextPoint;index=0;// for each data point we look for a matching on in the set below
for(var j=0;j<data.length;j++){subPrevPoint=undefined;subNextPoint=undefined;// we look for time matches or a before-after point
for(var k=index;k<subData.length;k++){// if times match exactly
if(subData[k].x===data[j].x){subPrevPoint=subData[k];subNextPoint=subData[k];index=k;break;}else if(subData[k].x>data[j].x){// overshoot
subNextPoint=subData[k];if(k==0){subPrevPoint=subNextPoint;}else {subPrevPoint=subData[k-1];}index=k;break;}}// in case the last data point has been used, we assume it stays like this.
if(subNextPoint===undefined){subPrevPoint=subData[subData.length-1];subNextPoint=subData[subData.length-1];}// linear interpolation
dx=subNextPoint.x-subPrevPoint.x;dy=subNextPoint.y-subPrevPoint.y;if(dx==0){data[j].y=data[j].orginalY+subNextPoint.y;}else {data[j].y=data[j].orginalY+dy/dx*(data[j].x-subPrevPoint.x)+subPrevPoint.y;// ax + b where b is data[j].y
}}};/**
* first select and preprocess the data from the datasets.
* the groups have their preselection of data, we now loop over this data to see
* what data we need to draw. Sorted data is much faster.
* more optimization is possible by doing the sampling before and using the binary search
* to find the end date to determine the increment.
*
* @param {array} groupIds
* @param {object} groupsData
* @param {date} minDate
* @param {date} maxDate
* @private
*/LineGraph.prototype._getRelevantData=function(groupIds,groupsData,minDate,maxDate){var group,i,j,item;if(groupIds.length>0){for(i=0;i<groupIds.length;i++){group=this.groups[groupIds[i]];var itemsData=group.getItems();// optimization for sorted data
if(group.options.sort==true){var dateComparator=function(a,b){return a.getTime()==b.getTime()?0:a<b?-1:1;};var first=Math.max(0,availableUtils.binarySearchValue(itemsData,minDate,'x','before',dateComparator));var last=Math.min(itemsData.length,availableUtils.binarySearchValue(itemsData,maxDate,'x','after',dateComparator)+1);if(last<=0){last=itemsData.length;}var dataContainer=new Array(last-first);for(j=first;j<last;j++){item=group.itemsData[j];dataContainer[j-first]=item;}groupsData[groupIds[i]]=dataContainer;}else {// If unsorted data, all data is relevant, just returning entire structure
groupsData[groupIds[i]]=group.itemsData;}}}};/**
*
* @param {Array.<vis.GraphGroup.id>} groupIds
* @param {vis.DataSet} groupsData
* @private
*/LineGraph.prototype._applySampling=function(groupIds,groupsData){var group;if(groupIds.length>0){for(var i=0;i<groupIds.length;i++){group=this.groups[groupIds[i]];if(group.options.sampling==true){var dataContainer=groupsData[groupIds[i]];if(dataContainer.length>0){var increment=1;var amountOfPoints=dataContainer.length;// the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
// of width changing of the yAxis.
//TODO: This assumes sorted data, but that's not guaranteed!
var xDistance=this.body.util.toGlobalScreen(dataContainer[dataContainer.length-1].x)-this.body.util.toGlobalScreen(dataContainer[0].x);var pointsPerPixel=amountOfPoints/xDistance;increment=Math.min(Math.ceil(0.2*amountOfPoints),Math.max(1,Math.round(pointsPerPixel)));var sampledData=new Array(amountOfPoints);for(var j=0;j<amountOfPoints;j+=increment){var idx=Math.round(j/increment);sampledData[idx]=dataContainer[j];}groupsData[groupIds[i]]=sampledData.splice(0,Math.round(amountOfPoints/increment));}}}}};/**
*
* @param {Array.<vis.GraphGroup.id>} groupIds
* @param {vis.DataSet} groupsData
* @param {object} groupRanges | this is being filled here
* @private
*/LineGraph.prototype._getYRanges=function(groupIds,groupsData,groupRanges){var groupData,group,i;var combinedDataLeft=[];var combinedDataRight=[];var options;if(groupIds.length>0){for(i=0;i<groupIds.length;i++){groupData=groupsData[groupIds[i]];options=this.groups[groupIds[i]].options;if(groupData.length>0){group=this.groups[groupIds[i]];// if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
if(options.stack===true&&options.style==='bar'){if(options.yAxisOrientation==='left'){combinedDataLeft=combinedDataLeft.concat(groupData);}else {combinedDataRight=combinedDataRight.concat(groupData);}}else {groupRanges[groupIds[i]]=group.getYRange(groupData,groupIds[i]);}}}// if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
Bargraph.getStackedYRange(combinedDataLeft,groupRanges,groupIds,'__barStackLeft','left');Bargraph.getStackedYRange(combinedDataRight,groupRanges,groupIds,'__barStackRight','right');}};/**
* this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
* @param {Array.<vis.GraphGroup.id>} groupIds
* @param {Object} groupRanges
* @returns {boolean} resized
* @private
*/LineGraph.prototype._updateYAxis=function(groupIds,groupRanges){var resized=false;var yAxisLeftUsed=false;var yAxisRightUsed=false;var minLeft=1e9,minRight=1e9,maxLeft=-1e9,maxRight=-1e9,minVal,maxVal;// if groups are present
if(groupIds.length>0){// this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop.
for(var i=0;i<groupIds.length;i++){var group=this.groups[groupIds[i]];if(group&&group.options.yAxisOrientation!='right'){yAxisLeftUsed=true;minLeft=1e9;maxLeft=-1e9;}else if(group&&group.options.yAxisOrientation){yAxisRightUsed=true;minRight=1e9;maxRight=-1e9;}}// if there are items:
for(i=0;i<groupIds.length;i++){if(groupRanges.hasOwnProperty(groupIds[i])){if(groupRanges[groupIds[i]].ignore!==true){minVal=groupRanges[groupIds[i]].min;maxVal=groupRanges[groupIds[i]].max;if(groupRanges[groupIds[i]].yAxisOrientation!='right'){yAxisLeftUsed=true;minLeft=minLeft>minVal?minVal:minLeft;maxLeft=maxLeft<maxVal?maxVal:maxLeft;}else {yAxisRightUsed=true;minRight=minRight>minVal?minVal:minRight;maxRight=maxRight<maxVal?maxVal:maxRight;}}}}if(yAxisLeftUsed==true){this.yAxisLeft.setRange(minLeft,maxLeft);}if(yAxisRightUsed==true){this.yAxisRight.setRange(minRight,maxRight);}}resized=this._toggleAxisVisiblity(yAxisLeftUsed,this.yAxisLeft)||resized;resized=this._toggleAxisVisiblity(yAxisRightUsed,this.yAxisRight)||resized;if(yAxisRightUsed==true&&yAxisLeftUsed==true){this.yAxisLeft.drawIcons=true;this.yAxisRight.drawIcons=true;}else {this.yAxisLeft.drawIcons=false;this.yAxisRight.drawIcons=false;}this.yAxisRight.master=!yAxisLeftUsed;this.yAxisRight.masterAxis=this.yAxisLeft;if(this.yAxisRight.master==false){if(yAxisRightUsed==true){this.yAxisLeft.lineOffset=this.yAxisRight.width;}else {this.yAxisLeft.lineOffset=0;}resized=this.yAxisLeft.redraw()||resized;resized=this.yAxisRight.redraw()||resized;}else {resized=this.yAxisRight.redraw()||resized;}// clean the accumulated lists
var tempGroups=['__barStackLeft','__barStackRight','__lineStackLeft','__lineStackRight'];for(i=0;i<tempGroups.length;i++){if(groupIds.indexOf(tempGroups[i])!=-1){groupIds.splice(groupIds.indexOf(tempGroups[i]),1);}}return resized;};/**
* This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
*
* @param {boolean} axisUsed
* @param {vis.DataAxis} axis
* @returns {boolean}
* @private
*/LineGraph.prototype._toggleAxisVisiblity=function(axisUsed,axis){var changed=false;if(axisUsed==false){if(axis.dom.frame.parentNode&&axis.hidden==false){axis.hide();changed=true;}}else {if(!axis.dom.frame.parentNode&&axis.hidden==true){axis.show();changed=true;}}return changed;};/**
* This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
* util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
* the yAxis.
*
* @param {Array.<Object>} datapoints
* @private
*/LineGraph.prototype._convertXcoordinates=function(datapoints){var toScreen=this.body.util.toScreen;for(var i=0;i<datapoints.length;i++){datapoints[i].screen_x=toScreen(datapoints[i].x)+this.props.width;datapoints[i].screen_y=datapoints[i].y;//starting point for range calculations
if(datapoints[i].end!=undefined){datapoints[i].screen_end=toScreen(datapoints[i].end)+this.props.width;}else {datapoints[i].screen_end=undefined;}}};/**
* This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
* util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
* the yAxis.
*
* @param {Array.<Object>} datapoints
* @param {vis.GraphGroup} group
* @private
*/LineGraph.prototype._convertYcoordinates=function(datapoints,group){var axis=this.yAxisLeft;var svgHeight=Number(this.svg.style.height.replace('px',''));if(group.options.yAxisOrientation=='right'){axis=this.yAxisRight;}for(var i=0;i<datapoints.length;i++){datapoints[i].screen_y=Math.round(axis.convertValue(datapoints[i].y));}group.setZeroPosition(Math.min(svgHeight,axis.convertValue(0)));};/**
* This object contains all possible options. It will check if the types are correct, if required if the option is one
* of the allowed values.
*
* __any__ means that the name of the property does not matter.
* __type__ is a required field for all objects and contains the allowed types of all objects
*/let string$2='string';let bool$2='boolean';let number$2='number';let array$2='array';let date='date';let object$2='object';// should only be in a __type__ property
let dom$2='dom';let moment='moment';let any$2='any';let allOptions$3={configure:{enabled:{'boolean':bool$2},filter:{'boolean':bool$2,'function':'function'},container:{dom: dom$2},__type__:{object: object$2,'boolean':bool$2,'function':'function'}},//globals :
alignCurrentTime:{string: string$2,'undefined':'undefined'},yAxisOrientation:{string:['left','right']},defaultGroup:{string: string$2},sort:{'boolean':bool$2},sampling:{'boolean':bool$2},stack:{'boolean':bool$2},graphHeight:{string: string$2,number: number$2},shaded:{enabled:{'boolean':bool$2},orientation:{string:['bottom','top','zero','group']},// top, bottom, zero, group
groupId:{object: object$2},__type__:{'boolean':bool$2,object: object$2}},style:{string:['line','bar','points']},// line, bar
barChart:{width:{number: number$2},minWidth:{number: number$2},sideBySide:{'boolean':bool$2},align:{string:['left','center','right']},__type__:{object: object$2}},interpolation:{enabled:{'boolean':bool$2},parametrization:{string:['centripetal','chordal','uniform']},// uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
alpha:{number: number$2},__type__:{object: object$2,'boolean':bool$2}},drawPoints:{enabled:{'boolean':bool$2},onRender:{'function':'function'},size:{number: number$2},style:{string:['square','circle']},// square, circle
__type__:{object: object$2,'boolean':bool$2,'function':'function'}},dataAxis:{showMinorLabels:{'boolean':bool$2},showMajorLabels:{'boolean':bool$2},showWeekScale:{'boolean':bool$2},icons:{'boolean':bool$2},width:{string: string$2,number: number$2},visible:{'boolean':bool$2},alignZeros:{'boolean':bool$2},left:{range:{min:{number: number$2,'undefined':'undefined'},max:{number: number$2,'undefined':'undefined'},__type__:{object: object$2}},format:{'function':'function'},title:{text:{string: string$2,number: number$2,'undefined':'undefined'},style:{string: string$2,'undefined':'undefined'},__type__:{object: object$2}},__type__:{object: object$2}},right:{range:{min:{number: number$2,'undefined':'undefined'},max:{number: number$2,'undefined':'undefined'},__type__:{object: object$2}},format:{'function':'function'},title:{text:{string: string$2,number: number$2,'undefined':'undefined'},style:{string: string$2,'undefined':'undefined'},__type__:{object: object$2}},__type__:{object: object$2}},__type__:{object: object$2}},legend:{enabled:{'boolean':bool$2},icons:{'boolean':bool$2},left:{visible:{'boolean':bool$2},position:{string:['top-right','bottom-right','top-left','bottom-left']},__type__:{object: object$2}},right:{visible:{'boolean':bool$2},position:{string:['top-right','bottom-right','top-left','bottom-left']},__type__:{object: object$2}},__type__:{object: object$2,'boolean':bool$2}},groups:{visibility:{any: any$2},__type__:{object: object$2}},autoResize:{'boolean':bool$2},throttleRedraw:{number: number$2},// TODO: DEPRICATED see https://github.com/almende/vis/issues/2511
clickToUse:{'boolean':bool$2},end:{number: number$2,date,string: string$2,moment},format:{minorLabels:{millisecond:{string: string$2,'undefined':'undefined'},second:{string: string$2,'undefined':'undefined'},minute:{string: string$2,'undefined':'undefined'},hour:{string: string$2,'undefined':'undefined'},weekday:{string: string$2,'undefined':'undefined'},day:{string: string$2,'undefined':'undefined'},week:{string: string$2,'undefined':'undefined'},month:{string: string$2,'undefined':'undefined'},quarter:{string: string$2,'undefined':'undefined'},year:{string: string$2,'undefined':'undefined'},__type__:{object: object$2}},majorLabels:{millisecond:{string: string$2,'undefined':'undefined'},second:{string: string$2,'undefined':'undefined'},minute:{string: string$2,'undefined':'undefined'},hour:{string: string$2,'undefined':'undefined'},weekday:{string: string$2,'undefined':'undefined'},day:{string: string$2,'undefined':'undefined'},week:{string: string$2,'undefined':'undefined'},month:{string: string$2,'undefined':'undefined'},quarter:{string: string$2,'undefined':'undefined'},year:{string: string$2,'undefined':'undefined'},__type__:{object: object$2}},__type__:{object: object$2}},moment:{'function':'function'},height:{string: string$2,number: number$2},hiddenDates:{start:{date,number: number$2,string: string$2,moment},end:{date,number: number$2,string: string$2,moment},repeat:{string: string$2},__type__:{object: object$2,array: array$2}},locale:{string: string$2},locales:{__any__:{any: any$2},__type__:{object: object$2}},max:{date,number: number$2,string: string$2,moment},maxHeight:{number: number$2,string: string$2},maxMinorChars:{number: number$2},min:{date,number: number$2,string: string$2,moment},minHeight:{number: number$2,string: string$2},moveable:{'boolean':bool$2},multiselect:{'boolean':bool$2},orientation:{string: string$2},showCurrentTime:{'boolean':bool$2},showMajorLabels:{'boolean':bool$2},showMinorLabels:{'boolean':bool$2},showWeekScale:{'boolean':bool$2},snap:{'function':'function','null':'null'},start:{date,number: number$2,string: string$2,moment},timeAxis:{scale:{string: string$2,'undefined':'undefined'},step:{number: number$2,'undefined':'undefined'},__type__:{object: object$2}},width:{string: string$2,number: number$2},zoomable:{'boolean':bool$2},zoomKey:{string:['ctrlKey','altKey','metaKey','']},zoomMax:{number: number$2},zoomMin:{number: number$2},zIndex:{number: number$2},__type__:{object: object$2}};let configureOptions$2={global:{alignCurrentTime:['none','year','month','quarter','week','isoWeek','day','date','hour','minute','second'],//yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly
sort:true,sampling:true,stack:false,shaded:{enabled:false,orientation:['zero','top','bottom','group']// zero, top, bottom
},style:['line','bar','points'],// line, bar
barChart:{width:[50,5,100,5],minWidth:[50,5,100,5],sideBySide:false,align:['left','center','right']// left, center, right
},interpolation:{enabled:true,parametrization:['centripetal','chordal','uniform']// uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
},drawPoints:{enabled:true,size:[6,2,30,1],style:['square','circle']// square, circle
},dataAxis:{showMinorLabels:true,showMajorLabels:true,showWeekScale:false,icons:false,width:[40,0,200,1],visible:true,alignZeros:true,left:{//range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined},
//format: function (value) {return value;},
title:{text:'',style:''}},right:{//range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined},
//format: function (value) {return value;},
title:{text:'',style:''}}},legend:{enabled:false,icons:true,left:{visible:true,position:['top-right','bottom-right','top-left','bottom-left']// top/bottom - left,right
},right:{visible:true,position:['top-right','bottom-right','top-left','bottom-left']// top/bottom - left,right
}},autoResize:true,clickToUse:false,end:'',format:{minorLabels:{millisecond:'SSS',second:'s',minute:'HH:mm',hour:'HH:mm',weekday:'ddd D',day:'D',week:'w',month:'MMM',quarter:'[Q]Q',year:'YYYY'},majorLabels:{millisecond:'HH:mm:ss',second:'D MMMM HH:mm',minute:'ddd D MMMM',hour:'ddd D MMMM',weekday:'MMMM YYYY',day:'MMMM YYYY',week:'MMMM YYYY',month:'YYYY',quarter:'YYYY',year:''}},height:'',locale:'',max:'',maxHeight:'',maxMinorChars:[7,0,20,1],min:'',minHeight:'',moveable:true,orientation:['both','bottom','top'],showCurrentTime:false,showMajorLabels:true,showMinorLabels:true,showWeekScale:false,start:'',width:'100%',zoomable:true,zoomKey:['ctrlKey','altKey','metaKey',''],zoomMax:[315360000000000,10,315360000000000,1],zoomMin:[10,10,315360000000000,1],zIndex:0}};/**
* Create a timeline visualization
* @param {HTMLElement} container
* @param {vis.DataSet | Array} [items]
* @param {vis.DataSet | Array | vis.DataView | Object} [groups]
* @param {Object} [options] See Graph2d.setOptions for the available options.
* @constructor Graph2d
* @extends Core
*/function Graph2d(container,items,groups,options){// if the third element is options, the forth is groups (optionally);
if(!(Array.isArray(groups)||isDataViewLike(groups))&&groups instanceof Object){var forthArgument=options;options=groups;groups=forthArgument;}// TODO: REMOVE THIS in the next MAJOR release
// see https://github.com/almende/vis/issues/2511
if(options&&options.throttleRedraw){console.warn("Graph2d option \"throttleRedraw\" is DEPRICATED and no longer supported. It will be removed in the next MAJOR release.");}var me=this;this.defaultOptions={start:null,end:null,autoResize:true,orientation:{axis:'bottom',// axis orientation: 'bottom', 'top', or 'both'
item:'bottom'// not relevant for Graph2d
},moment:moment$3,width:null,height:null,maxHeight:null,minHeight:null};this.options=availableUtils.deepExtend({},this.defaultOptions);// Create the DOM, props, and emitter
this._create(container);// all components listed here will be repainted automatically
this.components=[];this.body={dom:this.dom,domProps:this.props,emitter:{on:this.on.bind(this),off:this.off.bind(this),emit:this.emit.bind(this)},hiddenDates:[],util:{getScale(){return me.timeAxis.step.scale;},getStep(){return me.timeAxis.step.step;},toScreen:me._toScreen.bind(me),toGlobalScreen:me._toGlobalScreen.bind(me),// this refers to the root.width
toTime:me._toTime.bind(me),toGlobalTime:me._toGlobalTime.bind(me)}};// range
this.range=new Range(this.body);this.components.push(this.range);this.body.range=this.range;// time axis
this.timeAxis=new TimeAxis(this.body);this.components.push(this.timeAxis);//this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
// current time bar
this.currentTime=new CurrentTime(this.body);this.components.push(this.currentTime);// item set
this.linegraph=new LineGraph(this.body);this.components.push(this.linegraph);this.itemsData=null;// DataSet
this.groupsData=null;// DataSet
this.on('tap',function(event){me.emit('click',me.getEventProperties(event));});this.on('doubletap',function(event){me.emit('doubleClick',me.getEventProperties(event));});this.dom.root.oncontextmenu=function(event){me.emit('contextmenu',me.getEventProperties(event));};//Single time autoscale/fit
this.initialFitDone=false;this.on('changed',function(){if(me.itemsData==null)return;if(!me.initialFitDone&&!me.options.rollingMode){me.initialFitDone=true;if(me.options.start!=undefined||me.options.end!=undefined){if(me.options.start==undefined||me.options.end==undefined){var range=me.getItemRange();}var start=me.options.start!=undefined?me.options.start:range.min;var end=me.options.end!=undefined?me.options.end:range.max;me.setWindow(start,end,{animation:false});}else {me.fit({animation:false});}}if(!me.initialDrawDone&&(me.initialRangeChangeDone||!me.options.start&&!me.options.end||me.options.rollingMode)){me.initialDrawDone=true;me.dom.root.style.visibility='visible';me.dom.loadingScreen.parentNode.removeChild(me.dom.loadingScreen);if(me.options.onInitialDrawComplete){setTimeout(()=>{return me.options.onInitialDrawComplete();},0);}}});// apply options
if(options){this.setOptions(options);}// IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
if(groups){this.setGroups(groups);}// create itemset
if(items){this.setItems(items);}// draw for the first time
this._redraw();}// Extend the functionality from Core
Graph2d.prototype=new Core();Graph2d.prototype.setOptions=function(options){// validate options
let errorFound=Validator.validate(options,allOptions$3);if(errorFound===true){console.log('%cErrors have been found in the supplied options object.',printStyle);}Core.prototype.setOptions.call(this,options);};/**
* Set items
* @param {vis.DataSet | Array | null} items
*/Graph2d.prototype.setItems=function(items){var initialLoad=this.itemsData==null;// convert to type DataSet when needed
var newDataSet;if(!items){newDataSet=null;}else if(isDataViewLike(items)){newDataSet=typeCoerceDataSet(items);}else {// turn an array into a dataset
newDataSet=typeCoerceDataSet(new DataSet(items));}// set items
if(this.itemsData){// stop maintaining a coerced version of the old data set
this.itemsData.dispose();}this.itemsData=newDataSet;this.linegraph&&this.linegraph.setItems(newDataSet!=null?newDataSet.rawDS:null);if(initialLoad){if(this.options.start!=undefined||this.options.end!=undefined){var start=this.options.start!=undefined?this.options.start:null;var end=this.options.end!=undefined?this.options.end:null;this.setWindow(start,end,{animation:false});}else {this.fit({animation:false});}}};/**
* Set groups
* @param {vis.DataSet | Array} groups
*/Graph2d.prototype.setGroups=function(groups){// convert to type DataSet when needed
var newDataSet;if(!groups){newDataSet=null;}else if(isDataViewLike(groups)){newDataSet=groups;}else {// turn an array into a dataset
newDataSet=new DataSet(groups);}this.groupsData=newDataSet;this.linegraph.setGroups(newDataSet);};/**
* Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right).
* @param {vis.GraphGroup.id} groupId
* @param {number} width
* @param {number} height
* @returns {{icon: SVGElement, label: string, orientation: string}|string}
*/Graph2d.prototype.getLegend=function(groupId,width,height){if(width===undefined){width=15;}if(height===undefined){height=15;}if(this.linegraph.groups[groupId]!==undefined){return this.linegraph.groups[groupId].getLegend(width,height);}else {return "cannot find group:'"+groupId+"'";}};/**
* This checks if the visible option of the supplied group (by ID) is true or false.
* @param {vis.GraphGroup.id} groupId
* @returns {boolean}
*/Graph2d.prototype.isGroupVisible=function(groupId){if(this.linegraph.groups[groupId]!==undefined){return this.linegraph.groups[groupId].visible&&(this.linegraph.options.groups.visibility[groupId]===undefined||this.linegraph.options.groups.visibility[groupId]==true);}else {return false;}};/**
* Get the data range of the item set.
* @returns {{min: Date, max: Date}} range A range with a start and end Date.
* When no minimum is found, min==null
* When no maximum is found, max==null
*/Graph2d.prototype.getDataRange=function(){var min=null;var max=null;// calculate min from start filed
for(var groupId in this.linegraph.groups){if(this.linegraph.groups.hasOwnProperty(groupId)){if(this.linegraph.groups[groupId].visible==true){for(var i=0;i<this.linegraph.groups[groupId].itemsData.length;i++){var item=this.linegraph.groups[groupId].itemsData[i];var value=availableUtils.convert(item.x,'Date').valueOf();min=min==null?value:min>value?value:min;max=max==null?value:max<value?value:max;}}}}return {min:min!=null?new Date(min):null,max:max!=null?new Date(max):null};};/**
* Generate Timeline related information from an event
* @param {Event} event
* @return {Object} An object with related information, like on which area
* The event happened, whether clicked on an item, etc.
*/Graph2d.prototype.getEventProperties=function(event){var clientX=event.center?event.center.x:event.clientX;var clientY=event.center?event.center.y:event.clientY;var x=clientX-availableUtils.getAbsoluteLeft(this.dom.centerContainer);var y=clientY-availableUtils.getAbsoluteTop(this.dom.centerContainer);var time=this._toTime(x);var customTime=CustomTime.customTimeFromTarget(event);var element=availableUtils.getTarget(event);var what=null;if(availableUtils.hasParent(element,this.timeAxis.dom.foreground)){what='axis';}else if(this.timeAxis2&&availableUtils.hasParent(element,this.timeAxis2.dom.foreground)){what='axis';}else if(availableUtils.hasParent(element,this.linegraph.yAxisLeft.dom.frame)){what='data-axis';}else if(availableUtils.hasParent(element,this.linegraph.yAxisRight.dom.frame)){what='data-axis';}else if(availableUtils.hasParent(element,this.linegraph.legendLeft.dom.frame)){what='legend';}else if(availableUtils.hasParent(element,this.linegraph.legendRight.dom.frame)){what='legend';}else if(customTime!=null){what='custom-time';}else if(availableUtils.hasParent(element,this.currentTime.bar)){what='current-time';}else if(availableUtils.hasParent(element,this.dom.center)){what='background';}var value=[];var yAxisLeft=this.linegraph.yAxisLeft;var yAxisRight=this.linegraph.yAxisRight;if(!yAxisLeft.hidden&&this.itemsData.length>0){value.push(yAxisLeft.screenToValue(y));}if(!yAxisRight.hidden&&this.itemsData.length>0){value.push(yAxisRight.screenToValue(y));}return {event:event,customTime:customTime?customTime.options.id:null,what:what,pageX:event.srcEvent?event.srcEvent.pageX:event.pageX,pageY:event.srcEvent?event.srcEvent.pageY:event.pageY,x:x,y:y,time:time,value:value};};/**
* Load a configurator
* @return {Object}
* @private
*/Graph2d.prototype._createConfigurator=function(){return new Configurator(this,this.dom.container,configureOptions$2);};// Locales have to be supplied by the user.
const defaultLanguage=getNavigatorLanguage();moment$4.locale(defaultLanguage);
const arrayDiff = (arr1, arr2) => arr1.filter(x => arr2.indexOf(x) === -1);
const mountVisData = (vm, propName /*, DataSet, DataView*/) => {
let data = vm[propName];
// If data is DataSet or DataView we return early without attaching our own events
if (!(vm[propName] instanceof DataSet || vm[propName] instanceof DataView)) {
data = new DataSet(vm[propName]);
// Rethrow all events
data.on('*', (event, properties, senderId) => vm.$emit(`${propName}-${event}`, {
event,
properties,
senderId
}));
// We attach deep watcher on the prop to propagate changes in the DataSet
const callback = value => {
if (Array.isArray(value)) {
const newIds = new DataSet(value).getIds();
const diff = arrayDiff(vm.visData[propName].getIds(), newIds);
vm.visData[propName].update(value);
vm.visData[propName].remove(diff);
}
};
vm.$watch(propName, callback, {
deep: true
});
}
// Emitting DataSets back
vm.$emit(`${propName}-mounted`, data);
return data;
};
const translateEvent = event => {
return event.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
};
var script$2 = {
name: 'timeline',
props: {
groups: {
type: [Array, DataSet, DataView],
default: () => []
},
items: {
type: [Array, DataSet, DataView],
default: () => []
},
events: {
type: Array,
default: () => ['click', 'contextmenu', 'currentTimeTick', 'doubleClick', 'drop', 'mouseOver', 'mouseDown', 'mouseUp', 'mouseMove', 'groupDragged', 'changed', 'rangechange', 'rangechanged', 'select', 'itemover', 'itemout', 'timechange', 'timechanged', 'markerchange', 'markerchanged']
},
selection: {
type: [Array, String],
default: () => []
},
options: {
type: Object
}
},
data: () => ({
visData: {
items: null,
groups: null
}
}),
watchEffect: {
options: {
deep: true,
handler() {
this.timeline.setOptions(this.options);
}
},
selection: {
deep: false,
handler(v) {
this.timeline.setSelection(v);
}
}
},
methods: {
addCustomTime(time, id) {
return this.timeline.addCustomTime(time, id);
},
destroy() {
this.timeline.destroy();
},
fit() {
this.timeline.fit();
},
focus(id, options) {
this.timeline.focus(id, options);
},
getCurrentTime() {
return this.timeline.getCurrentTime();
},
getCustomTime(id) {
return this.timeline.getCustomTime(id);
},
getEventProperties(event) {
return this.timeline.getEventProperties(event);
},
getItemRange() {
return this.timeline.getItemRange();
},
getSelection() {
return this.timeline.getSelection();
},
getVisibleItems() {
return this.timeline.getVisibleItems();
},
getWindow() {
return this.timeline.getWindow();
},
moveTo(time, options) {
this.timeline.moveTo(time, options);
},
on(event, callback) {
this.timeline.on(event, callback);
},
off(event, callback) {
this.timeline.off(event, callback);
},
redraw() {
this.timeline.redraw();
},
removeCustomTime(id) {
this.timeline.removeCustomTime(id);
},
setCurrentTime(time) {
this.timeline.setCurrentTime(time);
},
setCustomTime(time, id) {
this.timeline.setCustomTime(time, id);
},
setCustomTimeTitle(title, id) {
this.timeline.setCustomTimeTitle(title, id);
},
setCustomTimeMarker(title, id, editable) {
this.timeline.setCustomTimeMarker(title, id, editable);
},
setData(object) {
this.timeline.setData(object);
},
setGroups(groups) {
this.timeline.setGroups(groups);
},
setItems(items) {
this.timeline.setItems(items);
},
setOptions(options) {
this.timeline.setOptions(options);
},
setSelection(ids, options) {
this.timeline.setSelection(ids, options);
},
setWindow(start, end, options, callback) {
this.timeline.setWindow(start, end, options, callback);
},
toggleRollingMode() {
this.timeline.toggleRollingMode();
},
zoomIn(percentage, options, callback) {
this.timeline.zoomIn(percentage, options, callback);
},
zoomOut(percentage, options, callback) {
this.timeline.zoomOut(percentage, options, callback);
}
},
mounted() {
const container = this.$refs.visualization;
this.visData.items = mountVisData(this, 'items');
if (this.groups && this.groups.length > 0) {
this.visData.groups = mountVisData(this, 'groups');
this.timeline = new Timeline(container, this.visData.items, this.visData.groups, this.options);
} else {
this.timeline = new Timeline(container, this.visData.items, this.options);
}
this.events.forEach(eventName => this.timeline.on(eventName, props => this.$emit(translateEvent(eventName), props)));
},
created() {
// This should be a Vue data property, but Vue reactivity kinda bugs Vis.
// See here for more: https://github.com/almende/vis/issues/2524
this.timeline = null;
},
beforeUnmount() {
this.timeline.destroy();
}
};
const _hoisted_1$2 = {
ref: "visualization"
};
function render$2(_ctx, _cache, $props, $setup, $data, $options) {
return openBlock(), createElementBlock("div", null, [createElementVNode("div", _hoisted_1$2, null, 512 /* NEED_PATCH */)]);
}
script$2.render = render$2;
var script$1 = {
name: 'graph2d',
props: {
groups: {
type: [Array, DataSet, DataView],
default: () => []
},
items: {
type: [Array, DataSet, DataView],
default: () => []
},
events: {
type: Array,
default: () => ['click', 'contextmenu', 'currentTimeTick', 'doubleClick', 'changed', 'rangechange', 'rangechanged', 'timechange', 'timechanged']
},
options: {
type: Object
}
},
data: () => ({
visData: {
items: null,
groups: null
}
}),
watchEffect: {
options: {
deep: true,
handler(v) {
this.graph2d.setOptions(v);
}
}
},
methods: {
destroy() {
this.graph2d.destroy();
},
fit() {
this.graph2d.fit();
},
getCurrentTime() {
return this.graph2d.getCurrentTime();
},
getCustomTime() {
return this.graph2d.getCustomTime();
},
getDataRange() {
return this.graph2d.getDataRange();
},
getEventProperties(event) {
return this.graph2d.getEventProperties(event);
},
getLegend(groupId, iconWidth, iconHeight) {
return this.graph2d.getLegend(groupId, iconWidth, iconHeight);
},
getWindow() {
return this.graph2d.getWindow();
},
isGroupVisible(groupId) {
return this.graph2d.isGroupVisible(groupId);
},
moveTo(time, options) {
this.graph2d.moveTo(time, options);
},
on(event, callback) {
this.graph2d.on(event, callback);
},
off(event, callback) {
this.graph2d.off(event, callback);
},
redraw() {
this.graph2d.redraw();
},
setCurrentTime(time) {
this.graph2d.setCurrentTime(time);
},
setCustomTime(time) {
this.graph2d.setCustomTime(time);
},
setGroups(groups) {
this.graph2d.setGroups(groups);
},
setItems(items) {
this.graph2d.setItems(items);
},
setOptions(options) {
this.graph2d.setOptions(options);
},
setWindow(start, end) {
this.graph2d.setWindow(start, end);
}
},
mounted() {
const container = this.$refs.visualization;
this.visData.items = mountVisData(this, 'items');
this.visData.groups = mountVisData(this, 'groups');
this.graph2d = new Graph2d(container, this.visData.items, this.visData.groups, this.options);
this.events.forEach(eventName => this.graph2d.on(eventName, props => this.$emit(translateEvent(eventName), props)));
},
created() {
// This should be a Vue data property, but Vue reactivity kinda bugs Vis.
// See here for more: https://github.com/almende/vis/issues/2524
this.graph2d = null;
},
beforeUnmount() {
this.graph2d.destroy();
}
};
const _hoisted_1$1 = {
ref: "visualization"
};
function render$1(_ctx, _cache, $props, $setup, $data, $options) {
return openBlock(), createElementBlock("div", _hoisted_1$1, null, 512 /* NEED_PATCH */);
}
script$1.render = render$1;
/**
* Draw a circle.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - The radius of the circle.
*/function drawCircle(ctx,x,y,r){ctx.beginPath();ctx.arc(x,y,r,0,2*Math.PI,false);ctx.closePath();}/**
* Draw a square.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the width and height of the square.
*/function drawSquare(ctx,x,y,r){ctx.beginPath();ctx.rect(x-r,y-r,r*2,r*2);ctx.closePath();}/**
* Draw an equilateral triangle standing on a side.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the length of the sides.
* @remarks
* http://en.wikipedia.org/wiki/Equilateral_triangle
*/function drawTriangle(ctx,x,y,r){ctx.beginPath();// the change in radius and the offset is here to center the shape
r*=1.15;y+=0.275*r;const s=r*2;const s2=s/2;const ir=Math.sqrt(3)/6*s;// radius of inner circle
const h=Math.sqrt(s*s-s2*s2);// height
ctx.moveTo(x,y-(h-ir));ctx.lineTo(x+s2,y+ir);ctx.lineTo(x-s2,y+ir);ctx.lineTo(x,y-(h-ir));ctx.closePath();}/**
* Draw an equilateral triangle standing on a vertex.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the length of the sides.
* @remarks
* http://en.wikipedia.org/wiki/Equilateral_triangle
*/function drawTriangleDown(ctx,x,y,r){ctx.beginPath();// the change in radius and the offset is here to center the shape
r*=1.15;y-=0.275*r;const s=r*2;const s2=s/2;const ir=Math.sqrt(3)/6*s;// radius of inner circle
const h=Math.sqrt(s*s-s2*s2);// height
ctx.moveTo(x,y+(h-ir));ctx.lineTo(x+s2,y-ir);ctx.lineTo(x-s2,y-ir);ctx.lineTo(x,y+(h-ir));ctx.closePath();}/**
* Draw a star.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - The outer radius of the star.
*/function drawStar(ctx,x,y,r){// http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
ctx.beginPath();// the change in radius and the offset is here to center the shape
r*=0.82;y+=0.1*r;for(let n=0;n<10;n++){const radius=n%2===0?r*1.3:r*0.5;ctx.lineTo(x+radius*Math.sin(n*2*Math.PI/10),y-radius*Math.cos(n*2*Math.PI/10));}ctx.closePath();}/**
* Draw a diamond.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - Half of the width and height of the diamond.
* @remarks
* http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
*/function drawDiamond(ctx,x,y,r){ctx.beginPath();ctx.lineTo(x,y+r);ctx.lineTo(x+r,y);ctx.lineTo(x,y-r);ctx.lineTo(x-r,y);ctx.closePath();}/**
* Draw a rectangle with rounded corners.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param r - The radius of the corners.
* @remarks
* http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
*/function drawRoundRect(ctx,x,y,w,h,r){const r2d=Math.PI/180;if(w-2*r<0){r=w/2;}//ensure that the radius isn't too large for x
if(h-2*r<0){r=h/2;}//ensure that the radius isn't too large for y
ctx.beginPath();ctx.moveTo(x+r,y);ctx.lineTo(x+w-r,y);ctx.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);ctx.lineTo(x+w,y+h-r);ctx.arc(x+w-r,y+h-r,r,0,r2d*90,false);ctx.lineTo(x+r,y+h);ctx.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);ctx.lineTo(x,y+r);ctx.arc(x+r,y+r,r,r2d*180,r2d*270,false);ctx.closePath();}/**
* Draw an ellipse.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param w - The width of the ellipse.
* @param h - The height of the ellipse.
* @remarks
* http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
*
* Postfix '_vis' added to discern it from standard method ellipse().
*/function drawEllipse(ctx,x,y,w,h){const kappa=0.5522848,ox=w/2*kappa,// control point offset horizontal
oy=h/2*kappa,// control point offset vertical
xe=x+w,// x-end
ye=y+h,// y-end
xm=x+w/2,// x-middle
ym=y+h/2;// y-middle
ctx.beginPath();ctx.moveTo(x,ym);ctx.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);ctx.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);ctx.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);ctx.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);ctx.closePath();}/**
* Draw an isometric cylinder.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param w - The width of the database.
* @param h - The height of the database.
* @remarks
* http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
*/function drawDatabase(ctx,x,y,w,h){const f=1/3;const wEllipse=w;const hEllipse=h*f;const kappa=0.5522848,ox=wEllipse/2*kappa,// control point offset horizontal
oy=hEllipse/2*kappa,// control point offset vertical
xe=x+wEllipse,// x-end
ye=y+hEllipse,// y-end
xm=x+wEllipse/2,// x-middle
ym=y+hEllipse/2,// y-middle
ymb=y+(h-hEllipse/2),// y-midlle, bottom ellipse
yeb=y+h;// y-end, bottom ellipse
ctx.beginPath();ctx.moveTo(xe,ym);ctx.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);ctx.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);ctx.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);ctx.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);ctx.lineTo(xe,ymb);ctx.bezierCurveTo(xe,ymb+oy,xm+ox,yeb,xm,yeb);ctx.bezierCurveTo(xm-ox,yeb,x,ymb+oy,x,ymb);ctx.lineTo(x,ym);}/**
* Draw a dashed line.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The start position on the x axis.
* @param y - The start position on the y axis.
* @param x2 - The end position on the x axis.
* @param y2 - The end position on the y axis.
* @param pattern - List of lengths starting with line and then alternating between space and line.
* @author David Jordan
* @remarks
* date 2012-08-08
* http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
*/function drawDashedLine(ctx,x,y,x2,y2,pattern){ctx.beginPath();ctx.moveTo(x,y);const patternLength=pattern.length;const dx=x2-x;const dy=y2-y;const slope=dy/dx;let distRemaining=Math.sqrt(dx*dx+dy*dy);let patternIndex=0;let draw=true;let xStep=0;let dashLength=+pattern[0];while(distRemaining>=0.1){dashLength=+pattern[patternIndex++%patternLength];if(dashLength>distRemaining){dashLength=distRemaining;}xStep=Math.sqrt(dashLength*dashLength/(1+slope*slope));xStep=dx<0?-xStep:xStep;x+=xStep;y+=slope*xStep;if(draw===true){ctx.lineTo(x,y);}else {ctx.moveTo(x,y);}distRemaining-=dashLength;draw=!draw;}}/**
* Draw a hexagon.
*
* @param ctx - The context this shape will be rendered to.
* @param x - The position of the center on the x axis.
* @param y - The position of the center on the y axis.
* @param r - The radius of the hexagon.
*/function drawHexagon(ctx,x,y,r){ctx.beginPath();const sides=6;const a=Math.PI*2/sides;ctx.moveTo(x+r,y);for(let i=1;i<sides;i++){ctx.lineTo(x+r*Math.cos(a*i),y+r*Math.sin(a*i));}ctx.closePath();}const shapeMap={circle:drawCircle,dashedLine:drawDashedLine,database:drawDatabase,diamond:drawDiamond,ellipse:drawEllipse,ellipse_vis:drawEllipse,hexagon:drawHexagon,roundRect:drawRoundRect,square:drawSquare,star:drawStar,triangle:drawTriangle,triangleDown:drawTriangleDown};/**
* Returns either custom or native drawing function base on supplied name.
*
* @param name - The name of the function. Either the name of a
* CanvasRenderingContext2D property or an export from shapes.ts without the
* draw prefix.
* @returns The function that can be used for rendering. In case of native
* CanvasRenderingContext2D function the API is normalized to
* `(ctx: CanvasRenderingContext2D, ...originalArgs) => void`.
*/function getShape(name){if(Object.prototype.hasOwnProperty.call(shapeMap,name)){return shapeMap[name];}else {return function(ctx,...args){CanvasRenderingContext2D.prototype[name].call(ctx,args);};}}/* eslint-disable no-prototype-builtins */ /* eslint-disable no-unused-vars */ /* eslint-disable no-var */ /**
* Parse a text source containing data in DOT language into a JSON object.
* The object contains two lists: one with nodes and one with edges.
*
* DOT language reference: http://www.graphviz.org/doc/info/lang.html
*
* DOT language attributes: http://graphviz.org/content/attrs
*
* @param {string} data Text containing a graph in DOT-notation
* @returns {object} graph An object containing two parameters:
* {Object[]} nodes
* {Object[]} edges
*
* -------------------------------------------
* TODO
* ====
*
* For label handling, this is an incomplete implementation. From docs (quote #3015):
*
* > the escape sequences "\n", "\l" and "\r" divide the label into lines, centered,
* > left-justified, and right-justified, respectively.
*
* Source: http://www.graphviz.org/content/attrs#kescString
*
* > As another aid for readability, dot allows double-quoted strings to span multiple physical
* > lines using the standard C convention of a backslash immediately preceding a newline
* > character
* > In addition, double-quoted strings can be concatenated using a '+' operator.
* > As HTML strings can contain newline characters, which are used solely for formatting,
* > the language does not allow escaped newlines or concatenation operators to be used
* > within them.
*
* - Currently, only '\\n' is handled
* - Note that text explicitly says 'labels'; the dot parser currently handles escape
* sequences in **all** strings.
*/function parseDOT(data){dot=data;return parseGraph();}// mapping of attributes from DOT (the keys) to vis.js (the values)
var NODE_ATTR_MAPPING={fontsize:"font.size",fontcolor:"font.color",labelfontcolor:"font.color",fontname:"font.face",color:["color.border","color.background"],fillcolor:"color.background",tooltip:"title",labeltooltip:"title"};var EDGE_ATTR_MAPPING=Object.create(NODE_ATTR_MAPPING);EDGE_ATTR_MAPPING.color="color.color";EDGE_ATTR_MAPPING.style="dashes";// token types enumeration
var TOKENTYPE={NULL:0,DELIMITER:1,IDENTIFIER:2,UNKNOWN:3};// map with all delimiters
var DELIMITERS={"{":true,"}":true,"[":true,"]":true,";":true,"=":true,",":true,"->":true,"--":true};var dot="";// current dot file
var index=0;// current index in dot file
var c="";// current token character in expr
var token="";// current token
var tokenType=TOKENTYPE.NULL;// type of the token
/**
* Get the first character from the dot file.
* The character is stored into the char c. If the end of the dot file is
* reached, the function puts an empty string in c.
*/function first(){index=0;c=dot.charAt(0);}/**
* Get the next character from the dot file.
* The character is stored into the char c. If the end of the dot file is
* reached, the function puts an empty string in c.
*/function next(){index++;c=dot.charAt(index);}/**
* Preview the next character from the dot file.
*
* @returns {string} cNext
*/function nextPreview(){return dot.charAt(index+1);}/**
* Test whether given character is alphabetic or numeric ( a-zA-Z_0-9.:# )
*
* @param {string} c
* @returns {boolean} isAlphaNumeric
*/function isAlphaNumeric(c){var charCode=c.charCodeAt(0);if(charCode<47){// #.
return charCode===35||charCode===46;}if(charCode<59){// 0-9 and :
return charCode>47;}if(charCode<91){// A-Z
return charCode>64;}if(charCode<96){// _
return charCode===95;}if(charCode<123){// a-z
return charCode>96;}return false;}/**
* Merge all options of object b into object b
*
* @param {object} a
* @param {object} b
* @returns {object} a
*/function merge(a,b){if(!a){a={};}if(b){for(var name in b){if(b.hasOwnProperty(name)){a[name]=b[name];}}}return a;}/**
* Set a value in an object, where the provided parameter name can be a
* path with nested parameters. For example:
*
* var obj = {a: 2};
* setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
*
* @param {object} obj
* @param {string} path A parameter name or dot-separated parameter path,
* like "color.highlight.border".
* @param {*} value
*/function setValue(obj,path,value){var keys=path.split(".");var o=obj;while(keys.length){var key=keys.shift();if(keys.length){// this isn't the end point
if(!o[key]){o[key]={};}o=o[key];}else {// this is the end point
o[key]=value;}}}/**
* Add a node to a graph object. If there is already a node with
* the same id, their attributes will be merged.
*
* @param {object} graph
* @param {object} node
*/function addNode(graph,node){var i,len;var current=null;// find root graph (in case of subgraph)
var graphs=[graph];// list with all graphs from current graph to root graph
var root=graph;while(root.parent){graphs.push(root.parent);root=root.parent;}// find existing node (at root level) by its id
if(root.nodes){for(i=0,len=root.nodes.length;i<len;i++){if(node.id===root.nodes[i].id){current=root.nodes[i];break;}}}if(!current){// this is a new node
current={id:node.id};if(graph.node){// clone default attributes
current.attr=merge(current.attr,graph.node);}}// add node to this (sub)graph and all its parent graphs
for(i=graphs.length-1;i>=0;i--){var g=graphs[i];if(!g.nodes){g.nodes=[];}if(g.nodes.indexOf(current)===-1){g.nodes.push(current);}}// merge attributes
if(node.attr){current.attr=merge(current.attr,node.attr);}}/**
* Add an edge to a graph object
*
* @param {object} graph
* @param {object} edge
*/function addEdge(graph,edge){if(!graph.edges){graph.edges=[];}graph.edges.push(edge);if(graph.edge){var attr=merge({},graph.edge);// clone default attributes
edge.attr=merge(attr,edge.attr);// merge attributes
}}/**
* Create an edge to a graph object
*
* @param {object} graph
* @param {string | number | object} from
* @param {string | number | object} to
* @param {string} type
* @param {object | null} attr
* @returns {object} edge
*/function createEdge(graph,from,to,type,attr){var edge={from:from,to:to,type:type};if(graph.edge){edge.attr=merge({},graph.edge);// clone default attributes
}edge.attr=merge(edge.attr||{},attr);// merge attributes
// Move arrows attribute from attr to edge temporally created in
// parseAttributeList().
if(attr!=null){if(attr.hasOwnProperty("arrows")&&attr["arrows"]!=null){edge["arrows"]={to:{enabled:true,type:attr.arrows.type}};attr["arrows"]=null;}}return edge;}/**
* Get next token in the current dot file.
* The token and token type are available as token and tokenType
*/function getToken(){tokenType=TOKENTYPE.NULL;token="";// skip over whitespaces
while(c===" "||c==="\t"||c==="\n"||c==="\r"){// space, tab, enter
next();}do{var isComment=false;// skip comment
if(c==="#"){// find the previous non-space character
var i=index-1;while(dot.charAt(i)===" "||dot.charAt(i)==="\t"){i--;}if(dot.charAt(i)==="\n"||dot.charAt(i)===""){// the # is at the start of a line, this is indeed a line comment
while(c!=""&&c!="\n"){next();}isComment=true;}}if(c==="/"&&nextPreview()==="/"){// skip line comment
while(c!=""&&c!="\n"){next();}isComment=true;}if(c==="/"&&nextPreview()==="*"){// skip block comment
while(c!=""){if(c==="*"&&nextPreview()==="/"){// end of block comment found. skip these last two characters
next();next();break;}else {next();}}isComment=true;}// skip over whitespaces
while(c===" "||c==="\t"||c==="\n"||c==="\r"){// space, tab, enter
next();}}while(isComment);// check for end of dot file
if(c===""){// token is still empty
tokenType=TOKENTYPE.DELIMITER;return;}// check for delimiters consisting of 2 characters
var c2=c+nextPreview();if(DELIMITERS[c2]){tokenType=TOKENTYPE.DELIMITER;token=c2;next();next();return;}// check for delimiters consisting of 1 character
if(DELIMITERS[c]){tokenType=TOKENTYPE.DELIMITER;token=c;next();return;}// check for an identifier (number or string)
// TODO: more precise parsing of numbers/strings (and the port separator ':')
if(isAlphaNumeric(c)||c==="-"){token+=c;next();while(isAlphaNumeric(c)){token+=c;next();}if(token==="false"){token=false;// convert to boolean
}else if(token==="true"){token=true;// convert to boolean
}else if(!isNaN(Number(token))){token=Number(token);// convert to number
}tokenType=TOKENTYPE.IDENTIFIER;return;}// check for a string enclosed by double quotes
if(c==='"'){next();while(c!=""&&(c!='"'||c==='"'&&nextPreview()==='"')){if(c==='"'){// skip the escape character
token+=c;next();}else if(c==="\\"&&nextPreview()==="n"){// Honor a newline escape sequence
token+="\n";next();}else {token+=c;}next();}if(c!='"'){throw newSyntaxError('End of string " expected');}next();tokenType=TOKENTYPE.IDENTIFIER;return;}// something unknown is found, wrong characters, a syntax error
tokenType=TOKENTYPE.UNKNOWN;while(c!=""){token+=c;next();}throw new SyntaxError('Syntax error in part "'+chop(token,30)+'"');}/**
* Parse a graph.
*
* @returns {object} graph
*/function parseGraph(){var graph={};first();getToken();// optional strict keyword
if(token==="strict"){graph.strict=true;getToken();}// graph or digraph keyword
if(token==="graph"||token==="digraph"){graph.type=token;getToken();}// optional graph id
if(tokenType===TOKENTYPE.IDENTIFIER){graph.id=token;getToken();}// open angle bracket
if(token!="{"){throw newSyntaxError("Angle bracket { expected");}getToken();// statements
parseStatements(graph);// close angle bracket
if(token!="}"){throw newSyntaxError("Angle bracket } expected");}getToken();// end of file
if(token!==""){throw newSyntaxError("End of file expected");}getToken();// remove temporary default options
delete graph.node;delete graph.edge;delete graph.graph;return graph;}/**
* Parse a list with statements.
*
* @param {object} graph
*/function parseStatements(graph){while(token!==""&&token!="}"){parseStatement(graph);if(token===";"){getToken();}}}/**
* Parse a single statement. Can be a an attribute statement, node
* statement, a series of node statements and edge statements, or a
* parameter.
*
* @param {object} graph
*/function parseStatement(graph){// parse subgraph
var subgraph=parseSubgraph(graph);if(subgraph){// edge statements
parseEdge(graph,subgraph);return;}// parse an attribute statement
var attr=parseAttributeStatement(graph);if(attr){return;}// parse node
if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Identifier expected");}var id=token;// id can be a string or a number
getToken();if(token==="="){// id statement
getToken();if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Identifier expected");}graph[id]=token;getToken();// TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
}else {parseNodeStatement(graph,id);}}/**
* Parse a subgraph
*
* @param {object} graph parent graph object
* @returns {object | null} subgraph
*/function parseSubgraph(graph){var subgraph=null;// optional subgraph keyword
if(token==="subgraph"){subgraph={};subgraph.type="subgraph";getToken();// optional graph id
if(tokenType===TOKENTYPE.IDENTIFIER){subgraph.id=token;getToken();}}// open angle bracket
if(token==="{"){getToken();if(!subgraph){subgraph={};}subgraph.parent=graph;subgraph.node=graph.node;subgraph.edge=graph.edge;subgraph.graph=graph.graph;// statements
parseStatements(subgraph);// close angle bracket
if(token!="}"){throw newSyntaxError("Angle bracket } expected");}getToken();// remove temporary default options
delete subgraph.node;delete subgraph.edge;delete subgraph.graph;delete subgraph.parent;// register at the parent graph
if(!graph.subgraphs){graph.subgraphs=[];}graph.subgraphs.push(subgraph);}return subgraph;}/**
* parse an attribute statement like "node [shape=circle fontSize=16]".
* Available keywords are 'node', 'edge', 'graph'.
* The previous list with default attributes will be replaced
*
* @param {object} graph
* @returns {string | null} keyword Returns the name of the parsed attribute
* (node, edge, graph), or null if nothing
* is parsed.
*/function parseAttributeStatement(graph){// attribute statements
if(token==="node"){getToken();// node attributes
graph.node=parseAttributeList();return "node";}else if(token==="edge"){getToken();// edge attributes
graph.edge=parseAttributeList();return "edge";}else if(token==="graph"){getToken();// graph attributes
graph.graph=parseAttributeList();return "graph";}return null;}/**
* parse a node statement
*
* @param {object} graph
* @param {string | number} id
*/function parseNodeStatement(graph,id){// node statement
var node={id:id};var attr=parseAttributeList();if(attr){node.attr=attr;}addNode(graph,node);// edge statements
parseEdge(graph,id);}/**
* Parse an edge or a series of edges
*
* @param {object} graph
* @param {string | number} from Id of the from node
*/function parseEdge(graph,from){while(token==="->"||token==="--"){var to;var type=token;getToken();var subgraph=parseSubgraph(graph);if(subgraph){to=subgraph;}else {if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Identifier or subgraph expected");}to=token;addNode(graph,{id:to});getToken();}// parse edge attributes
var attr=parseAttributeList();// create edge
var edge=createEdge(graph,from,to,type,attr);addEdge(graph,edge);from=to;}}/**
* Parse a set with attributes,
* for example [label="1.000", shape=solid]
*
* @returns {object | null} attr
*/function parseAttributeList(){var i;var attr=null;// edge styles of dot and vis
var edgeStyles={dashed:true,solid:false,dotted:[1,5]};/**
* Define arrow types.
* vis currently supports types defined in 'arrowTypes'.
* Details of arrow shapes are described in
* http://www.graphviz.org/content/arrow-shapes
*/var arrowTypes={dot:"circle",box:"box",crow:"crow",curve:"curve",icurve:"inv_curve",normal:"triangle",inv:"inv_triangle",diamond:"diamond",tee:"bar",vee:"vee"};/**
* 'attr_list' contains attributes for checking if some of them are affected
* later. For instance, both of 'arrowhead' and 'dir' (edge style defined
* in DOT) make changes to 'arrows' attribute in vis.
*/var attr_list=new Array();var attr_names=new Array();// used for checking the case.
// parse attributes
while(token==="["){getToken();attr={};while(token!==""&&token!="]"){if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Attribute name expected");}var name=token;getToken();if(token!="="){throw newSyntaxError("Equal sign = expected");}getToken();if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Attribute value expected");}var value=token;// convert from dot style to vis
if(name==="style"){value=edgeStyles[value];}var arrowType;if(name==="arrowhead"){arrowType=arrowTypes[value];name="arrows";value={to:{enabled:true,type:arrowType}};}if(name==="arrowtail"){arrowType=arrowTypes[value];name="arrows";value={from:{enabled:true,type:arrowType}};}attr_list.push({attr:attr,name:name,value:value});attr_names.push(name);getToken();if(token==","){getToken();}}if(token!="]"){throw newSyntaxError("Bracket ] expected");}getToken();}/**
* As explained in [1], graphviz has limitations for combination of
* arrow[head|tail] and dir. If attribute list includes 'dir',
* following cases just be supported.
* 1. both or none + arrowhead, arrowtail
* 2. forward + arrowhead (arrowtail is not affedted)
* 3. back + arrowtail (arrowhead is not affected)
* [1] https://www.graphviz.org/doc/info/attrs.html#h:undir_note
*/if(attr_names.includes("dir")){var idx={};// get index of 'arrows' and 'dir'
idx.arrows={};for(i=0;i<attr_list.length;i++){if(attr_list[i].name==="arrows"){if(attr_list[i].value.to!=null){idx.arrows.to=i;}else if(attr_list[i].value.from!=null){idx.arrows.from=i;}else {throw newSyntaxError("Invalid value of arrows");}}else if(attr_list[i].name==="dir"){idx.dir=i;}}// first, add default arrow shape if it is not assigned to avoid error
var dir_type=attr_list[idx.dir].value;if(!attr_names.includes("arrows")){if(dir_type==="both"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{to:{enabled:true}}});idx.arrows.to=attr_list.length-1;attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{from:{enabled:true}}});idx.arrows.from=attr_list.length-1;}else if(dir_type==="forward"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{to:{enabled:true}}});idx.arrows.to=attr_list.length-1;}else if(dir_type==="back"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{from:{enabled:true}}});idx.arrows.from=attr_list.length-1;}else if(dir_type==="none"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:""});idx.arrows.to=attr_list.length-1;}else {throw newSyntaxError('Invalid dir type "'+dir_type+'"');}}var from_type;var to_type;// update 'arrows' attribute from 'dir'.
if(dir_type==="both"){// both of shapes of 'from' and 'to' are given
if(idx.arrows.to&&idx.arrows.from){to_type=attr_list[idx.arrows.to].value.to.type;from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};attr_list.splice(idx.arrows.from,1);// shape of 'to' is assigned and use default to 'from'
}else if(idx.arrows.to){to_type=attr_list[idx.arrows.to].value.to.type;from_type="arrow";attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// only shape of 'from' is assigned and use default for 'to'
}else if(idx.arrows.from){to_type="arrow";from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};}}else if(dir_type==="back"){// given both of shapes, but use only 'from'
if(idx.arrows.to&&idx.arrows.from){to_type="";from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// given shape of 'to', but does not use it
}else if(idx.arrows.to){to_type="";from_type="arrow";idx.arrows.from=idx.arrows.to;attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// assign given 'from' shape
}else if(idx.arrows.from){to_type="";from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};}attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{from:{enabled:true,type:attr_list[idx.arrows.from].value.from.type}}};}else if(dir_type==="none"){var idx_arrow;if(idx.arrows.to){idx_arrow=idx.arrows.to;}else {idx_arrow=idx.arrows.from;}attr_list[idx_arrow]={attr:attr_list[idx_arrow].attr,name:attr_list[idx_arrow].name,value:""};}else if(dir_type==="forward"){// given both of shapes, but use only 'to'
if(idx.arrows.to&&idx.arrows.from){to_type=attr_list[idx.arrows.to].value.to.type;from_type="";attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// assign given 'to' shape
}else if(idx.arrows.to){to_type=attr_list[idx.arrows.to].value.to.type;from_type="";attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// given shape of 'from', but does not use it
}else if(idx.arrows.from){to_type="arrow";from_type="";idx.arrows.to=idx.arrows.from;attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};}attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:attr_list[idx.arrows.to].value.to.type}}};}else {throw newSyntaxError('Invalid dir type "'+dir_type+'"');}// remove 'dir' attribute no need anymore
attr_list.splice(idx.dir,1);}// parse 'penwidth'
var nof_attr_list;if(attr_names.includes("penwidth")){var tmp_attr_list=[];nof_attr_list=attr_list.length;for(i=0;i<nof_attr_list;i++){// exclude 'width' from attr_list if 'penwidth' exists
if(attr_list[i].name!=="width"){if(attr_list[i].name==="penwidth"){attr_list[i].name="width";}tmp_attr_list.push(attr_list[i]);}}attr_list=tmp_attr_list;}nof_attr_list=attr_list.length;for(i=0;i<nof_attr_list;i++){setValue(attr_list[i].attr,attr_list[i].name,attr_list[i].value);}return attr;}/**
* Create a syntax error with extra information on current token and index.
*
* @param {string} message
* @returns {SyntaxError} err
*/function newSyntaxError(message){return new SyntaxError(message+', got "'+chop(token,30)+'" (char '+index+")");}/**
* Chop off text after a maximum length
*
* @param {string} text
* @param {number} maxLength
* @returns {string}
*/function chop(text,maxLength){return text.length<=maxLength?text:text.substr(0,27)+"...";}/**
* Execute a function fn for each pair of elements in two arrays
*
* @param {Array | *} array1
* @param {Array | *} array2
* @param {Function} fn
*/function forEach2(array1,array2,fn){if(Array.isArray(array1)){array1.forEach(function(elem1){if(Array.isArray(array2)){array2.forEach(function(elem2){fn(elem1,elem2);});}else {fn(elem1,array2);}});}else {if(Array.isArray(array2)){array2.forEach(function(elem2){fn(array1,elem2);});}else {fn(array1,array2);}}}/**
* Set a nested property on an object
* When nested objects are missing, they will be created.
* For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}}
*
* @param {object} object
* @param {string} path A dot separated string like 'font.color'
* @param {*} value Value for the property
* @returns {object} Returns the original object, allows for chaining.
*/function setProp(object,path,value){var names=path.split(".");var prop=names.pop();// traverse over the nested objects
var obj=object;for(var i=0;i<names.length;i++){var name=names[i];if(!(name in obj)){obj[name]={};}obj=obj[name];}// set the property value
obj[prop]=value;return object;}/**
* Convert an object with DOT attributes to their vis.js equivalents.
*
* @param {object} attr Object with DOT attributes
* @param {object} mapping
* @returns {object} Returns an object with vis.js attributes
*/function convertAttr(attr,mapping){var converted={};for(var prop in attr){if(attr.hasOwnProperty(prop)){var visProp=mapping[prop];if(Array.isArray(visProp)){visProp.forEach(function(visPropI){setProp(converted,visPropI,attr[prop]);});}else if(typeof visProp==="string"){setProp(converted,visProp,attr[prop]);}else {setProp(converted,prop,attr[prop]);}}}return converted;}/**
* Convert a string containing a graph in DOT language into a map containing
* with nodes and edges in the format of graph.
*
* @param {string} data Text containing a graph in DOT-notation
* @returns {object} graphData
*/function DOTToGraph(data){// parse the DOT file
var dotData=parseDOT(data);var graphData={nodes:[],edges:[],options:{}};// copy the nodes
if(dotData.nodes){dotData.nodes.forEach(function(dotNode){var graphNode={id:dotNode.id,label:String(dotNode.label||dotNode.id)};merge(graphNode,convertAttr(dotNode.attr,NODE_ATTR_MAPPING));if(graphNode.image){graphNode.shape="image";}graphData.nodes.push(graphNode);});}// copy the edges
if(dotData.edges){/**
* Convert an edge in DOT format to an edge with VisGraph format
*
* @param {object} dotEdge
* @returns {object} graphEdge
*/var convertEdge=function(dotEdge){var graphEdge={from:dotEdge.from,to:dotEdge.to};merge(graphEdge,convertAttr(dotEdge.attr,EDGE_ATTR_MAPPING));// Add arrows attribute to default styled arrow.
// The reason why default style is not added in parseAttributeList() is
// because only default is cleared before here.
if(graphEdge.arrows==null&&dotEdge.type==="->"){graphEdge.arrows="to";}return graphEdge;};dotData.edges.forEach(function(dotEdge){var from,to;if(dotEdge.from instanceof Object){from=dotEdge.from.nodes;}else {from={id:dotEdge.from};}if(dotEdge.to instanceof Object){to=dotEdge.to.nodes;}else {to={id:dotEdge.to};}if(dotEdge.from instanceof Object&&dotEdge.from.edges){dotEdge.from.edges.forEach(function(subEdge){var graphEdge=convertEdge(subEdge);graphData.edges.push(graphEdge);});}forEach2(from,to,function(from,to){var subEdge=createEdge(graphData,from.id,to.id,dotEdge.type,dotEdge.attr);var graphEdge=convertEdge(subEdge);graphData.edges.push(graphEdge);});if(dotEdge.to instanceof Object&&dotEdge.to.edges){dotEdge.to.edges.forEach(function(subEdge){var graphEdge=convertEdge(subEdge);graphData.edges.push(graphEdge);});}});}// copy the options
if(dotData.attr){graphData.options=dotData.attr;}return graphData;}/**
* Convert Gephi to Vis.
*
* @param gephiJSON - The parsed JSON data in Gephi format.
* @param optionsObj - Additional options.
* @returns The converted data ready to be used in Vis.
*/function parseGephi(gephiJSON,optionsObj){const options={edges:{inheritColor:false},nodes:{fixed:false,parseColor:false}};if(optionsObj!=null){if(optionsObj.fixed!=null){options.nodes.fixed=optionsObj.fixed;}if(optionsObj.parseColor!=null){options.nodes.parseColor=optionsObj.parseColor;}if(optionsObj.inheritColor!=null){options.edges.inheritColor=optionsObj.inheritColor;}}const gEdges=gephiJSON.edges;const vEdges=gEdges.map(gEdge=>{const vEdge={from:gEdge.source,id:gEdge.id,to:gEdge.target};if(gEdge.attributes!=null){vEdge.attributes=gEdge.attributes;}if(gEdge.label!=null){vEdge.label=gEdge.label;}if(gEdge.attributes!=null&&gEdge.attributes.title!=null){vEdge.title=gEdge.attributes.title;}if(gEdge.type==="Directed"){vEdge.arrows="to";}// edge['value'] = gEdge.attributes != null ? gEdge.attributes.Weight : undefined;
// edge['width'] = edge['value'] != null ? undefined : edgegEdge.size;
if(gEdge.color&&options.edges.inheritColor===false){vEdge.color=gEdge.color;}return vEdge;});const vNodes=gephiJSON.nodes.map(gNode=>{const vNode={id:gNode.id,fixed:options.nodes.fixed&&gNode.x!=null&&gNode.y!=null};if(gNode.attributes!=null){vNode.attributes=gNode.attributes;}if(gNode.label!=null){vNode.label=gNode.label;}if(gNode.size!=null){vNode.size=gNode.size;}if(gNode.attributes!=null&&gNode.attributes.title!=null){vNode.title=gNode.attributes.title;}if(gNode.title!=null){vNode.title=gNode.title;}if(gNode.x!=null){vNode.x=gNode.x;}if(gNode.y!=null){vNode.y=gNode.y;}if(gNode.color!=null){if(options.nodes.parseColor===true){vNode.color=gNode.color;}else {vNode.color={background:gNode.color,border:gNode.color,highlight:{background:gNode.color,border:gNode.color},hover:{background:gNode.color,border:gNode.color}};}}return vNode;});return {nodes:vNodes,edges:vEdges};}const en={addDescription:"Click in an empty space to place a new node.",addEdge:"Add Edge",addNode:"Add Node",back:"Back",close:"Close",createEdgeError:"Cannot link edges to a cluster.",del:"Delete selected",deleteClusterError:"Clusters cannot be deleted.",edgeDescription:"Click on a node and drag the edge to another node to connect them.",edit:"Edit",editClusterError:"Clusters cannot be edited.",editEdge:"Edit Edge",editEdgeDescription:"Click on the control points and drag them to a node to connect to it.",editNode:"Edit Node"};// German
const de={addDescription:"Klicke auf eine freie Stelle, um einen neuen Knoten zu plazieren.",addEdge:"Kante hinzuf\u00fcgen",addNode:"Knoten hinzuf\u00fcgen",back:"Zur\u00fcck",close:"Schließen",createEdgeError:"Es ist nicht m\u00f6glich, Kanten mit Clustern zu verbinden.",del:"L\u00f6sche Auswahl",deleteClusterError:"Cluster k\u00f6nnen nicht gel\u00f6scht werden.",edgeDescription:"Klicke auf einen Knoten und ziehe die Kante zu einem anderen Knoten, um diese zu verbinden.",edit:"Editieren",editClusterError:"Cluster k\u00f6nnen nicht editiert werden.",editEdge:"Kante editieren",editEdgeDescription:"Klicke auf die Verbindungspunkte und ziehe diese auf einen Knoten, um sie zu verbinden.",editNode:"Knoten editieren"};// Spanish
const es={addDescription:"Haga clic en un lugar vac\u00edo para colocar un nuevo nodo.",addEdge:"A\u00f1adir arista",addNode:"A\u00f1adir nodo",back:"Atr\u00e1s",close:"Cerrar",createEdgeError:"No se puede conectar una arista a un grupo.",del:"Eliminar selecci\u00f3n",deleteClusterError:"No es posible eliminar grupos.",edgeDescription:"Haga clic en un nodo y arrastre la arista hacia otro nodo para conectarlos.",edit:"Editar",editClusterError:"No es posible editar grupos.",editEdge:"Editar arista",editEdgeDescription:"Haga clic en un punto de control y arrastrelo a un nodo para conectarlo.",editNode:"Editar nodo"};//Italiano
const it={addDescription:"Clicca per aggiungere un nuovo nodo",addEdge:"Aggiungi un vertice",addNode:"Aggiungi un nodo",back:"Indietro",close:"Chiudere",createEdgeError:"Non si possono collegare vertici ad un cluster",del:"Cancella la selezione",deleteClusterError:"I cluster non possono essere cancellati",edgeDescription:"Clicca su un nodo e trascinalo ad un altro nodo per connetterli.",edit:"Modifica",editClusterError:"I clusters non possono essere modificati.",editEdge:"Modifica il vertice",editEdgeDescription:"Clicca sui Punti di controllo e trascinali ad un nodo per connetterli.",editNode:"Modifica il nodo"};// Dutch
const nl={addDescription:"Klik op een leeg gebied om een nieuwe node te maken.",addEdge:"Link toevoegen",addNode:"Node toevoegen",back:"Terug",close:"Sluiten",createEdgeError:"Kan geen link maken naar een cluster.",del:"Selectie verwijderen",deleteClusterError:"Clusters kunnen niet worden verwijderd.",edgeDescription:"Klik op een node en sleep de link naar een andere node om ze te verbinden.",edit:"Wijzigen",editClusterError:"Clusters kunnen niet worden aangepast.",editEdge:"Link wijzigen",editEdgeDescription:"Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.",editNode:"Node wijzigen"};// Portuguese Brazil
const pt={addDescription:"Clique em um espaço em branco para adicionar um novo nó",addEdge:"Adicionar aresta",addNode:"Adicionar nó",back:"Voltar",close:"Fechar",createEdgeError:"Não foi possível linkar arestas a um cluster.",del:"Remover selecionado",deleteClusterError:"Clusters não puderam ser removidos.",edgeDescription:"Clique em um nó e arraste a aresta até outro nó para conectá-los",edit:"Editar",editClusterError:"Clusters não puderam ser editados.",editEdge:"Editar aresta",editEdgeDescription:"Clique nos pontos de controle e os arraste para um nó para conectá-los",editNode:"Editar nó"};// Russian
const ru={addDescription:"Кликните в свободное место, чтобы добавить новый узел.",addEdge:"Добавить ребро",addNode:"Добавить узел",back:"Назад",close:"Закрывать",createEdgeError:"Невозможно соединить ребра в кластер.",del:"Удалить выбранное",deleteClusterError:"Кластеры не могут быть удалены",edgeDescription:"Кликните на узел и протяните ребро к другому узлу, чтобы соединить их.",edit:"Редактировать",editClusterError:"Кластеры недоступны для редактирования.",editEdge:"Редактировать ребро",editEdgeDescription:"Кликните на контрольные точки и перетащите их в узел, чтобы подключиться к нему.",editNode:"Редактировать узел"};// Chinese
const cn={addDescription:"单击空白处放置新节点。",addEdge:"添加连接线",addNode:"添加节点",back:"返回",close:"關閉",createEdgeError:"无法将连接线连接到群集。",del:"删除选定",deleteClusterError:"无法删除群集。",edgeDescription:"单击某个节点并将该连接线拖动到另一个节点以连接它们。",edit:"编辑",editClusterError:"无法编辑群集。",editEdge:"编辑连接线",editEdgeDescription:"单击控制节点并将它们拖到节点上连接。",editNode:"编辑节点"};// Ukrainian
const uk={addDescription:"Kлікніть на вільне місце, щоб додати новий вузол.",addEdge:"Додати край",addNode:"Додати вузол",back:"Назад",close:"Закрити",createEdgeError:"Не можливо об'єднати краї в групу.",del:"Видалити обране",deleteClusterError:"Групи не можуть бути видалені.",edgeDescription:"Клікніть на вузол і перетягніть край до іншого вузла, щоб їх з'єднати.",edit:"Редагувати",editClusterError:"Групи недоступні для редагування.",editEdge:"Редагувати край",editEdgeDescription:"Клікніть на контрольні точки і перетягніть їх у вузол, щоб підключитися до нього.",editNode:"Редагувати вузол"};// French
const fr={addDescription:"Cliquez dans un endroit vide pour placer un nœud.",addEdge:"Ajouter un lien",addNode:"Ajouter un nœud",back:"Retour",close:"Fermer",createEdgeError:"Impossible de créer un lien vers un cluster.",del:"Effacer la sélection",deleteClusterError:"Les clusters ne peuvent pas être effacés.",edgeDescription:"Cliquez sur un nœud et glissez le lien vers un autre nœud pour les connecter.",edit:"Éditer",editClusterError:"Les clusters ne peuvent pas être édités.",editEdge:"Éditer le lien",editEdgeDescription:"Cliquez sur les points de contrôle et glissez-les pour connecter un nœud.",editNode:"Éditer le nœud"};// Czech
const cs={addDescription:"Kluknutím do prázdného prostoru můžete přidat nový vrchol.",addEdge:"Přidat hranu",addNode:"Přidat vrchol",back:"Zpět",close:"Zavřít",createEdgeError:"Nelze připojit hranu ke shluku.",del:"Smazat výběr",deleteClusterError:"Nelze mazat shluky.",edgeDescription:"Přetažením z jednoho vrcholu do druhého můžete spojit tyto vrcholy novou hranou.",edit:"Upravit",editClusterError:"Nelze upravovat shluky.",editEdge:"Upravit hranu",editEdgeDescription:"Přetažením kontrolního vrcholu hrany ji můžete připojit k jinému vrcholu.",editNode:"Upravit vrchol"};var locales=/*#__PURE__*/Object.freeze({__proto__:null,cn:cn,cs:cs,de:de,en:en,es:es,fr:fr,it:it,nl:nl,pt:pt,ru:ru,uk:uk});/**
* Normalizes language code into the format used internally.
*
* @param locales - All the available locales.
* @param rawCode - The original code as supplied by the user.
* @returns Language code in the format language-COUNTRY or language, eventually
* fallbacks to en.
*/function normalizeLanguageCode(locales,rawCode){try{const[rawLanguage,rawCountry]=rawCode.split(/[-_ /]/,2);const language=rawLanguage!=null?rawLanguage.toLowerCase():null;const country=rawCountry!=null?rawCountry.toUpperCase():null;if(language&&country){const code=language+"-"+country;if(Object.prototype.hasOwnProperty.call(locales,code)){return code;}else {console.warn(`Unknown variant ${country} of language ${language}.`);}}if(language){const code=language;if(Object.prototype.hasOwnProperty.call(locales,code)){return code;}else {console.warn(`Unknown language ${language}`);}}console.warn(`Unknown locale ${rawCode}, falling back to English.`);return "en";}catch(error){console.error(error);console.warn(`Unexpected error while normalizing locale ${rawCode}, falling back to English.`);return "en";}}/**
* Associates a canvas to a given image, containing a number of renderings
* of the image at various sizes.
*
* This technique is known as 'mipmapping'.
*
* NOTE: Images can also be of type 'data:svg+xml`. This code also works
* for svg, but the mipmapping may not be necessary.
*
* @param {Image} image
*/class CachedImage{/**
* @ignore
*/constructor(){this.NUM_ITERATIONS=4;// Number of items in the coordinates array
this.image=new Image();this.canvas=document.createElement("canvas");}/**
* Called when the image has been successfully loaded.
*/init(){if(this.initialized())return;this.src=this.image.src;// For same interface with Image
const w=this.image.width;const h=this.image.height;// Ease external access
this.width=w;this.height=h;const h2=Math.floor(h/2);const h4=Math.floor(h/4);const h8=Math.floor(h/8);const h16=Math.floor(h/16);const w2=Math.floor(w/2);const w4=Math.floor(w/4);const w8=Math.floor(w/8);const w16=Math.floor(w/16);// Make canvas as small as possible
this.canvas.width=3*w4;this.canvas.height=h2;// Coordinates and sizes of images contained in the canvas
// Values per row: [top x, left y, width, height]
this.coordinates=[[0,0,w2,h2],[w2,0,w4,h4],[w2,h4,w8,h8],[5*w8,h4,w16,h16]];this._fillMipMap();}/**
* @returns {boolean} true if init() has been called, false otherwise.
*/initialized(){return this.coordinates!==undefined;}/**
* Redraw main image in various sizes to the context.
*
* The rationale behind this is to reduce artefacts due to interpolation
* at differing zoom levels.
*
* Source: http://stackoverflow.com/q/18761404/1223531
*
* This methods takes the resizing out of the drawing loop, in order to
* reduce performance overhead.
*
* TODO: The code assumes that a 2D context can always be gotten. This is
* not necessarily true! OTOH, if not true then usage of this class
* is senseless.
*
* @private
*/_fillMipMap(){const ctx=this.canvas.getContext("2d");// First zoom-level comes from the image
const to=this.coordinates[0];ctx.drawImage(this.image,to[0],to[1],to[2],to[3]);// The rest are copy actions internal to the canvas/context
for(let iterations=1;iterations<this.NUM_ITERATIONS;iterations++){const from=this.coordinates[iterations-1];const to=this.coordinates[iterations];ctx.drawImage(this.canvas,from[0],from[1],from[2],from[3],to[0],to[1],to[2],to[3]);}}/**
* Draw the image, using the mipmap if necessary.
*
* MipMap is only used if param factor > 2; otherwise, original bitmap
* is resized. This is also used to skip mipmap usage, e.g. by setting factor = 1
*
* Credits to 'Alex de Mulder' for original implementation.
*
* @param {CanvasRenderingContext2D} ctx context on which to draw zoomed image
* @param {Float} factor scale factor at which to draw
* @param {number} left
* @param {number} top
* @param {number} width
* @param {number} height
*/drawImageAtPosition(ctx,factor,left,top,width,height){if(!this.initialized())return;//can't draw image yet not intialized
if(factor>2){// Determine which zoomed image to use
factor*=0.5;let iterations=0;while(factor>2&&iterations<this.NUM_ITERATIONS){factor*=0.5;iterations+=1;}if(iterations>=this.NUM_ITERATIONS){iterations=this.NUM_ITERATIONS-1;}//console.log("iterations: " + iterations);
const from=this.coordinates[iterations];ctx.drawImage(this.canvas,from[0],from[1],from[2],from[3],left,top,width,height);}else {// Draw image directly
ctx.drawImage(this.image,left,top,width,height);}}}/**
* This callback is a callback that accepts an Image.
*
* @callback ImageCallback
* @param {Image} image
*/ /**
* This class loads images and keeps them stored.
*
* @param {ImageCallback} callback
*/class Images{/**
* @param {ImageCallback} callback
*/constructor(callback){this.images={};this.imageBroken={};this.callback=callback;}/**
* @param {string} url The original Url that failed to load, if the broken image is successfully loaded it will be added to the cache using this Url as the key so that subsequent requests for this Url will return the broken image
* @param {string} brokenUrl Url the broken image to try and load
* @param {Image} imageToLoadBrokenUrlOn The image object
*/_tryloadBrokenUrl(url,brokenUrl,imageToLoadBrokenUrlOn){//If these parameters aren't specified then exit the function because nothing constructive can be done
if(url===undefined||imageToLoadBrokenUrlOn===undefined)return;if(brokenUrl===undefined){console.warn("No broken url image defined");return;}//Clear the old subscription to the error event and put a new in place that only handle errors in loading the brokenImageUrl
imageToLoadBrokenUrlOn.image.onerror=()=>{console.error("Could not load brokenImage:",brokenUrl);// cache item will contain empty image, this should be OK for default
};//Set the source of the image to the brokenUrl, this is actually what kicks off the loading of the broken image
imageToLoadBrokenUrlOn.image.src=brokenUrl;}/**
*
* @param {vis.Image} imageToRedrawWith
* @private
*/_redrawWithImage(imageToRedrawWith){if(this.callback){this.callback(imageToRedrawWith);}}/**
* @param {string} url Url of the image
* @param {string} brokenUrl Url of an image to use if the url image is not found
* @returns {Image} img The image object
*/load(url,brokenUrl){//Try and get the image from the cache, if successful then return the cached image
const cachedImage=this.images[url];if(cachedImage)return cachedImage;//Create a new image
const img=new CachedImage();// Need to add to cache here, otherwise final return will spawn different copies of the same image,
// Also, there will be multiple loads of the same image.
this.images[url]=img;//Subscribe to the event that is raised if the image loads successfully
img.image.onload=()=>{// Properly init the cached item and then request a redraw
this._fixImageCoordinates(img.image);img.init();this._redrawWithImage(img);};//Subscribe to the event that is raised if the image fails to load
img.image.onerror=()=>{console.error("Could not load image:",url);//Try and load the image specified by the brokenUrl using
this._tryloadBrokenUrl(url,brokenUrl,img);};//Set the source of the image to the url, this is what actually kicks off the loading of the image
img.image.src=url;//Return the new image
return img;}/**
* IE11 fix -- thanks dponch!
*
* Local helper function
*
* @param {vis.Image} imageToCache
* @private
*/_fixImageCoordinates(imageToCache){if(imageToCache.width===0){document.body.appendChild(imageToCache);imageToCache.width=imageToCache.offsetWidth;imageToCache.height=imageToCache.offsetHeight;document.body.removeChild(imageToCache);}}}/**
* This class can store groups and options specific for groups.
*/class Groups{/**
* @ignore
*/constructor(){this.clear();this._defaultIndex=0;this._groupIndex=0;this._defaultGroups=[{border:"#2B7CE9",background:"#97C2FC",highlight:{border:"#2B7CE9",background:"#D2E5FF"},hover:{border:"#2B7CE9",background:"#D2E5FF"}},// 0: blue
{border:"#FFA500",background:"#FFFF00",highlight:{border:"#FFA500",background:"#FFFFA3"},hover:{border:"#FFA500",background:"#FFFFA3"}},// 1: yellow
{border:"#FA0A10",background:"#FB7E81",highlight:{border:"#FA0A10",background:"#FFAFB1"},hover:{border:"#FA0A10",background:"#FFAFB1"}},// 2: red
{border:"#41A906",background:"#7BE141",highlight:{border:"#41A906",background:"#A1EC76"},hover:{border:"#41A906",background:"#A1EC76"}},// 3: green
{border:"#E129F0",background:"#EB7DF4",highlight:{border:"#E129F0",background:"#F0B3F5"},hover:{border:"#E129F0",background:"#F0B3F5"}},// 4: magenta
{border:"#7C29F0",background:"#AD85E4",highlight:{border:"#7C29F0",background:"#D3BDF0"},hover:{border:"#7C29F0",background:"#D3BDF0"}},// 5: purple
{border:"#C37F00",background:"#FFA807",highlight:{border:"#C37F00",background:"#FFCA66"},hover:{border:"#C37F00",background:"#FFCA66"}},// 6: orange
{border:"#4220FB",background:"#6E6EFD",highlight:{border:"#4220FB",background:"#9B9BFD"},hover:{border:"#4220FB",background:"#9B9BFD"}},// 7: darkblue
{border:"#FD5A77",background:"#FFC0CB",highlight:{border:"#FD5A77",background:"#FFD1D9"},hover:{border:"#FD5A77",background:"#FFD1D9"}},// 8: pink
{border:"#4AD63A",background:"#C2FABC",highlight:{border:"#4AD63A",background:"#E6FFE3"},hover:{border:"#4AD63A",background:"#E6FFE3"}},// 9: mint
{border:"#990000",background:"#EE0000",highlight:{border:"#BB0000",background:"#FF3333"},hover:{border:"#BB0000",background:"#FF3333"}},// 10:bright red
{border:"#FF6000",background:"#FF6000",highlight:{border:"#FF6000",background:"#FF6000"},hover:{border:"#FF6000",background:"#FF6000"}},// 12: real orange
{border:"#97C2FC",background:"#2B7CE9",highlight:{border:"#D2E5FF",background:"#2B7CE9"},hover:{border:"#D2E5FF",background:"#2B7CE9"}},// 13: blue
{border:"#399605",background:"#255C03",highlight:{border:"#399605",background:"#255C03"},hover:{border:"#399605",background:"#255C03"}},// 14: green
{border:"#B70054",background:"#FF007E",highlight:{border:"#B70054",background:"#FF007E"},hover:{border:"#B70054",background:"#FF007E"}},// 15: magenta
{border:"#AD85E4",background:"#7C29F0",highlight:{border:"#D3BDF0",background:"#7C29F0"},hover:{border:"#D3BDF0",background:"#7C29F0"}},// 16: purple
{border:"#4557FA",background:"#000EA1",highlight:{border:"#6E6EFD",background:"#000EA1"},hover:{border:"#6E6EFD",background:"#000EA1"}},// 17: darkblue
{border:"#FFC0CB",background:"#FD5A77",highlight:{border:"#FFD1D9",background:"#FD5A77"},hover:{border:"#FFD1D9",background:"#FD5A77"}},// 18: pink
{border:"#C2FABC",background:"#74D66A",highlight:{border:"#E6FFE3",background:"#74D66A"},hover:{border:"#E6FFE3",background:"#74D66A"}},// 19: mint
{border:"#EE0000",background:"#990000",highlight:{border:"#FF3333",background:"#BB0000"},hover:{border:"#FF3333",background:"#BB0000"}}// 20:bright red
];this.options={};this.defaultOptions={useDefaultGroups:true};Object.assign(this.options,this.defaultOptions);}/**
*
* @param {object} options
*/setOptions(options){const optionFields=["useDefaultGroups"];if(options!==undefined){for(const groupName in options){if(Object.prototype.hasOwnProperty.call(options,groupName)){if(optionFields.indexOf(groupName)===-1){const group=options[groupName];this.add(groupName,group);}}}}}/**
* Clear all groups
*/clear(){this._groups=new Map();this._groupNames=[];}/**
* Get group options of a groupname.
* If groupname is not found, a new group may be created.
*
* @param {*} groupname Can be a number, string, Date, etc.
* @param {boolean} [shouldCreate=true] If true, create a new group
* @returns {object} The found or created group
*/get(groupname,shouldCreate=true){let group=this._groups.get(groupname);if(group===undefined&&shouldCreate){if(this.options.useDefaultGroups===false&&this._groupNames.length>0){// create new group
const index=this._groupIndex%this._groupNames.length;++this._groupIndex;group={};group.color=this._groups.get(this._groupNames[index]);this._groups.set(groupname,group);}else {// create new group
const index=this._defaultIndex%this._defaultGroups.length;this._defaultIndex++;group={};group.color=this._defaultGroups[index];this._groups.set(groupname,group);}}return group;}/**
* Add custom group style.
*
* @param {string} groupName - The name of the group, a new group will be
* created if a group with the same name doesn't exist, otherwise the old
* groups style will be overwritten.
* @param {object} style - An object containing borderColor, backgroundColor,
* etc.
* @returns {object} The created group object.
*/add(groupName,style){// Only push group name once to prevent duplicates which would consume more
// RAM and also skew the distribution towards more often updated groups,
// neither of which is desirable.
if(!this._groups.has(groupName)){this._groupNames.push(groupName);}this._groups.set(groupName,style);return style;}}/**
* Helper functions for components
*/ /**
* Determine values to use for (sub)options of 'chosen'.
*
* This option is either a boolean or an object whose values should be examined further.
* The relevant structures are:
*
* - chosen: <boolean value>
* - chosen: { subOption: <boolean or function> }
*
* Where subOption is 'node', 'edge' or 'label'.
*
* The intention of this method appears to be to set a specific priority to the options;
* Since most properties are either bridged or merged into the local options objects, there
* is not much point in handling them separately.
* TODO: examine if 'most' in previous sentence can be replaced with 'all'. In that case, we
* should be able to get rid of this method.
*
* @param {string} subOption option within object 'chosen' to consider; either 'node', 'edge' or 'label'
* @param {object} pile array of options objects to consider
* @returns {boolean | Function} value for passed subOption of 'chosen' to use
*/function choosify(subOption,pile){// allowed values for subOption
const allowed=["node","edge","label"];let value=true;const chosen=topMost(pile,"chosen");if(typeof chosen==="boolean"){value=chosen;}else if(typeof chosen==="object"){if(allowed.indexOf(subOption)===-1){throw new Error("choosify: subOption '"+subOption+"' should be one of "+"'"+allowed.join("', '")+"'");}const chosenEdge=topMost(pile,["chosen",subOption]);if(typeof chosenEdge==="boolean"||typeof chosenEdge==="function"){value=chosenEdge;}}return value;}/**
* Check if the point falls within the given rectangle.
*
* @param {rect} rect
* @param {point} point
* @param {rotationPoint} [rotationPoint] if specified, the rotation that applies to the rectangle.
* @returns {boolean} true if point within rectangle, false otherwise
*/function pointInRect(rect,point,rotationPoint){if(rect.width<=0||rect.height<=0){return false;// early out
}if(rotationPoint!==undefined){// Rotate the point the same amount as the rectangle
const tmp={x:point.x-rotationPoint.x,y:point.y-rotationPoint.y};if(rotationPoint.angle!==0){// In order to get the coordinates the same, you need to
// rotate in the reverse direction
const angle=-rotationPoint.angle;const tmp2={x:Math.cos(angle)*tmp.x-Math.sin(angle)*tmp.y,y:Math.sin(angle)*tmp.x+Math.cos(angle)*tmp.y};point=tmp2;}else {point=tmp;}// Note that if a rotation is specified, the rectangle coordinates
// are **not* the full canvas coordinates. They are relative to the
// rotationPoint. Hence, the point coordinates need not be translated
// back in this case.
}const right=rect.x+rect.width;const bottom=rect.y+rect.width;return rect.left<point.x&&right>point.x&&rect.top<point.y&&bottom>point.y;}/**
* Check if given value is acceptable as a label text.
*
* @param {*} text value to check; can be anything at this point
* @returns {boolean} true if valid label value, false otherwise
*/function isValidLabel(text){// Note that this is quite strict: types that *might* be converted to string are disallowed
return typeof text==="string"&&text!=="";}/**
* Returns x, y of self reference circle based on provided angle
*
* @param {object} ctx
* @param {number} angle
* @param {number} radius
* @param {VisNode} node
* @returns {object} x and y coordinates
*/function getSelfRefCoordinates(ctx,angle,radius,node){let x=node.x;let y=node.y;if(typeof node.distanceToBorder==="function"){//calculating opposite and adjacent
//distaneToBorder becomes Hypotenuse.
//Formulas sin(a) = Opposite / Hypotenuse and cos(a) = Adjacent / Hypotenuse
const toBorderDist=node.distanceToBorder(ctx,angle);const yFromNodeCenter=Math.sin(angle)*toBorderDist;const xFromNodeCenter=Math.cos(angle)*toBorderDist;//xFromNodeCenter is basically x and if xFromNodeCenter equals to the distance to border then it means
//that y does not need calculation because it is equal node.height / 2 or node.y
//same thing with yFromNodeCenter and if yFromNodeCenter equals to the distance to border then it means
//that x is equal node.width / 2 or node.x
if(xFromNodeCenter===toBorderDist){x+=toBorderDist;y=node.y;}else if(yFromNodeCenter===toBorderDist){x=node.x;y-=toBorderDist;}else {x+=xFromNodeCenter;y-=yFromNodeCenter;}}else if(node.shape.width>node.shape.height){x=node.x+node.shape.width*0.5;y=node.y-radius;}else {x=node.x+radius;y=node.y-node.shape.height*0.5;}return {x,y};}/**
* Callback to determine text dimensions, using the parent label settings.
*
* @callback MeasureText
* @param {text} text
* @param {text} mod
* @returns {object} { width, values} width in pixels and font attributes
*/ /**
* Helper class for Label which collects results of splitting labels into lines and blocks.
*
* @private
*/class LabelAccumulator{/**
* @param {MeasureText} measureText
*/constructor(measureText){this.measureText=measureText;this.current=0;this.width=0;this.height=0;this.lines=[];}/**
* Append given text to the given line.
*
* @param {number} l index of line to add to
* @param {string} text string to append to line
* @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod='normal']
* @private
*/_add(l,text,mod="normal"){if(this.lines[l]===undefined){this.lines[l]={width:0,height:0,blocks:[]};}// We still need to set a block for undefined and empty texts, hence return at this point
// This is necessary because we don't know at this point if we're at the
// start of an empty line or not.
// To compensate, empty blocks are removed in `finalize()`.
//
// Empty strings should still have a height
let tmpText=text;if(text===undefined||text==="")tmpText=" ";// Determine width and get the font properties
const result=this.measureText(tmpText,mod);const block=Object.assign({},result.values);block.text=text;block.width=result.width;block.mod=mod;if(text===undefined||text===""){block.width=0;}this.lines[l].blocks.push(block);// Update the line width. We need this for determining if a string goes over max width
this.lines[l].width+=block.width;}/**
* Returns the width in pixels of the current line.
*
* @returns {number}
*/curWidth(){const line=this.lines[this.current];if(line===undefined)return 0;return line.width;}/**
* Add text in block to current line
*
* @param {string} text
* @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod='normal']
*/append(text,mod="normal"){this._add(this.current,text,mod);}/**
* Add text in block to current line and start a new line
*
* @param {string} text
* @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod='normal']
*/newLine(text,mod="normal"){this._add(this.current,text,mod);this.current++;}/**
* Determine and set the heights of all the lines currently contained in this instance
*
* Note that width has already been set.
*
* @private
*/determineLineHeights(){for(let k=0;k<this.lines.length;k++){const line=this.lines[k];// Looking for max height of blocks in line
let height=0;if(line.blocks!==undefined){// Can happen if text contains e.g. '\n '
for(let l=0;l<line.blocks.length;l++){const block=line.blocks[l];if(height<block.height){height=block.height;}}}line.height=height;}}/**
* Determine the full size of the label text, as determined by current lines and blocks
*
* @private
*/determineLabelSize(){let width=0;let height=0;for(let k=0;k<this.lines.length;k++){const line=this.lines[k];if(line.width>width){width=line.width;}height+=line.height;}this.width=width;this.height=height;}/**
* Remove all empty blocks and empty lines we don't need
*
* This must be done after the width/height determination,
* so that these are set properly for processing here.
*
* @returns {Array<Line>} Lines with empty blocks (and some empty lines) removed
* @private
*/removeEmptyBlocks(){const tmpLines=[];for(let k=0;k<this.lines.length;k++){const line=this.lines[k];// Note: an empty line in between text has width zero but is still relevant to layout.
// So we can't use width for testing empty line here
if(line.blocks.length===0)continue;// Discard final empty line always
if(k===this.lines.length-1){if(line.width===0)continue;}const tmpLine={};Object.assign(tmpLine,line);tmpLine.blocks=[];let firstEmptyBlock;const tmpBlocks=[];for(let l=0;l<line.blocks.length;l++){const block=line.blocks[l];if(block.width!==0){tmpBlocks.push(block);}else {if(firstEmptyBlock===undefined){firstEmptyBlock=block;}}}// Ensure that there is *some* text present
if(tmpBlocks.length===0&&firstEmptyBlock!==undefined){tmpBlocks.push(firstEmptyBlock);}tmpLine.blocks=tmpBlocks;tmpLines.push(tmpLine);}return tmpLines;}/**
* Set the sizes for all lines and the whole thing.
*
* @returns {{width: (number|*), height: (number|*), lines: Array}}
*/finalize(){//console.log(JSON.stringify(this.lines, null, 2));
this.determineLineHeights();this.determineLabelSize();const tmpLines=this.removeEmptyBlocks();// Return a simple hash object for further processing.
return {width:this.width,height:this.height,lines:tmpLines};}}// Hash of prepared regexp's for tags
const tagPattern={// HTML
"<b>":/<b>/,"<i>":/<i>/,"<code>":/<code>/,"</b>":/<\/b>/,"</i>":/<\/i>/,"</code>":/<\/code>/,// Markdown
"*":/\*/,// bold
_:/_/,// ital
"`":/`/,// mono
afterBold:/[^*]/,afterItal:/[^_]/,afterMono:/[^`]/};/**
* Internal helper class for parsing the markup tags for HTML and Markdown.
*
* NOTE: Sequences of tabs and spaces are reduced to single space.
* Scan usage of `this.spacing` within method
*/class MarkupAccumulator{/**
* Create an instance
*
* @param {string} text text to parse for markup
*/constructor(text){this.text=text;this.bold=false;this.ital=false;this.mono=false;this.spacing=false;this.position=0;this.buffer="";this.modStack=[];this.blocks=[];}/**
* Return the mod label currently on the top of the stack
*
* @returns {string} label of topmost mod
* @private
*/mod(){return this.modStack.length===0?"normal":this.modStack[0];}/**
* Return the mod label currently active
*
* @returns {string} label of active mod
* @private
*/modName(){if(this.modStack.length===0)return "normal";else if(this.modStack[0]==="mono")return "mono";else {if(this.bold&&this.ital){return "boldital";}else if(this.bold){return "bold";}else if(this.ital){return "ital";}}}/**
* @private
*/emitBlock(){if(this.spacing){this.add(" ");this.spacing=false;}if(this.buffer.length>0){this.blocks.push({text:this.buffer,mod:this.modName()});this.buffer="";}}/**
* Output text to buffer
*
* @param {string} text text to add
* @private
*/add(text){if(text===" "){this.spacing=true;}if(this.spacing){this.buffer+=" ";this.spacing=false;}if(text!=" "){this.buffer+=text;}}/**
* Handle parsing of whitespace
*
* @param {string} ch the character to check
* @returns {boolean} true if the character was processed as whitespace, false otherwise
*/parseWS(ch){if(/[ \t]/.test(ch)){if(!this.mono){this.spacing=true;}else {this.add(ch);}return true;}return false;}/**
* @param {string} tagName label for block type to set
* @private
*/setTag(tagName){this.emitBlock();this[tagName]=true;this.modStack.unshift(tagName);}/**
* @param {string} tagName label for block type to unset
* @private
*/unsetTag(tagName){this.emitBlock();this[tagName]=false;this.modStack.shift();}/**
* @param {string} tagName label for block type we are currently processing
* @param {string|RegExp} tag string to match in text
* @returns {boolean} true if the tag was processed, false otherwise
*/parseStartTag(tagName,tag){// Note: if 'mono' passed as tagName, there is a double check here. This is OK
if(!this.mono&&!this[tagName]&&this.match(tag)){this.setTag(tagName);return true;}return false;}/**
* @param {string|RegExp} tag
* @param {number} [advance=true] if set, advance current position in text
* @returns {boolean} true if match at given position, false otherwise
* @private
*/match(tag,advance=true){const[regExp,length]=this.prepareRegExp(tag);const matched=regExp.test(this.text.substr(this.position,length));if(matched&&advance){this.position+=length-1;}return matched;}/**
* @param {string} tagName label for block type we are currently processing
* @param {string|RegExp} tag string to match in text
* @param {RegExp} [nextTag] regular expression to match for characters *following* the current tag
* @returns {boolean} true if the tag was processed, false otherwise
*/parseEndTag(tagName,tag,nextTag){let checkTag=this.mod()===tagName;if(tagName==="mono"){// special handling for 'mono'
checkTag=checkTag&&this.mono;}else {checkTag=checkTag&&!this.mono;}if(checkTag&&this.match(tag)){if(nextTag!==undefined){// Purpose of the following match is to prevent a direct unset/set of a given tag
// E.g. '*bold **still bold*' => '*bold still bold*'
if(this.position===this.text.length-1||this.match(nextTag,false)){this.unsetTag(tagName);}}else {this.unsetTag(tagName);}return true;}return false;}/**
* @param {string|RegExp} tag string to match in text
* @param {value} value string to replace tag with, if found at current position
* @returns {boolean} true if the tag was processed, false otherwise
*/replace(tag,value){if(this.match(tag)){this.add(value);this.position+=length-1;return true;}return false;}/**
* Create a regular expression for the tag if it isn't already one.
*
* The return value is an array `[RegExp, number]`, with exactly two value, where:
* - RegExp is the regular expression to use
* - number is the lenth of the input string to match
*
* @param {string|RegExp} tag string to match in text
* @returns {Array} regular expression to use and length of input string to match
* @private
*/prepareRegExp(tag){let length;let regExp;if(tag instanceof RegExp){regExp=tag;length=1;// ASSUMPTION: regexp only tests one character
}else {// use prepared regexp if present
const prepared=tagPattern[tag];if(prepared!==undefined){regExp=prepared;}else {regExp=new RegExp(tag);}length=tag.length;}return [regExp,length];}}/**
* Helper class for Label which explodes the label text into lines and blocks within lines
*
* @private
*/class LabelSplitter{/**
* @param {CanvasRenderingContext2D} ctx Canvas rendering context
* @param {Label} parent reference to the Label instance using current instance
* @param {boolean} selected
* @param {boolean} hover
*/constructor(ctx,parent,selected,hover){this.ctx=ctx;this.parent=parent;this.selected=selected;this.hover=hover;/**
* Callback to determine text width; passed to LabelAccumulator instance
*
* @param {string} text string to determine width of
* @param {string} mod font type to use for this text
* @returns {object} { width, values} width in pixels and font attributes
*/const textWidth=(text,mod)=>{if(text===undefined)return 0;// TODO: This can be done more efficiently with caching
// This will set the ctx.font correctly, depending on selected/hover and mod - so that ctx.measureText() will be accurate.
const values=this.parent.getFormattingValues(ctx,selected,hover,mod);let width=0;if(text!==""){const measure=this.ctx.measureText(text);width=measure.width;}return {width,values:values};};this.lines=new LabelAccumulator(textWidth);}/**
* Split passed text of a label into lines and blocks.
*
* # NOTE
*
* The handling of spacing is option dependent:
*
* - if `font.multi : false`, all spaces are retained
* - if `font.multi : true`, every sequence of spaces is compressed to a single space
*
* This might not be the best way to do it, but this is as it has been working till now.
* In order not to break existing functionality, for the time being this behaviour will
* be retained in any code changes.
*
* @param {string} text text to split
* @returns {Array<line>}
*/process(text){if(!isValidLabel(text)){return this.lines.finalize();}const font=this.parent.fontOptions;// Normalize the end-of-line's to a single representation - order important
text=text.replace(/\r\n/g,"\n");// Dos EOL's
text=text.replace(/\r/g,"\n");// Mac EOL's
// Note that at this point, there can be no \r's in the text.
// This is used later on splitStringIntoLines() to split multifont texts.
const nlLines=String(text).split("\n");const lineCount=nlLines.length;if(font.multi){// Multi-font case: styling tags active
for(let i=0;i<lineCount;i++){const blocks=this.splitBlocks(nlLines[i],font.multi);// Post: Sequences of tabs and spaces are reduced to single space
if(blocks===undefined)continue;if(blocks.length===0){this.lines.newLine("");continue;}if(font.maxWdt>0){// widthConstraint.maximum defined
//console.log('Running widthConstraint multi, max: ' + this.fontOptions.maxWdt);
for(let j=0;j<blocks.length;j++){const mod=blocks[j].mod;const text=blocks[j].text;this.splitStringIntoLines(text,mod,true);}}else {// widthConstraint.maximum NOT defined
for(let j=0;j<blocks.length;j++){const mod=blocks[j].mod;const text=blocks[j].text;this.lines.append(text,mod);}}this.lines.newLine();}}else {// Single-font case
if(font.maxWdt>0){// widthConstraint.maximum defined
// console.log('Running widthConstraint normal, max: ' + this.fontOptions.maxWdt);
for(let i=0;i<lineCount;i++){this.splitStringIntoLines(nlLines[i]);}}else {// widthConstraint.maximum NOT defined
for(let i=0;i<lineCount;i++){this.lines.newLine(nlLines[i]);}}}return this.lines.finalize();}/**
* normalize the markup system
*
* @param {boolean|'md'|'markdown'|'html'} markupSystem
* @returns {string}
*/decodeMarkupSystem(markupSystem){let system="none";if(markupSystem==="markdown"||markupSystem==="md"){system="markdown";}else if(markupSystem===true||markupSystem==="html"){system="html";}return system;}/**
*
* @param {string} text
* @returns {Array}
*/splitHtmlBlocks(text){const s=new MarkupAccumulator(text);const parseEntities=ch=>{if(/&/.test(ch)){const parsed=s.replace(s.text,"<","<")||s.replace(s.text,"&","&");if(!parsed){s.add("&");}return true;}return false;};while(s.position<s.text.length){const ch=s.text.charAt(s.position);const parsed=s.parseWS(ch)||/</.test(ch)&&(s.parseStartTag("bold","<b>")||s.parseStartTag("ital","<i>")||s.parseStartTag("mono","<code>")||s.parseEndTag("bold","</b>")||s.parseEndTag("ital","</i>")||s.parseEndTag("mono","</code>"))||parseEntities(ch);if(!parsed){s.add(ch);}s.position++;}s.emitBlock();return s.blocks;}/**
*
* @param {string} text
* @returns {Array}
*/splitMarkdownBlocks(text){const s=new MarkupAccumulator(text);let beginable=true;const parseOverride=ch=>{if(/\\/.test(ch)){if(s.position<this.text.length+1){s.position++;ch=this.text.charAt(s.position);if(/ \t/.test(ch)){s.spacing=true;}else {s.add(ch);beginable=false;}}return true;}return false;};while(s.position<s.text.length){const ch=s.text.charAt(s.position);const parsed=s.parseWS(ch)||parseOverride(ch)||(beginable||s.spacing)&&(s.parseStartTag("bold","*")||s.parseStartTag("ital","_")||s.parseStartTag("mono","`"))||s.parseEndTag("bold","*","afterBold")||s.parseEndTag("ital","_","afterItal")||s.parseEndTag("mono","`","afterMono");if(!parsed){s.add(ch);beginable=false;}s.position++;}s.emitBlock();return s.blocks;}/**
* Explodes a piece of text into single-font blocks using a given markup
*
* @param {string} text
* @param {boolean|'md'|'markdown'|'html'} markupSystem
* @returns {Array.<{text: string, mod: string}>}
* @private
*/splitBlocks(text,markupSystem){const system=this.decodeMarkupSystem(markupSystem);if(system==="none"){return [{text:text,mod:"normal"}];}else if(system==="markdown"){return this.splitMarkdownBlocks(text);}else if(system==="html"){return this.splitHtmlBlocks(text);}}/**
* @param {string} text
* @returns {boolean} true if text length over the current max with
* @private
*/overMaxWidth(text){const width=this.ctx.measureText(text).width;return this.lines.curWidth()+width>this.parent.fontOptions.maxWdt;}/**
* Determine the longest part of the sentence which still fits in the
* current max width.
*
* @param {Array} words Array of strings signifying a text lines
* @returns {number} index of first item in string making string go over max
* @private
*/getLongestFit(words){let text="";let w=0;while(w<words.length){const pre=text===""?"":" ";const newText=text+pre+words[w];if(this.overMaxWidth(newText))break;text=newText;w++;}return w;}/**
* Determine the longest part of the string which still fits in the
* current max width.
*
* @param {Array} words Array of strings signifying a text lines
* @returns {number} index of first item in string making string go over max
*/getLongestFitWord(words){let w=0;while(w<words.length){if(this.overMaxWidth(words.slice(0,w)))break;w++;}return w;}/**
* Split the passed text into lines, according to width constraint (if any).
*
* The method assumes that the input string is a single line, i.e. without lines break.
*
* This method retains spaces, if still present (case `font.multi: false`).
* A space which falls on an internal line break, will be replaced by a newline.
* There is no special handling of tabs; these go along with the flow.
*
* @param {string} str
* @param {string} [mod='normal']
* @param {boolean} [appendLast=false]
* @private
*/splitStringIntoLines(str,mod="normal",appendLast=false){// Set the canvas context font, based upon the current selected/hover state
// and the provided mod, so the text measurement performed by getLongestFit
// will be accurate - and not just use the font of whoever last used the canvas.
this.parent.getFormattingValues(this.ctx,this.selected,this.hover,mod);// Still-present spaces are relevant, retain them
str=str.replace(/^( +)/g,"$1\r");str=str.replace(/([^\r][^ ]*)( +)/g,"$1\r$2\r");let words=str.split("\r");while(words.length>0){let w=this.getLongestFit(words);if(w===0){// Special case: the first word is already larger than the max width.
const word=words[0];// Break the word to the largest part that fits the line
const x=this.getLongestFitWord(word);this.lines.newLine(word.slice(0,x),mod);// Adjust the word, so that the rest will be done next iteration
words[0]=word.slice(x);}else {// skip any space that is replaced by a newline
let newW=w;if(words[w-1]===" "){w--;}else if(words[newW]===" "){newW++;}const text=words.slice(0,w).join("");if(w==words.length&&appendLast){this.lines.append(text,mod);}else {this.lines.newLine(text,mod);}// Adjust the word, so that the rest will be done next iteration
words=words.slice(newW);}}}}/**
* List of special styles for multi-fonts
*
* @private
*/const multiFontStyle=["bold","ital","boldital","mono"];/**
* A Label to be used for Nodes or Edges.
*/class Label{/**
* @param {object} body
* @param {object} options
* @param {boolean} [edgelabel=false]
*/constructor(body,options,edgelabel=false){this.body=body;this.pointToSelf=false;this.baseSize=undefined;this.fontOptions={};// instance variable containing the *instance-local* font options
this.setOptions(options);this.size={top:0,left:0,width:0,height:0,yLine:0};this.isEdgeLabel=edgelabel;}/**
* @param {object} options the options of the parent Node-instance
*/setOptions(options){this.elementOptions=options;// Reference to the options of the parent Node-instance
this.initFontOptions(options.font);if(isValidLabel(options.label)){this.labelDirty=true;}else {// Bad label! Change the option value to prevent bad stuff happening
options.label=undefined;}if(options.font!==undefined&&options.font!==null){// font options can be deleted at various levels
if(typeof options.font==="string"){this.baseSize=this.fontOptions.size;}else if(typeof options.font==="object"){const size=options.font.size;if(size!==undefined){this.baseSize=size;}}}}/**
* Init the font Options structure.
*
* Member fontOptions serves as an accumulator for the current font options.
* As such, it needs to be completely separated from the node options.
*
* @param {object} newFontOptions the new font options to process
* @private
*/initFontOptions(newFontOptions){// Prepare the multi-font option objects.
// These will be filled in propagateFonts(), if required
forEach(multiFontStyle,style=>{this.fontOptions[style]={};});// Handle shorthand option, if present
if(Label.parseFontString(this.fontOptions,newFontOptions)){this.fontOptions.vadjust=0;return;}// Copy over the non-multifont options, if specified
forEach(newFontOptions,(prop,n)=>{if(prop!==undefined&&prop!==null&&typeof prop!=="object"){this.fontOptions[n]=prop;}});}/**
* If in-variable is a string, parse it as a font specifier.
*
* Note that following is not done here and have to be done after the call:
* - Not all font options are set (vadjust, mod)
*
* @param {object} outOptions out-parameter, object in which to store the parse results (if any)
* @param {object} inOptions font options to parse
* @returns {boolean} true if font parsed as string, false otherwise
* @static
*/static parseFontString(outOptions,inOptions){if(!inOptions||typeof inOptions!=="string")return false;const newOptionsArray=inOptions.split(" ");outOptions.size=+newOptionsArray[0].replace("px","");outOptions.face=newOptionsArray[1];outOptions.color=newOptionsArray[2];return true;}/**
* Set the width and height constraints based on 'nearest' value
*
* @param {Array} pile array of option objects to consider
* @returns {object} the actual constraint values to use
* @private
*/constrain(pile){// NOTE: constrainWidth and constrainHeight never set!
// NOTE: for edge labels, only 'maxWdt' set
// Node labels can set all the fields
const fontOptions={constrainWidth:false,maxWdt:-1,minWdt:-1,constrainHeight:false,minHgt:-1,valign:"middle"};const widthConstraint=topMost(pile,"widthConstraint");if(typeof widthConstraint==="number"){fontOptions.maxWdt=Number(widthConstraint);fontOptions.minWdt=Number(widthConstraint);}else if(typeof widthConstraint==="object"){const widthConstraintMaximum=topMost(pile,["widthConstraint","maximum"]);if(typeof widthConstraintMaximum==="number"){fontOptions.maxWdt=Number(widthConstraintMaximum);}const widthConstraintMinimum=topMost(pile,["widthConstraint","minimum"]);if(typeof widthConstraintMinimum==="number"){fontOptions.minWdt=Number(widthConstraintMinimum);}}const heightConstraint=topMost(pile,"heightConstraint");if(typeof heightConstraint==="number"){fontOptions.minHgt=Number(heightConstraint);}else if(typeof heightConstraint==="object"){const heightConstraintMinimum=topMost(pile,["heightConstraint","minimum"]);if(typeof heightConstraintMinimum==="number"){fontOptions.minHgt=Number(heightConstraintMinimum);}const heightConstraintValign=topMost(pile,["heightConstraint","valign"]);if(typeof heightConstraintValign==="string"){if(heightConstraintValign==="top"||heightConstraintValign==="bottom"){fontOptions.valign=heightConstraintValign;}}}return fontOptions;}/**
* Set options and update internal state
*
* @param {object} options options to set
* @param {Array} pile array of option objects to consider for option 'chosen'
*/update(options,pile){this.setOptions(options,true);this.propagateFonts(pile);deepExtend(this.fontOptions,this.constrain(pile));this.fontOptions.chooser=choosify("label",pile);}/**
* When margins are set in an element, adjust sizes is called to remove them
* from the width/height constraints. This must be done prior to label sizing.
*
* @param {{top: number, right: number, bottom: number, left: number}} margins
*/adjustSizes(margins){const widthBias=margins?margins.right+margins.left:0;if(this.fontOptions.constrainWidth){this.fontOptions.maxWdt-=widthBias;this.fontOptions.minWdt-=widthBias;}const heightBias=margins?margins.top+margins.bottom:0;if(this.fontOptions.constrainHeight){this.fontOptions.minHgt-=heightBias;}}/////////////////////////////////////////////////////////
// Methods for handling options piles
// Eventually, these will be moved to a separate class
/////////////////////////////////////////////////////////
/**
* Add the font members of the passed list of option objects to the pile.
*
* @param {Pile} dstPile pile of option objects add to
* @param {Pile} srcPile pile of option objects to take font options from
* @private
*/addFontOptionsToPile(dstPile,srcPile){for(let i=0;i<srcPile.length;++i){this.addFontToPile(dstPile,srcPile[i]);}}/**
* Add given font option object to the list of objects (the 'pile') to consider for determining
* multi-font option values.
*
* @param {Pile} pile pile of option objects to use
* @param {object} options instance to add to pile
* @private
*/addFontToPile(pile,options){if(options===undefined)return;if(options.font===undefined||options.font===null)return;const item=options.font;pile.push(item);}/**
* Collect all own-property values from the font pile that aren't multi-font option objectss.
*
* @param {Pile} pile pile of option objects to use
* @returns {object} object with all current own basic font properties
* @private
*/getBasicOptions(pile){const ret={};// Scans the whole pile to get all options present
for(let n=0;n<pile.length;++n){let fontOptions=pile[n];// Convert shorthand if necessary
const tmpShorthand={};if(Label.parseFontString(tmpShorthand,fontOptions)){fontOptions=tmpShorthand;}forEach(fontOptions,(opt,name)=>{if(opt===undefined)return;// multi-font option need not be present
if(Object.prototype.hasOwnProperty.call(ret,name))return;// Keep first value we encounter
if(multiFontStyle.indexOf(name)!==-1){// Skip multi-font properties but we do need the structure
ret[name]={};}else {ret[name]=opt;}});}return ret;}/**
* Return the value for given option for the given multi-font.
*
* All available option objects are trawled in the set order to construct the option values.
*
* ---------------------------------------------------------------------
* ## Traversal of pile for multi-fonts
*
* The determination of multi-font option values is a special case, because any values not
* present in the multi-font options should by definition be taken from the main font options,
* i.e. from the current 'parent' object of the multi-font option.
*
* ### Search order for multi-fonts
*
* 'bold' used as example:
*
* - search in option group 'bold' in local properties
* - search in main font option group in local properties
*
* ---------------------------------------------------------------------
*
* @param {Pile} pile pile of option objects to use
* @param {MultiFontStyle} multiName sub path for the multi-font
* @param {string} option the option to search for, for the given multi-font
* @returns {string|number} the value for the given option
* @private
*/getFontOption(pile,multiName,option){let multiFont;// Search multi font in local properties
for(let n=0;n<pile.length;++n){const fontOptions=pile[n];if(Object.prototype.hasOwnProperty.call(fontOptions,multiName)){multiFont=fontOptions[multiName];if(multiFont===undefined||multiFont===null)continue;// Convert shorthand if necessary
// TODO: inefficient to do this conversion every time; find a better way.
const tmpShorthand={};if(Label.parseFontString(tmpShorthand,multiFont)){multiFont=tmpShorthand;}if(Object.prototype.hasOwnProperty.call(multiFont,option)){return multiFont[option];}}}// Option is not mentioned in the multi font options; take it from the parent font options.
// These have already been converted with getBasicOptions(), so use the converted values.
if(Object.prototype.hasOwnProperty.call(this.fontOptions,option)){return this.fontOptions[option];}// A value **must** be found; you should never get here.
throw new Error("Did not find value for multi-font for property: '"+option+"'");}/**
* Return all options values for the given multi-font.
*
* All available option objects are trawled in the set order to construct the option values.
*
* @param {Pile} pile pile of option objects to use
* @param {MultiFontStyle} multiName sub path for the mod-font
* @returns {MultiFontOptions}
* @private
*/getFontOptions(pile,multiName){const result={};const optionNames=["color","size","face","mod","vadjust"];// List of allowed options per multi-font
for(let i=0;i<optionNames.length;++i){const mod=optionNames[i];result[mod]=this.getFontOption(pile,multiName,mod);}return result;}/////////////////////////////////////////////////////////
// End methods for handling options piles
/////////////////////////////////////////////////////////
/**
* Collapse the font options for the multi-font to single objects, from
* the chain of option objects passed (the 'pile').
*
* @param {Pile} pile sequence of option objects to consider.
* First item in list assumed to be the newly set options.
*/propagateFonts(pile){const fontPile=[];// sequence of font objects to consider, order important
// Note that this.elementOptions is not used here.
this.addFontOptionsToPile(fontPile,pile);this.fontOptions=this.getBasicOptions(fontPile);// We set multifont values even if multi === false, for consistency (things break otherwise)
for(let i=0;i<multiFontStyle.length;++i){const mod=multiFontStyle[i];const modOptions=this.fontOptions[mod];const tmpMultiFontOptions=this.getFontOptions(fontPile,mod);// Copy over found values
forEach(tmpMultiFontOptions,(option,n)=>{modOptions[n]=option;});modOptions.size=Number(modOptions.size);modOptions.vadjust=Number(modOptions.vadjust);}}/**
* Main function. This is called from anything that wants to draw a label.
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x
* @param {number} y
* @param {boolean} selected
* @param {boolean} hover
* @param {string} [baseline='middle']
*/draw(ctx,x,y,selected,hover,baseline="middle"){// if no label, return
if(this.elementOptions.label===undefined)return;// check if we have to render the label
let viewFontSize=this.fontOptions.size*this.body.view.scale;if(this.elementOptions.label&&viewFontSize<this.elementOptions.scaling.label.drawThreshold-1)return;// This ensures that there will not be HUGE letters on screen
// by setting an upper limit on the visible text size (regardless of zoomLevel)
if(viewFontSize>=this.elementOptions.scaling.label.maxVisible){viewFontSize=Number(this.elementOptions.scaling.label.maxVisible)/this.body.view.scale;}// update the size cache if required
this.calculateLabelSize(ctx,selected,hover,x,y,baseline);this._drawBackground(ctx);this._drawText(ctx,x,this.size.yLine,baseline,viewFontSize);}/**
* Draws the label background
*
* @param {CanvasRenderingContext2D} ctx
* @private
*/_drawBackground(ctx){if(this.fontOptions.background!==undefined&&this.fontOptions.background!=="none"){ctx.fillStyle=this.fontOptions.background;const size=this.getSize();ctx.fillRect(size.left,size.top,size.width,size.height);}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x
* @param {number} y
* @param {string} [baseline='middle']
* @param {number} viewFontSize
* @private
*/_drawText(ctx,x,y,baseline="middle",viewFontSize){[x,y]=this._setAlignment(ctx,x,y,baseline);ctx.textAlign="left";x=x-this.size.width/2;// Shift label 1/2-distance to the left
if(this.fontOptions.valign&&this.size.height>this.size.labelHeight){if(this.fontOptions.valign==="top"){y-=(this.size.height-this.size.labelHeight)/2;}if(this.fontOptions.valign==="bottom"){y+=(this.size.height-this.size.labelHeight)/2;}}// draw the text
for(let i=0;i<this.lineCount;i++){const line=this.lines[i];if(line&&line.blocks){let width=0;if(this.isEdgeLabel||this.fontOptions.align==="center"){width+=(this.size.width-line.width)/2;}else if(this.fontOptions.align==="right"){width+=this.size.width-line.width;}for(let j=0;j<line.blocks.length;j++){const block=line.blocks[j];ctx.font=block.font;const[fontColor,strokeColor]=this._getColor(block.color,viewFontSize,block.strokeColor);if(block.strokeWidth>0){ctx.lineWidth=block.strokeWidth;ctx.strokeStyle=strokeColor;ctx.lineJoin="round";}ctx.fillStyle=fontColor;if(block.strokeWidth>0){ctx.strokeText(block.text,x+width,y+block.vadjust);}ctx.fillText(block.text,x+width,y+block.vadjust);width+=block.width;}y+=line.height;}}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x
* @param {number} y
* @param {string} baseline
* @returns {Array.<number>}
* @private
*/_setAlignment(ctx,x,y,baseline){// check for label alignment (for edges)
// TODO: make alignment for nodes
if(this.isEdgeLabel&&this.fontOptions.align!=="horizontal"&&this.pointToSelf===false){x=0;y=0;const lineMargin=2;if(this.fontOptions.align==="top"){ctx.textBaseline="alphabetic";y-=2*lineMargin;// distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers
}else if(this.fontOptions.align==="bottom"){ctx.textBaseline="hanging";y+=2*lineMargin;// distance from edge, required because we use hanging. Hanging has less difference between browsers
}else {ctx.textBaseline="middle";}}else {ctx.textBaseline=baseline;}return [x,y];}/**
* fade in when relative scale is between threshold and threshold - 1.
* If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here.
*
* @param {string} color The font color to use
* @param {number} viewFontSize
* @param {string} initialStrokeColor
* @returns {Array.<string>} An array containing the font color and stroke color
* @private
*/_getColor(color,viewFontSize,initialStrokeColor){let fontColor=color||"#000000";let strokeColor=initialStrokeColor||"#ffffff";if(viewFontSize<=this.elementOptions.scaling.label.drawThreshold){const opacity=Math.max(0,Math.min(1,1-(this.elementOptions.scaling.label.drawThreshold-viewFontSize)));fontColor=overrideOpacity(fontColor,opacity);strokeColor=overrideOpacity(strokeColor,opacity);}return [fontColor,strokeColor];}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
* @returns {{width: number, height: number}}
*/getTextSize(ctx,selected=false,hover=false){this._processLabel(ctx,selected,hover);return {width:this.size.width,height:this.size.height,lineCount:this.lineCount};}/**
* Get the current dimensions of the label
*
* @returns {rect}
*/getSize(){const lineMargin=2;let x=this.size.left;// default values which might be overridden below
let y=this.size.top-0.5*lineMargin;// idem
if(this.isEdgeLabel){const x2=-this.size.width*0.5;switch(this.fontOptions.align){case"middle":x=x2;y=-this.size.height*0.5;break;case"top":x=x2;y=-(this.size.height+lineMargin);break;case"bottom":x=x2;y=lineMargin;break;}}const ret={left:x,top:y,width:this.size.width,height:this.size.height};return ret;}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
* @param {number} [x=0]
* @param {number} [y=0]
* @param {'middle'|'hanging'} [baseline='middle']
*/calculateLabelSize(ctx,selected,hover,x=0,y=0,baseline="middle"){this._processLabel(ctx,selected,hover);this.size.left=x-this.size.width*0.5;this.size.top=y-this.size.height*0.5;this.size.yLine=y+(1-this.lineCount)*0.5*this.fontOptions.size;if(baseline==="hanging"){this.size.top+=0.5*this.fontOptions.size;this.size.top+=4;// distance from node, required because we use hanging. Hanging has less difference between browsers
this.size.yLine+=4;// distance from node
}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
* @param {string} mod
* @returns {{color, size, face, mod, vadjust, strokeWidth: *, strokeColor: (*|string|allOptions.edges.font.strokeColor|{string}|allOptions.nodes.font.strokeColor|Array)}}
*/getFormattingValues(ctx,selected,hover,mod){const getValue=function(fontOptions,mod,option){if(mod==="normal"){if(option==="mod")return "";return fontOptions[option];}if(fontOptions[mod][option]!==undefined){// Grumbl leaving out test on undefined equals false for ""
return fontOptions[mod][option];}else {// Take from parent font option
return fontOptions[option];}};const values={color:getValue(this.fontOptions,mod,"color"),size:getValue(this.fontOptions,mod,"size"),face:getValue(this.fontOptions,mod,"face"),mod:getValue(this.fontOptions,mod,"mod"),vadjust:getValue(this.fontOptions,mod,"vadjust"),strokeWidth:this.fontOptions.strokeWidth,strokeColor:this.fontOptions.strokeColor};if(selected||hover){if(mod==="normal"&&this.fontOptions.chooser===true&&this.elementOptions.labelHighlightBold){values.mod="bold";}else {if(typeof this.fontOptions.chooser==="function"){this.fontOptions.chooser(values,this.elementOptions.id,selected,hover);}}}let fontString="";if(values.mod!==undefined&&values.mod!==""){// safeguard for undefined - this happened
fontString+=values.mod+" ";}fontString+=values.size+"px "+values.face;ctx.font=fontString.replace(/"/g,"");values.font=ctx.font;values.height=values.size;return values;}/**
*
* @param {boolean} selected
* @param {boolean} hover
* @returns {boolean}
*/differentState(selected,hover){return selected!==this.selectedState||hover!==this.hoverState;}/**
* This explodes the passed text into lines and determines the width, height and number of lines.
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
* @param {string} inText the text to explode
* @returns {{width, height, lines}|*}
* @private
*/_processLabelText(ctx,selected,hover,inText){const splitter=new LabelSplitter(ctx,this,selected,hover);return splitter.process(inText);}/**
* This explodes the label string into lines and sets the width, height and number of lines.
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
* @private
*/_processLabel(ctx,selected,hover){if(this.labelDirty===false&&!this.differentState(selected,hover))return;const state=this._processLabelText(ctx,selected,hover,this.elementOptions.label);if(this.fontOptions.minWdt>0&&state.width<this.fontOptions.minWdt){state.width=this.fontOptions.minWdt;}this.size.labelHeight=state.height;if(this.fontOptions.minHgt>0&&state.height<this.fontOptions.minHgt){state.height=this.fontOptions.minHgt;}this.lines=state.lines;this.lineCount=state.lines.length;this.size.width=state.width;this.size.height=state.height;this.selectedState=selected;this.hoverState=hover;this.labelDirty=false;}/**
* Check if this label is visible
*
* @returns {boolean} true if this label will be show, false otherwise
*/visible(){if(this.size.width===0||this.size.height===0||this.elementOptions.label===undefined){return false;// nothing to display
}const viewFontSize=this.fontOptions.size*this.body.view.scale;if(viewFontSize<this.elementOptions.scaling.label.drawThreshold-1){return false;// Too small or too far away to show
}return true;}}/**
* The Base class for all Nodes.
*/class NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){this.body=body;this.labelModule=labelModule;this.setOptions(options);this.top=undefined;this.left=undefined;this.height=undefined;this.width=undefined;this.radius=undefined;this.margin=undefined;this.refreshNeeded=true;this.boundingBox={top:0,left:0,right:0,bottom:0};}/**
*
* @param {object} options
*/setOptions(options){this.options=options;}/**
*
* @param {Label} labelModule
* @private
*/_setMargins(labelModule){this.margin={};if(this.options.margin){if(typeof this.options.margin=="object"){this.margin.top=this.options.margin.top;this.margin.right=this.options.margin.right;this.margin.bottom=this.options.margin.bottom;this.margin.left=this.options.margin.left;}else {this.margin.top=this.options.margin;this.margin.right=this.options.margin;this.margin.bottom=this.options.margin;this.margin.left=this.options.margin;}}labelModule.adjustSizes(this.margin);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
* @private
*/_distanceToBorder(ctx,angle){const borderWidth=this.options.borderWidth;if(ctx){this.resize(ctx);}return Math.min(Math.abs(this.width/2/Math.cos(angle)),Math.abs(this.height/2/Math.sin(angle)))+borderWidth;}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
*/enableShadow(ctx,values){if(values.shadow){ctx.shadowColor=values.shadowColor;ctx.shadowBlur=values.shadowSize;ctx.shadowOffsetX=values.shadowX;ctx.shadowOffsetY=values.shadowY;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
*/disableShadow(ctx,values){if(values.shadow){ctx.shadowColor="rgba(0,0,0,0)";ctx.shadowBlur=0;ctx.shadowOffsetX=0;ctx.shadowOffsetY=0;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
*/enableBorderDashes(ctx,values){if(values.borderDashes!==false){if(ctx.setLineDash!==undefined){let dashes=values.borderDashes;if(dashes===true){dashes=[5,15];}ctx.setLineDash(dashes);}else {console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");this.options.shapeProperties.borderDashes=false;values.borderDashes=false;}}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
*/disableBorderDashes(ctx,values){if(values.borderDashes!==false){if(ctx.setLineDash!==undefined){ctx.setLineDash([0]);}else {console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");this.options.shapeProperties.borderDashes=false;values.borderDashes=false;}}}/**
* Determine if the shape of a node needs to be recalculated.
*
* @param {boolean} selected
* @param {boolean} hover
* @returns {boolean}
* @protected
*/needsRefresh(selected,hover){if(this.refreshNeeded===true){// This is probably not the best location to reset this member.
// However, in the current logic, it is the most convenient one.
this.refreshNeeded=false;return true;}return this.width===undefined||this.labelModule.differentState(selected,hover);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
*/initContextForDraw(ctx,values){const borderWidth=values.borderWidth/this.body.view.scale;ctx.lineWidth=Math.min(this.width,borderWidth);ctx.strokeStyle=values.borderColor;ctx.fillStyle=values.color;}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
*/performStroke(ctx,values){const borderWidth=values.borderWidth/this.body.view.scale;//draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
ctx.save();// if borders are zero width, they will be drawn with width 1 by default. This prevents that
if(borderWidth>0){this.enableBorderDashes(ctx,values);//draw the border
ctx.stroke();//disable dashed border for other elements
this.disableBorderDashes(ctx,values);}ctx.restore();}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
*/performFill(ctx,values){ctx.save();ctx.fillStyle=values.color;// draw shadow if enabled
this.enableShadow(ctx,values);// draw the background
ctx.fill();// disable shadows for other elements.
this.disableShadow(ctx,values);ctx.restore();this.performStroke(ctx,values);}/**
*
* @param {number} margin
* @private
*/_addBoundingBoxMargin(margin){this.boundingBox.left-=margin;this.boundingBox.top-=margin;this.boundingBox.bottom+=margin;this.boundingBox.right+=margin;}/**
* Actual implementation of this method call.
*
* Doing it like this makes it easier to override
* in the child classes.
*
* @param {number} x width
* @param {number} y height
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
* @private
*/_updateBoundingBox(x,y,ctx,selected,hover){if(ctx!==undefined){this.resize(ctx,selected,hover);}this.left=x-this.width/2;this.top=y-this.height/2;this.boundingBox.left=this.left;this.boundingBox.top=this.top;this.boundingBox.bottom=this.top+this.height;this.boundingBox.right=this.left+this.width;}/**
* Default implementation of this method call.
* This acts as a stub which can be overridden.
*
* @param {number} x width
* @param {number} y height
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
*/updateBoundingBox(x,y,ctx,selected,hover){this._updateBoundingBox(x,y,ctx,selected,hover);}/**
* Determine the dimensions to use for nodes with an internal label
*
* Currently, these are: Circle, Ellipse, Database, Box
* The other nodes have external labels, and will not call this method
*
* If there is no label, decent default values are supplied.
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
* @returns {{width:number, height:number}}
*/getDimensionsFromLabel(ctx,selected,hover){// NOTE: previously 'textSize' was not put in 'this' for Ellipse
// TODO: examine the consequences.
this.textSize=this.labelModule.getTextSize(ctx,selected,hover);let width=this.textSize.width;let height=this.textSize.height;const DEFAULT_SIZE=14;if(width===0){// This happens when there is no label text set
width=DEFAULT_SIZE;// use a decent default
height=DEFAULT_SIZE;// if width zero, then height also always zero
}return {width:width,height:height};}}/**
* A Box Node/Cluster shape.
*
* @augments NodeBase
*/let Box$1=class Box extends NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
*/resize(ctx,selected=this.selected,hover=this.hover){if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);this.width=dimensions.width+this.margin.right+this.margin.left;this.height=dimensions.height+this.margin.top+this.margin.bottom;this.radius=this.width/2;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
*/draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;this.initContextForDraw(ctx,values);drawRoundRect(ctx,this.left,this.top,this.width,this.height,values.borderRadius);this.performFill(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,this.top+this.textSize.height/2+this.margin.top,selected,hover);}/**
*
* @param {number} x width
* @param {number} y height
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
*/updateBoundingBox(x,y,ctx,selected,hover){this._updateBoundingBox(x,y,ctx,selected,hover);const borderRadius=this.options.shapeProperties.borderRadius;// only effective for box
this._addBoundingBoxMargin(borderRadius);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){if(ctx){this.resize(ctx);}const borderWidth=this.options.borderWidth;return Math.min(Math.abs(this.width/2/Math.cos(angle)),Math.abs(this.height/2/Math.sin(angle)))+borderWidth;}};/**
* NOTE: This is a bad base class
*
* Child classes are:
*
* Image - uses *only* image methods
* Circle - uses *only* _drawRawCircle
* CircleImage - uses all
*
* TODO: Refactor, move _drawRawCircle to different module, derive Circle from NodeBase
* Rename this to ImageBase
* Consolidate common code in Image and CircleImage to base class
*
* @augments NodeBase
*/class CircleImageBase extends NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);this.labelOffset=0;this.selected=false;}/**
*
* @param {object} options
* @param {object} [imageObj]
* @param {object} [imageObjAlt]
*/setOptions(options,imageObj,imageObjAlt){this.options=options;if(!(imageObj===undefined&&imageObjAlt===undefined)){this.setImages(imageObj,imageObjAlt);}}/**
* Set the images for this node.
*
* The images can be updated after the initial setting of options;
* therefore, this method needs to be reentrant.
*
* For correct working in error cases, it is necessary to properly set
* field 'nodes.brokenImage' in the options.
*
* @param {Image} imageObj required; main image to show for this node
* @param {Image|undefined} imageObjAlt optional; image to show when node is selected
*/setImages(imageObj,imageObjAlt){if(imageObjAlt&&this.selected){this.imageObj=imageObjAlt;this.imageObjAlt=imageObj;}else {this.imageObj=imageObj;this.imageObjAlt=imageObjAlt;}}/**
* Set selection and switch between the base and the selected image.
*
* Do the switch only if imageObjAlt exists.
*
* @param {boolean} selected value of new selected state for current node
*/switchImages(selected){const selection_changed=selected&&!this.selected||!selected&&this.selected;this.selected=selected;// Remember new selection
if(this.imageObjAlt!==undefined&&selection_changed){const imageTmp=this.imageObj;this.imageObj=this.imageObjAlt;this.imageObjAlt=imageTmp;}}/**
* Returns Image Padding from node options
*
* @returns {{top: number,left: number,bottom: number,right: number}} image padding inside this shape
* @private
*/_getImagePadding(){const imgPadding={top:0,right:0,bottom:0,left:0};if(this.options.imagePadding){const optImgPadding=this.options.imagePadding;if(typeof optImgPadding=="object"){imgPadding.top=optImgPadding.top;imgPadding.right=optImgPadding.right;imgPadding.bottom=optImgPadding.bottom;imgPadding.left=optImgPadding.left;}else {imgPadding.top=optImgPadding;imgPadding.right=optImgPadding;imgPadding.bottom=optImgPadding;imgPadding.left=optImgPadding;}}return imgPadding;}/**
* Adjust the node dimensions for a loaded image.
*
* Pre: this.imageObj is valid
*/_resizeImage(){let width,height;if(this.options.shapeProperties.useImageSize===false){// Use the size property
let ratio_width=1;let ratio_height=1;// Only calculate the proper ratio if both width and height not zero
if(this.imageObj.width&&this.imageObj.height){if(this.imageObj.width>this.imageObj.height){ratio_width=this.imageObj.width/this.imageObj.height;}else {ratio_height=this.imageObj.height/this.imageObj.width;}}width=this.options.size*2*ratio_width;height=this.options.size*2*ratio_height;}else {// Use the image size with image padding
const imgPadding=this._getImagePadding();width=this.imageObj.width+imgPadding.left+imgPadding.right;height=this.imageObj.height+imgPadding.top+imgPadding.bottom;}this.width=width;this.height=height;this.radius=0.5*this.width;}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {ArrowOptions} values
* @private
*/_drawRawCircle(ctx,x,y,values){this.initContextForDraw(ctx,values);drawCircle(ctx,x,y,values.size);this.performFill(ctx,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {ArrowOptions} values
* @private
*/_drawImageAtPosition(ctx,values){if(this.imageObj.width!=0){// draw the image
ctx.globalAlpha=values.opacity!==undefined?values.opacity:1;// draw shadow if enabled
this.enableShadow(ctx,values);let factor=1;if(this.options.shapeProperties.interpolation===true){factor=this.imageObj.width/this.width/this.body.view.scale;}const imgPadding=this._getImagePadding();const imgPosLeft=this.left+imgPadding.left;const imgPosTop=this.top+imgPadding.top;const imgWidth=this.width-imgPadding.left-imgPadding.right;const imgHeight=this.height-imgPadding.top-imgPadding.bottom;this.imageObj.drawImageAtPosition(ctx,factor,imgPosLeft,imgPosTop,imgWidth,imgHeight);// disable shadows for other elements.
this.disableShadow(ctx,values);}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @private
*/_drawImageLabel(ctx,x,y,selected,hover){let offset=0;if(this.height!==undefined){offset=this.height*0.5;const labelDimensions=this.labelModule.getTextSize(ctx,selected,hover);if(labelDimensions.lineCount>=1){offset+=labelDimensions.height/2;}}const yLabel=y+offset;if(this.options.label){this.labelOffset=offset;}this.labelModule.draw(ctx,x,yLabel,selected,hover,"hanging");}}/**
* A Circle Node/Cluster shape.
*
* @augments CircleImageBase
*/let Circle$1=class Circle extends CircleImageBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
*/resize(ctx,selected=this.selected,hover=this.hover){if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);const diameter=Math.max(dimensions.width+this.margin.right+this.margin.left,dimensions.height+this.margin.top+this.margin.bottom);this.options.size=diameter/2;// NOTE: this size field only set here, not in Ellipse, Database, Box
this.width=diameter;this.height=diameter;this.radius=this.width/2;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
*/draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;this._drawRawCircle(ctx,x,y,values);this.updateBoundingBox(x,y);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,y,selected,hover);}/**
*
* @param {number} x width
* @param {number} y height
*/updateBoundingBox(x,y){this.boundingBox.top=y-this.options.size;this.boundingBox.left=x-this.options.size;this.boundingBox.right=x+this.options.size;this.boundingBox.bottom=y+this.options.size;}/**
*
* @param {CanvasRenderingContext2D} ctx
* @returns {number}
*/distanceToBorder(ctx){if(ctx){this.resize(ctx);}return this.width*0.5;}};/**
* A CircularImage Node/Cluster shape.
*
* @augments CircleImageBase
*/class CircularImage extends CircleImageBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
* @param {Image} imageObj
* @param {Image} imageObjAlt
*/constructor(options,body,labelModule,imageObj,imageObjAlt){super(options,body,labelModule);this.setImages(imageObj,imageObjAlt);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
*/resize(ctx,selected=this.selected,hover=this.hover){const imageAbsent=this.imageObj.src===undefined||this.imageObj.width===undefined||this.imageObj.height===undefined;if(imageAbsent){const diameter=this.options.size*2;this.width=diameter;this.height=diameter;this.radius=0.5*this.width;return;}// At this point, an image is present, i.e. this.imageObj is valid.
if(this.needsRefresh(selected,hover)){this._resizeImage();}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
*/draw(ctx,x,y,selected,hover,values){this.switchImages(selected);this.resize();let labelX=x,labelY=y;if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.left=x;this.top=y;labelX+=this.width/2;labelY+=this.height/2;}else {this.left=x-this.width/2;this.top=y-this.height/2;}// draw the background circle. IMPORTANT: the stroke in this method is used by the clip method below.
this._drawRawCircle(ctx,labelX,labelY,values);// now we draw in the circle, we save so we can revert the clip operation after drawing.
ctx.save();// clip is used to use the stroke in drawRawCircle as an area that we can draw in.
ctx.clip();// draw the image
this._drawImageAtPosition(ctx,values);// restore so we can again draw on the full canvas
ctx.restore();this._drawImageLabel(ctx,labelX,labelY,selected,hover);this.updateBoundingBox(x,y);}// TODO: compare with Circle.updateBoundingBox(), consolidate? More stuff is happening here
/**
*
* @param {number} x width
* @param {number} y height
*/updateBoundingBox(x,y){if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.boundingBox.top=y;this.boundingBox.left=x;this.boundingBox.right=x+this.options.size*2;this.boundingBox.bottom=y+this.options.size*2;}else {this.boundingBox.top=y-this.options.size;this.boundingBox.left=x-this.options.size;this.boundingBox.right=x+this.options.size;this.boundingBox.bottom=y+this.options.size;}// TODO: compare with Image.updateBoundingBox(), consolidate?
this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelOffset);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @returns {number}
*/distanceToBorder(ctx){if(ctx){this.resize(ctx);}return this.width*0.5;}}/**
* Base class for constructing Node/Cluster Shapes.
*
* @augments NodeBase
*/class ShapeBase extends NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
* @param {object} [values={size: this.options.size}]
*/resize(ctx,selected=this.selected,hover=this.hover,values={size:this.options.size}){if(this.needsRefresh(selected,hover)){var _this$customSizeWidth,_this$customSizeHeigh;this.labelModule.getTextSize(ctx,selected,hover);const size=2*values.size;this.width=(_this$customSizeWidth=this.customSizeWidth)!==null&&_this$customSizeWidth!==void 0?_this$customSizeWidth:size;this.height=(_this$customSizeHeigh=this.customSizeHeight)!==null&&_this$customSizeHeigh!==void 0?_this$customSizeHeigh:size;this.radius=0.5*this.width;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {string} shape
* @param {number} sizeMultiplier - Unused! TODO: Remove next major release
* @param {number} x
* @param {number} y
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @private
* @returns {object} Callbacks to draw later on higher layers.
*/_drawShape(ctx,shape,sizeMultiplier,x,y,selected,hover,values){this.resize(ctx,selected,hover,values);this.left=x-this.width/2;this.top=y-this.height/2;this.initContextForDraw(ctx,values);getShape(shape)(ctx,x,y,values.size);this.performFill(ctx,values);if(this.options.icon!==undefined){if(this.options.icon.code!==undefined){ctx.font=(selected?"bold ":"")+this.height/2+"px "+(this.options.icon.face||"FontAwesome");ctx.fillStyle=this.options.icon.color||"black";ctx.textAlign="center";ctx.textBaseline="middle";ctx.fillText(this.options.icon.code,x,y);}}return {drawExternalLabel:()=>{if(this.options.label!==undefined){// Need to call following here in order to ensure value for
// `this.labelModule.size.height`.
this.labelModule.calculateLabelSize(ctx,selected,hover,x,y,"hanging");const yLabel=y+0.5*this.height+0.5*this.labelModule.size.height;this.labelModule.draw(ctx,x,yLabel,selected,hover,"hanging");}this.updateBoundingBox(x,y);}};}/**
*
* @param {number} x
* @param {number} y
*/updateBoundingBox(x,y){this.boundingBox.top=y-this.options.size;this.boundingBox.left=x-this.options.size;this.boundingBox.right=x+this.options.size;this.boundingBox.bottom=y+this.options.size;if(this.options.label!==undefined&&this.labelModule.size.width>0){this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelModule.size.height);}}}/**
* A CustomShape Node/Cluster shape.
*
* @augments ShapeBase
*/class CustomShape extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
* @param {Function} ctxRenderer
*/constructor(options,body,labelModule,ctxRenderer){super(options,body,labelModule,ctxRenderer);this.ctxRenderer=ctxRenderer;}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on different layers.
*/draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover,values);this.left=x-this.width/2;this.top=y-this.height/2;// Guard right away because someone may just draw in the function itself.
ctx.save();const drawLater=this.ctxRenderer({ctx,id:this.options.id,x,y,state:{selected,hover},style:{...values},label:this.options.label});// Render the node shape bellow arrows.
if(drawLater.drawNode!=null){drawLater.drawNode();}ctx.restore();if(drawLater.drawExternalLabel){// Guard the external label (above arrows) drawing function.
const drawExternalLabel=drawLater.drawExternalLabel;drawLater.drawExternalLabel=()=>{ctx.save();drawExternalLabel();ctx.restore();};}if(drawLater.nodeDimensions){this.customSizeWidth=drawLater.nodeDimensions.width;this.customSizeHeight=drawLater.nodeDimensions.height;}return drawLater;}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* A Database Node/Cluster shape.
*
* @augments NodeBase
*/class Database extends NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
*/resize(ctx,selected,hover){if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);const size=dimensions.width+this.margin.right+this.margin.left;this.width=size;this.height=size;this.radius=this.width/2;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
*/draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;this.initContextForDraw(ctx,values);drawDatabase(ctx,x-this.width/2,y-this.height/2,this.width,this.height);this.performFill(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,this.top+this.textSize.height/2+this.margin.top,selected,hover);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* A Diamond Node/Cluster shape.
*
* @augments ShapeBase
*/let Diamond$1=class Diamond extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"diamond",4,x,y,selected,hover,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}};/**
* A Dot Node/Cluster shape.
*
* @augments ShapeBase
*/class Dot extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"circle",2,x,y,selected,hover,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @returns {number}
*/distanceToBorder(ctx){if(ctx){this.resize(ctx);}return this.options.size;}}/**
* Am Ellipse Node/Cluster shape.
*
* @augments NodeBase
*/class Ellipse extends NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
*/resize(ctx,selected=this.selected,hover=this.hover){if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);this.height=dimensions.height*2;this.width=dimensions.width+dimensions.height;this.radius=0.5*this.width;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
*/draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width*0.5;this.top=y-this.height*0.5;this.initContextForDraw(ctx,values);drawEllipse(ctx,this.left,this.top,this.width,this.height);this.performFill(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);this.labelModule.draw(ctx,x,y,selected,hover);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){if(ctx){this.resize(ctx);}const a=this.width*0.5;const b=this.height*0.5;const w=Math.sin(angle)*a;const h=Math.cos(angle)*b;return a*b/Math.sqrt(w*w+h*h);}}/**
* An icon replacement for the default Node shape.
*
* @augments NodeBase
*/class Icon extends NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx - Unused.
* @param {boolean} [selected]
* @param {boolean} [hover]
*/resize(ctx,selected,hover){if(this.needsRefresh(selected,hover)){this.iconSize={width:Number(this.options.icon.size),height:Number(this.options.icon.size)};this.width=this.iconSize.width+this.margin.right+this.margin.left;this.height=this.iconSize.height+this.margin.top+this.margin.bottom;this.radius=0.5*this.width;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.options.icon.size=this.options.icon.size||50;this.left=x-this.width/2;this.top=y-this.height/2;this._icon(ctx,x,y,selected,hover,values);return {drawExternalLabel:()=>{if(this.options.label!==undefined){const iconTextSpacing=5;this.labelModule.draw(ctx,this.left+this.iconSize.width/2+this.margin.left,y+this.height/2+iconTextSpacing,selected);}this.updateBoundingBox(x,y);}};}/**
*
* @param {number} x
* @param {number} y
*/updateBoundingBox(x,y){this.boundingBox.top=y-this.options.icon.size*0.5;this.boundingBox.left=x-this.options.icon.size*0.5;this.boundingBox.right=x+this.options.icon.size*0.5;this.boundingBox.bottom=y+this.options.icon.size*0.5;if(this.options.label!==undefined&&this.labelModule.size.width>0){const iconTextSpacing=5;this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelModule.size.height+iconTextSpacing);}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover - Unused
* @param {ArrowOptions} values
*/_icon(ctx,x,y,selected,hover,values){const iconSize=Number(this.options.icon.size);if(this.options.icon.code!==undefined){ctx.font=[this.options.icon.weight!=null?this.options.icon.weight:selected?"bold":"",// If the weight is forced (for example to make Font Awesome 5 work
// properly) substitute slightly bigger size for bold font face.
(this.options.icon.weight!=null&&selected?5:0)+iconSize+"px",this.options.icon.face].join(" ");// draw icon
ctx.fillStyle=this.options.icon.color||"black";ctx.textAlign="center";ctx.textBaseline="middle";// draw shadow if enabled
this.enableShadow(ctx,values);ctx.fillText(this.options.icon.code,x,y);// disable shadows for other elements.
this.disableShadow(ctx,values);}else {console.error("When using the icon shape, you need to define the code in the icon options object. This can be done per node or globally.");}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* An image-based replacement for the default Node shape.
*
* @augments CircleImageBase
*/let Image$2=class Image extends CircleImageBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
* @param {Image} imageObj
* @param {Image} imageObjAlt
*/constructor(options,body,labelModule,imageObj,imageObjAlt){super(options,body,labelModule);this.setImages(imageObj,imageObjAlt);}/**
*
* @param {CanvasRenderingContext2D} ctx - Unused.
* @param {boolean} [selected]
* @param {boolean} [hover]
*/resize(ctx,selected=this.selected,hover=this.hover){const imageAbsent=this.imageObj.src===undefined||this.imageObj.width===undefined||this.imageObj.height===undefined;if(imageAbsent){const side=this.options.size*2;this.width=side;this.height=side;return;}if(this.needsRefresh(selected,hover)){this._resizeImage();}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
*/draw(ctx,x,y,selected,hover,values){ctx.save();this.switchImages(selected);this.resize();let labelX=x,labelY=y;if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.left=x;this.top=y;labelX+=this.width/2;labelY+=this.height/2;}else {this.left=x-this.width/2;this.top=y-this.height/2;}if(this.options.shapeProperties.useBorderWithImage===true){const neutralborderWidth=this.options.borderWidth;const selectionLineWidth=this.options.borderWidthSelected||2*this.options.borderWidth;const borderWidth=(selected?selectionLineWidth:neutralborderWidth)/this.body.view.scale;ctx.lineWidth=Math.min(this.width,borderWidth);ctx.beginPath();let strokeStyle=selected?this.options.color.highlight.border:hover?this.options.color.hover.border:this.options.color.border;let fillStyle=selected?this.options.color.highlight.background:hover?this.options.color.hover.background:this.options.color.background;if(values.opacity!==undefined){strokeStyle=overrideOpacity(strokeStyle,values.opacity);fillStyle=overrideOpacity(fillStyle,values.opacity);}// setup the line properties.
ctx.strokeStyle=strokeStyle;// set a fillstyle
ctx.fillStyle=fillStyle;// draw a rectangle to form the border around. This rectangle is filled so the opacity of a picture (in future vis releases?) can be used to tint the image
ctx.rect(this.left-0.5*ctx.lineWidth,this.top-0.5*ctx.lineWidth,this.width+ctx.lineWidth,this.height+ctx.lineWidth);ctx.fill();this.performStroke(ctx,values);ctx.closePath();}this._drawImageAtPosition(ctx,values);this._drawImageLabel(ctx,labelX,labelY,selected,hover);this.updateBoundingBox(x,y);ctx.restore();}/**
*
* @param {number} x
* @param {number} y
*/updateBoundingBox(x,y){this.resize();if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.left=x;this.top=y;}else {this.left=x-this.width/2;this.top=y-this.height/2;}this.boundingBox.left=this.left;this.boundingBox.top=this.top;this.boundingBox.bottom=this.top+this.height;this.boundingBox.right=this.left+this.width;if(this.options.label!==undefined&&this.labelModule.size.width>0){this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelOffset);}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}};/**
* A Square Node/Cluster shape.
*
* @augments ShapeBase
*/class Square extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"square",2,x,y,selected,hover,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* A Hexagon Node/Cluster shape.
*
* @augments ShapeBase
*/class Hexagon extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"hexagon",4,x,y,selected,hover,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* A Star Node/Cluster shape.
*
* @augments ShapeBase
*/class Star extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"star",4,x,y,selected,hover,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* A text-based replacement for the default Node shape.
*
* @augments NodeBase
*/class Text extends NodeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
*/resize(ctx,selected,hover){if(this.needsRefresh(selected,hover)){this.textSize=this.labelModule.getTextSize(ctx,selected,hover);this.width=this.textSize.width+this.margin.right+this.margin.left;this.height=this.textSize.height+this.margin.top+this.margin.bottom;this.radius=0.5*this.width;}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
*/draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;// draw shadow if enabled
this.enableShadow(ctx,values);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,this.top+this.textSize.height/2+this.margin.top,selected,hover);// disable shadows for other elements.
this.disableShadow(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* A Triangle Node/Cluster shape.
*
* @augments ShapeBase
*/let Triangle$1=class Triangle extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x
* @param {number} y
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"triangle",3,x,y,selected,hover,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}};/**
* A downward facing Triangle Node/Cluster shape.
*
* @augments ShapeBase
*/class TriangleDown extends ShapeBase{/**
* @param {object} options
* @param {object} body
* @param {Label} labelModule
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x
* @param {number} y
* @param {boolean} selected
* @param {boolean} hover
* @param {ArrowOptions} values
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"triangleDown",3,x,y,selected,hover,values);}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
*/distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
* A node. A node can be connected to other nodes via one or multiple edges.
*/class Node{/**
*
* @param {object} options An object containing options for the node. All
* options are optional, except for the id.
* {number} id Id of the node. Required
* {string} label Text label for the node
* {number} x Horizontal position of the node
* {number} y Vertical position of the node
* {string} shape Node shape
* {string} image An image url
* {string} title A title text, can be HTML
* {anytype} group A group name or number
* @param {object} body Shared state of current network instance
* @param {Network.Images} imagelist A list with images. Only needed when the node has an image
* @param {Groups} grouplist A list with groups. Needed for retrieving group options
* @param {object} globalOptions Current global node options; these serve as defaults for the node instance
* @param {object} defaultOptions Global default options for nodes; note that this is also the prototype
* for parameter `globalOptions`.
*/constructor(options,body,imagelist,grouplist,globalOptions,defaultOptions){this.options=bridgeObject(globalOptions);this.globalOptions=globalOptions;this.defaultOptions=defaultOptions;this.body=body;this.edges=[];// all edges connected to this node
// set defaults for the options
this.id=undefined;this.imagelist=imagelist;this.grouplist=grouplist;// state options
this.x=undefined;this.y=undefined;this.baseSize=this.options.size;this.baseFontSize=this.options.font.size;this.predefinedPosition=false;// used to check if initial fit should just take the range or approximate
this.selected=false;this.hover=false;this.labelModule=new Label(this.body,this.options,false/* Not edge label */);this.setOptions(options);}/**
* Attach a edge to the node
*
* @param {Edge} edge
*/attachEdge(edge){if(this.edges.indexOf(edge)===-1){this.edges.push(edge);}}/**
* Detach a edge from the node
*
* @param {Edge} edge
*/detachEdge(edge){const index=this.edges.indexOf(edge);if(index!=-1){this.edges.splice(index,1);}}/**
* Set or overwrite options for the node
*
* @param {object} options an object with options
* @returns {null|boolean}
*/setOptions(options){const currentShape=this.options.shape;if(!options){return;// Note that the return value will be 'undefined'! This is OK.
}// Save the color for later.
// This is necessary in order to prevent local color from being overwritten by group color.
// TODO: To prevent such workarounds the way options are handled should be rewritten from scratch.
// This is not the only problem with current options handling.
if(typeof options.color!=="undefined"){this._localColor=options.color;}// basic options
if(options.id!==undefined){this.id=options.id;}if(this.id===undefined){throw new Error("Node must have an id");}Node.checkMass(options,this.id);// set these options locally
// clear x and y positions
if(options.x!==undefined){if(options.x===null){this.x=undefined;this.predefinedPosition=false;}else {this.x=parseInt(options.x);this.predefinedPosition=true;}}if(options.y!==undefined){if(options.y===null){this.y=undefined;this.predefinedPosition=false;}else {this.y=parseInt(options.y);this.predefinedPosition=true;}}if(options.size!==undefined){this.baseSize=options.size;}if(options.value!==undefined){options.value=parseFloat(options.value);}// this transforms all shorthands into fully defined options
Node.parseOptions(this.options,options,true,this.globalOptions,this.grouplist);const pile=[options,this.options,this.defaultOptions];this.chooser=choosify("node",pile);this._load_images();this.updateLabelModule(options);// Need to set local opacity after `this.updateLabelModule(options);` because `this.updateLabelModule(options);` overrites local opacity with group opacity
if(options.opacity!==undefined&&Node.checkOpacity(options.opacity)){this.options.opacity=options.opacity;}this.updateShape(currentShape);return options.hidden!==undefined||options.physics!==undefined;}/**
* Load the images from the options, for the nodes that need them.
*
* Images are always loaded, even if they are not used in the current shape.
* The user may switch to an image shape later on.
*
* @private
*/_load_images(){if(this.options.shape==="circularImage"||this.options.shape==="image"){if(this.options.image===undefined){throw new Error("Option image must be defined for node type '"+this.options.shape+"'");}}if(this.options.image===undefined){return;}if(this.imagelist===undefined){throw new Error("Internal Error: No images provided");}if(typeof this.options.image==="string"){this.imageObj=this.imagelist.load(this.options.image,this.options.brokenImage,this.id);}else {if(this.options.image.unselected===undefined){throw new Error("No unselected image provided");}this.imageObj=this.imagelist.load(this.options.image.unselected,this.options.brokenImage,this.id);if(this.options.image.selected!==undefined){this.imageObjAlt=this.imagelist.load(this.options.image.selected,this.options.brokenImage,this.id);}else {this.imageObjAlt=undefined;}}}/**
* Check that opacity is only between 0 and 1
*
* @param {number} opacity
* @returns {boolean}
*/static checkOpacity(opacity){return 0<=opacity&&opacity<=1;}/**
* Check that origin is 'center' or 'top-left'
*
* @param {string} origin
* @returns {boolean}
*/static checkCoordinateOrigin(origin){return origin===undefined||origin==="center"||origin==="top-left";}/**
* Copy group option values into the node options.
*
* The group options override the global node options, so the copy of group options
* must happen *after* the global node options have been set.
*
* This method must also be called also if the global node options have changed and the group options did not.
*
* @param {object} parentOptions
* @param {object} newOptions new values for the options, currently only passed in for check
* @param {object} groupList
*/static updateGroupOptions(parentOptions,newOptions,groupList){if(groupList===undefined)return;// No groups, nothing to do
const group=parentOptions.group;// paranoia: the selected group is already merged into node options, check.
if(newOptions!==undefined&&newOptions.group!==undefined&&group!==newOptions.group){throw new Error("updateGroupOptions: group values in options don't match.");}const hasGroup=typeof group==="number"||typeof group==="string"&&group!="";if(!hasGroup)return;// current node has no group, no need to merge
const groupObj=groupList.get(group);if(groupObj.opacity!==undefined&&newOptions.opacity===undefined){if(!Node.checkOpacity(groupObj.opacity)){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+groupObj.opacity);groupObj.opacity=undefined;}}// Skip any new option to avoid them being overridden by the group options.
const skipProperties=Object.getOwnPropertyNames(newOptions).filter(p=>newOptions[p]!=null);// Always skip merging group font options into parent; these are required to be distinct for labels
skipProperties.push("font");selectiveNotDeepExtend(skipProperties,parentOptions,groupObj);// the color object needs to be completely defined.
// Since groups can partially overwrite the colors, we parse it again, just in case.
parentOptions.color=parseColor(parentOptions.color);}/**
* This process all possible shorthands in the new options and makes sure that the parentOptions are fully defined.
* Static so it can also be used by the handler.
*
* @param {object} parentOptions
* @param {object} newOptions
* @param {boolean} [allowDeletion=false]
* @param {object} [globalOptions={}]
* @param {object} [groupList]
* @static
*/static parseOptions(parentOptions,newOptions,allowDeletion=false,globalOptions={},groupList){const fields=["color","fixed","shadow"];selectiveNotDeepExtend(fields,parentOptions,newOptions,allowDeletion);Node.checkMass(newOptions);if(parentOptions.opacity!==undefined){if(!Node.checkOpacity(parentOptions.opacity)){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+parentOptions.opacity);parentOptions.opacity=undefined;}}if(newOptions.opacity!==undefined){if(!Node.checkOpacity(newOptions.opacity)){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+newOptions.opacity);newOptions.opacity=undefined;}}if(newOptions.shapeProperties&&!Node.checkCoordinateOrigin(newOptions.shapeProperties.coordinateOrigin)){console.error("Invalid option for node coordinateOrigin, found: "+newOptions.shapeProperties.coordinateOrigin);}// merge the shadow options into the parent.
mergeOptions(parentOptions,newOptions,"shadow",globalOptions);// individual shape newOptions
if(newOptions.color!==undefined&&newOptions.color!==null){const parsedColor=parseColor(newOptions.color);fillIfDefined(parentOptions.color,parsedColor);}else if(allowDeletion===true&&newOptions.color===null){parentOptions.color=bridgeObject(globalOptions.color);// set the object back to the global options
}// handle the fixed options
if(newOptions.fixed!==undefined&&newOptions.fixed!==null){if(typeof newOptions.fixed==="boolean"){parentOptions.fixed.x=newOptions.fixed;parentOptions.fixed.y=newOptions.fixed;}else {if(newOptions.fixed.x!==undefined&&typeof newOptions.fixed.x==="boolean"){parentOptions.fixed.x=newOptions.fixed.x;}if(newOptions.fixed.y!==undefined&&typeof newOptions.fixed.y==="boolean"){parentOptions.fixed.y=newOptions.fixed.y;}}}if(allowDeletion===true&&newOptions.font===null){parentOptions.font=bridgeObject(globalOptions.font);// set the object back to the global options
}Node.updateGroupOptions(parentOptions,newOptions,groupList);// handle the scaling options, specifically the label part
if(newOptions.scaling!==undefined){mergeOptions(parentOptions.scaling,newOptions.scaling,"label",globalOptions.scaling);}}/**
*
* @returns {{color: *, borderWidth: *, borderColor: *, size: *, borderDashes: (boolean|Array|allOptions.nodes.shapeProperties.borderDashes|{boolean, array}), borderRadius: (number|allOptions.nodes.shapeProperties.borderRadius|{number}|Array), shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *}}
*/getFormattingValues(){const values={color:this.options.color.background,opacity:this.options.opacity,borderWidth:this.options.borderWidth,borderColor:this.options.color.border,size:this.options.size,borderDashes:this.options.shapeProperties.borderDashes,borderRadius:this.options.shapeProperties.borderRadius,shadow:this.options.shadow.enabled,shadowColor:this.options.shadow.color,shadowSize:this.options.shadow.size,shadowX:this.options.shadow.x,shadowY:this.options.shadow.y};if(this.selected||this.hover){if(this.chooser===true){if(this.selected){if(this.options.borderWidthSelected!=null){values.borderWidth=this.options.borderWidthSelected;}else {values.borderWidth*=2;}values.color=this.options.color.highlight.background;values.borderColor=this.options.color.highlight.border;values.shadow=this.options.shadow.enabled;}else if(this.hover){values.color=this.options.color.hover.background;values.borderColor=this.options.color.hover.border;values.shadow=this.options.shadow.enabled;}}else if(typeof this.chooser==="function"){this.chooser(values,this.options.id,this.selected,this.hover);if(values.shadow===false){if(values.shadowColor!==this.options.shadow.color||values.shadowSize!==this.options.shadow.size||values.shadowX!==this.options.shadow.x||values.shadowY!==this.options.shadow.y){values.shadow=true;}}}}else {values.shadow=this.options.shadow.enabled;}if(this.options.opacity!==undefined){const opacity=this.options.opacity;values.borderColor=overrideOpacity(values.borderColor,opacity);values.color=overrideOpacity(values.color,opacity);values.shadowColor=overrideOpacity(values.shadowColor,opacity);}return values;}/**
*
* @param {object} options
*/updateLabelModule(options){if(this.options.label===undefined||this.options.label===null){this.options.label="";}Node.updateGroupOptions(this.options,{...options,color:options&&options.color||this._localColor||undefined},this.grouplist);//
// Note:The prototype chain for this.options is:
//
// this.options -> NodesHandler.options -> NodesHandler.defaultOptions
// (also: this.globalOptions)
//
// Note that the prototypes are mentioned explicitly in the pile list below;
// WE DON'T WANT THE ORDER OF THE PROTOTYPES!!!! At least, not for font handling of labels.
// This is a good indication that the prototype usage of options is deficient.
//
const currentGroup=this.grouplist.get(this.options.group,false);const pile=[options,// new options
this.options,// current node options, see comment above for prototype
currentGroup,// group options, if any
this.globalOptions,// Currently set global node options
this.defaultOptions// Default global node options
];this.labelModule.update(this.options,pile);if(this.labelModule.baseSize!==undefined){this.baseFontSize=this.labelModule.baseSize;}}/**
*
* @param {string} currentShape
*/updateShape(currentShape){if(currentShape===this.options.shape&&this.shape){this.shape.setOptions(this.options,this.imageObj,this.imageObjAlt);}else {// choose draw method depending on the shape
switch(this.options.shape){case"box":this.shape=new Box$1(this.options,this.body,this.labelModule);break;case"circle":this.shape=new Circle$1(this.options,this.body,this.labelModule);break;case"circularImage":this.shape=new CircularImage(this.options,this.body,this.labelModule,this.imageObj,this.imageObjAlt);break;case"custom":this.shape=new CustomShape(this.options,this.body,this.labelModule,this.options.ctxRenderer);break;case"database":this.shape=new Database(this.options,this.body,this.labelModule);break;case"diamond":this.shape=new Diamond$1(this.options,this.body,this.labelModule);break;case"dot":this.shape=new Dot(this.options,this.body,this.labelModule);break;case"ellipse":this.shape=new Ellipse(this.options,this.body,this.labelModule);break;case"icon":this.shape=new Icon(this.options,this.body,this.labelModule);break;case"image":this.shape=new Image$2(this.options,this.body,this.labelModule,this.imageObj,this.imageObjAlt);break;case"square":this.shape=new Square(this.options,this.body,this.labelModule);break;case"hexagon":this.shape=new Hexagon(this.options,this.body,this.labelModule);break;case"star":this.shape=new Star(this.options,this.body,this.labelModule);break;case"text":this.shape=new Text(this.options,this.body,this.labelModule);break;case"triangle":this.shape=new Triangle$1(this.options,this.body,this.labelModule);break;case"triangleDown":this.shape=new TriangleDown(this.options,this.body,this.labelModule);break;default:this.shape=new Ellipse(this.options,this.body,this.labelModule);break;}}this.needsRefresh();}/**
* select this node
*/select(){this.selected=true;this.needsRefresh();}/**
* unselect this node
*/unselect(){this.selected=false;this.needsRefresh();}/**
* Reset the calculated size of the node, forces it to recalculate its size
*/needsRefresh(){this.shape.refreshNeeded=true;}/**
* get the title of this node.
*
* @returns {string} title The title of the node, or undefined when no title
* has been set.
*/getTitle(){return this.options.title;}/**
* Calculate the distance to the border of the Node
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle Angle in radians
* @returns {number} distance Distance to the border in pixels
*/distanceToBorder(ctx,angle){return this.shape.distanceToBorder(ctx,angle);}/**
* Check if this node has a fixed x and y position
*
* @returns {boolean} true if fixed, false if not
*/isFixed(){return this.options.fixed.x&&this.options.fixed.y;}/**
* check if this node is selecte
*
* @returns {boolean} selected True if node is selected, else false
*/isSelected(){return this.selected;}/**
* Retrieve the value of the node. Can be undefined
*
* @returns {number} value
*/getValue(){return this.options.value;}/**
* Get the current dimensions of the label
*
* @returns {rect}
*/getLabelSize(){return this.labelModule.size();}/**
* Adjust the value range of the node. The node will adjust it's size
* based on its value.
*
* @param {number} min
* @param {number} max
* @param {number} total
*/setValueRange(min,max,total){if(this.options.value!==undefined){const scale=this.options.scaling.customScalingFunction(min,max,total,this.options.value);const sizeDiff=this.options.scaling.max-this.options.scaling.min;if(this.options.scaling.label.enabled===true){const fontDiff=this.options.scaling.label.max-this.options.scaling.label.min;this.options.font.size=this.options.scaling.label.min+scale*fontDiff;}this.options.size=this.options.scaling.min+scale*sizeDiff;}else {this.options.size=this.baseSize;this.options.font.size=this.baseFontSize;}this.updateLabelModule();}/**
* Draw this node in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
*
* @param {CanvasRenderingContext2D} ctx
* @returns {object} Callbacks to draw later on higher layers.
*/draw(ctx){const values=this.getFormattingValues();return this.shape.draw(ctx,this.x,this.y,this.selected,this.hover,values)||{};}/**
* Update the bounding box of the shape
*
* @param {CanvasRenderingContext2D} ctx
*/updateBoundingBox(ctx){this.shape.updateBoundingBox(this.x,this.y,ctx);}/**
* Recalculate the size of this node in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
*
* @param {CanvasRenderingContext2D} ctx
*/resize(ctx){const values=this.getFormattingValues();this.shape.resize(ctx,this.selected,this.hover,values);}/**
* Determine all visual elements of this node instance, in which the given
* point falls within the bounding shape.
*
* @param {point} point
* @returns {Array.<nodeClickItem|nodeLabelClickItem>} list with the items which are on the point
*/getItemsOnPoint(point){const ret=[];if(this.labelModule.visible()){if(pointInRect(this.labelModule.getSize(),point)){ret.push({nodeId:this.id,labelId:0});}}if(pointInRect(this.shape.boundingBox,point)){ret.push({nodeId:this.id});}return ret;}/**
* Check if this object is overlapping with the provided object
*
* @param {object} obj an object with parameters left, top, right, bottom
* @returns {boolean} True if location is located on node
*/isOverlappingWith(obj){return this.shape.left<obj.right&&this.shape.left+this.shape.width>obj.left&&this.shape.top<obj.bottom&&this.shape.top+this.shape.height>obj.top;}/**
* Check if this object is overlapping with the provided object
*
* @param {object} obj an object with parameters left, top, right, bottom
* @returns {boolean} True if location is located on node
*/isBoundingBoxOverlappingWith(obj){return this.shape.boundingBox.left<obj.right&&this.shape.boundingBox.right>obj.left&&this.shape.boundingBox.top<obj.bottom&&this.shape.boundingBox.bottom>obj.top;}/**
* Check valid values for mass
*
* The mass may not be negative or zero. If it is, reset to 1
*
* @param {object} options
* @param {Node.id} id
* @static
*/static checkMass(options,id){if(options.mass!==undefined&&options.mass<=0){let strId="";if(id!==undefined){strId=" in node id: "+id;}console.error("%cNegative or zero mass disallowed"+strId+", setting mass to 1.",VALIDATOR_PRINT_STYLE);options.mass=1;}}}/**
* Handler for Nodes
*/class NodesHandler{/**
* @param {object} body
* @param {Images} images
* @param {Array.<Group>} groups
* @param {LayoutEngine} layoutEngine
*/constructor(body,images,groups,layoutEngine){this.body=body;this.images=images;this.groups=groups;this.layoutEngine=layoutEngine;// create the node API in the body container
this.body.functions.createNode=this.create.bind(this);this.nodesListeners={add:(event,params)=>{this.add(params.items);},update:(event,params)=>{this.update(params.items,params.data,params.oldData);},remove:(event,params)=>{this.remove(params.items);}};this.defaultOptions={borderWidth:1,borderWidthSelected:undefined,brokenImage:undefined,color:{border:"#2B7CE9",background:"#97C2FC",highlight:{border:"#2B7CE9",background:"#D2E5FF"},hover:{border:"#2B7CE9",background:"#D2E5FF"}},opacity:undefined,// number between 0 and 1
fixed:{x:false,y:false},font:{color:"#343434",size:14,// px
face:"arial",background:"none",strokeWidth:0,// px
strokeColor:"#ffffff",align:"center",vadjust:0,multi:false,bold:{mod:"bold"},boldital:{mod:"bold italic"},ital:{mod:"italic"},mono:{mod:"",size:15,// px
face:"monospace",vadjust:2}},group:undefined,hidden:false,icon:{face:"FontAwesome",//'FontAwesome',
code:undefined,//'\uf007',
size:50,//50,
color:"#2B7CE9"//'#aa00ff'
},image:undefined,// --> URL
imagePadding:{// only for image shape
top:0,right:0,bottom:0,left:0},label:undefined,labelHighlightBold:true,level:undefined,margin:{top:5,right:5,bottom:5,left:5},mass:1,physics:true,scaling:{min:10,max:30,label:{enabled:false,min:14,max:30,maxVisible:30,drawThreshold:5},customScalingFunction:function(min,max,total,value){if(max===min){return 0.5;}else {const scale=1/(max-min);return Math.max(0,(value-min)*scale);}}},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:10,x:5,y:5},shape:"ellipse",shapeProperties:{borderDashes:false,// only for borders
borderRadius:6,// only for box shape
interpolation:true,// only for image and circularImage shapes
useImageSize:false,// only for image and circularImage shapes
useBorderWithImage:false,// only for image shape
coordinateOrigin:"center"// only for image and circularImage shapes
},size:25,title:undefined,value:undefined,x:undefined,y:undefined};// Protect from idiocy
if(this.defaultOptions.mass<=0){throw "Internal error: mass in defaultOptions of NodesHandler may not be zero or negative";}this.options=bridgeObject(this.defaultOptions);this.bindEventListeners();}/**
* Binds event listeners
*/bindEventListeners(){// refresh the nodes. Used when reverting from hierarchical layout
this.body.emitter.on("refreshNodes",this.refresh.bind(this));this.body.emitter.on("refresh",this.refresh.bind(this));this.body.emitter.on("destroy",()=>{forEach(this.nodesListeners,(callback,event)=>{if(this.body.data.nodes)this.body.data.nodes.off(event,callback);});delete this.body.functions.createNode;delete this.nodesListeners.add;delete this.nodesListeners.update;delete this.nodesListeners.remove;delete this.nodesListeners;});}/**
*
* @param {object} options
*/setOptions(options){if(options!==undefined){Node.parseOptions(this.options,options);// Need to set opacity here because Node.parseOptions is also used for groups,
// if you set opacity in Node.parseOptions it overwrites group opacity.
if(options.opacity!==undefined){if(Number.isNaN(options.opacity)||!Number.isFinite(options.opacity)||options.opacity<0||options.opacity>1){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+options.opacity);}else {this.options.opacity=options.opacity;}}// update the shape in all nodes
if(options.shape!==undefined){for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){this.body.nodes[nodeId].updateShape();}}}// Update the labels of nodes if any relevant options changed.
if(typeof options.font!=="undefined"||typeof options.widthConstraint!=="undefined"||typeof options.heightConstraint!=="undefined"){for(const nodeId of Object.keys(this.body.nodes)){this.body.nodes[nodeId].updateLabelModule();this.body.nodes[nodeId].needsRefresh();}}// update the shape size in all nodes
if(options.size!==undefined){for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){this.body.nodes[nodeId].needsRefresh();}}}// update the state of the variables if needed
if(options.hidden!==undefined||options.physics!==undefined){this.body.emitter.emit("_dataChanged");}}}/**
* Set a data set with nodes for the network
*
* @param {Array | DataSet | DataView} nodes The data containing the nodes.
* @param {boolean} [doNotEmit=false] - Suppress data changed event.
* @private
*/setData(nodes,doNotEmit=false){const oldNodesData=this.body.data.nodes;if(isDataViewLike$1("id",nodes)){this.body.data.nodes=nodes;}else if(Array.isArray(nodes)){this.body.data.nodes=new DataSet();this.body.data.nodes.add(nodes);}else if(!nodes){this.body.data.nodes=new DataSet();}else {throw new TypeError("Array or DataSet expected");}if(oldNodesData){// unsubscribe from old dataset
forEach(this.nodesListeners,function(callback,event){oldNodesData.off(event,callback);});}// remove drawn nodes
this.body.nodes={};if(this.body.data.nodes){// subscribe to new dataset
const me=this;forEach(this.nodesListeners,function(callback,event){me.body.data.nodes.on(event,callback);});// draw all new nodes
const ids=this.body.data.nodes.getIds();this.add(ids,true);}if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
* Add nodes
*
* @param {number[] | string[]} ids
* @param {boolean} [doNotEmit=false]
* @private
*/add(ids,doNotEmit=false){let id;const newNodes=[];for(let i=0;i<ids.length;i++){id=ids[i];const properties=this.body.data.nodes.get(id);const node=this.create(properties);newNodes.push(node);this.body.nodes[id]=node;// note: this may replace an existing node
}this.layoutEngine.positionInitially(newNodes);if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
* Update existing nodes, or create them when not yet existing
*
* @param {number[] | string[]} ids id's of changed nodes
* @param {Array} changedData array with changed data
* @param {Array|undefined} oldData optional; array with previous data
* @private
*/update(ids,changedData,oldData){const nodes=this.body.nodes;let dataChanged=false;for(let i=0;i<ids.length;i++){const id=ids[i];let node=nodes[id];const data=changedData[i];if(node!==undefined){// update node
if(node.setOptions(data)){dataChanged=true;}}else {dataChanged=true;// create node
node=this.create(data);nodes[id]=node;}}if(!dataChanged&&oldData!==undefined){// Check for any changes which should trigger a layout recalculation
// For now, this is just 'level' for hierarchical layout
// Assumption: old and new data arranged in same order; at time of writing, this holds.
dataChanged=changedData.some(function(newValue,index){const oldValue=oldData[index];return oldValue&&oldValue.level!==newValue.level;});}if(dataChanged===true){this.body.emitter.emit("_dataChanged");}else {this.body.emitter.emit("_dataUpdated");}}/**
* Remove existing nodes. If nodes do not exist, the method will just ignore it.
*
* @param {number[] | string[]} ids
* @private
*/remove(ids){const nodes=this.body.nodes;for(let i=0;i<ids.length;i++){const id=ids[i];delete nodes[id];}this.body.emitter.emit("_dataChanged");}/**
* create a node
*
* @param {object} properties
* @param {class} [constructorClass=Node.default]
* @returns {*}
*/create(properties,constructorClass=Node){return new constructorClass(properties,this.body,this.images,this.groups,this.options,this.defaultOptions);}/**
*
* @param {boolean} [clearPositions=false]
*/refresh(clearPositions=false){forEach(this.body.nodes,(node,nodeId)=>{const data=this.body.data.nodes.get(nodeId);if(data!==undefined){if(clearPositions===true){node.setOptions({x:null,y:null});}node.setOptions({fixed:false});node.setOptions(data);}});}/**
* Returns the positions of the nodes.
*
* @param {Array.<Node.id> | string} [ids] --> optional, can be array of nodeIds, can be string
* @returns {{}}
*/getPositions(ids){const dataArray={};if(ids!==undefined){if(Array.isArray(ids)===true){for(let i=0;i<ids.length;i++){if(this.body.nodes[ids[i]]!==undefined){const node=this.body.nodes[ids[i]];dataArray[ids[i]]={x:Math.round(node.x),y:Math.round(node.y)};}}}else {if(this.body.nodes[ids]!==undefined){const node=this.body.nodes[ids];dataArray[ids]={x:Math.round(node.x),y:Math.round(node.y)};}}}else {for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];dataArray[this.body.nodeIndices[i]]={x:Math.round(node.x),y:Math.round(node.y)};}}return dataArray;}/**
* Retrieves the x y position of a specific id.
*
* @param {string} id The id to retrieve.
* @throws {TypeError} If no id is included.
* @throws {ReferenceError} If an invalid id is provided.
* @returns {{ x: number, y: number }} Returns X, Y canvas position of the node with given id.
*/getPosition(id){if(id==undefined){throw new TypeError("No id was specified for getPosition method.");}else if(this.body.nodes[id]==undefined){throw new ReferenceError(`NodeId provided for getPosition does not exist. Provided: ${id}`);}else {return {x:Math.round(this.body.nodes[id].x),y:Math.round(this.body.nodes[id].y)};}}/**
* Load the XY positions of the nodes into the dataset.
*/storePositions(){// todo: add support for clusters and hierarchical.
const dataArray=[];const dataset=this.body.data.nodes.getDataSet();for(const dsNode of dataset.get()){const id=dsNode.id;const bodyNode=this.body.nodes[id];const x=Math.round(bodyNode.x);const y=Math.round(bodyNode.y);if(dsNode.x!==x||dsNode.y!==y){dataArray.push({id,x,y});}}dataset.update(dataArray);}/**
* get the bounding box of a node.
*
* @param {Node.id} nodeId
* @returns {j|*}
*/getBoundingBox(nodeId){if(this.body.nodes[nodeId]!==undefined){return this.body.nodes[nodeId].shape.boundingBox;}}/**
* Get the Ids of nodes connected to this node.
*
* @param {Node.id} nodeId
* @param {'to'|'from'|undefined} direction values 'from' and 'to' select respectively parent and child nodes only.
* Any other value returns both parent and child nodes.
* @returns {Array}
*/getConnectedNodes(nodeId,direction){const nodeList=[];if(this.body.nodes[nodeId]!==undefined){const node=this.body.nodes[nodeId];const nodeObj={};// used to quickly check if node already exists
for(let i=0;i<node.edges.length;i++){const edge=node.edges[i];if(direction!=="to"&&edge.toId==node.id){// these are double equals since ids can be numeric or string
if(nodeObj[edge.fromId]===undefined){nodeList.push(edge.fromId);nodeObj[edge.fromId]=true;}}else if(direction!=="from"&&edge.fromId==node.id){// these are double equals since ids can be numeric or string
if(nodeObj[edge.toId]===undefined){nodeList.push(edge.toId);nodeObj[edge.toId]=true;}}}}return nodeList;}/**
* Get the ids of the edges connected to this node.
*
* @param {Node.id} nodeId
* @returns {*}
*/getConnectedEdges(nodeId){const edgeList=[];if(this.body.nodes[nodeId]!==undefined){const node=this.body.nodes[nodeId];for(let i=0;i<node.edges.length;i++){edgeList.push(node.edges[i].id);}}else {console.error("NodeId provided for getConnectedEdges does not exist. Provided: ",nodeId);}return edgeList;}/**
* Move a node.
*
* @param {Node.id} nodeId
* @param {number} x
* @param {number} y
*/moveNode(nodeId,x,y){if(this.body.nodes[nodeId]!==undefined){this.body.nodes[nodeId].x=Number(x);this.body.nodes[nodeId].y=Number(y);setTimeout(()=>{this.body.emitter.emit("startSimulation");},0);}else {console.error("Node id supplied to moveNode does not exist. Provided: ",nodeId);}}}/**
* ============================================================================
* Location of all the endpoint drawing routines.
*
* Every endpoint has its own drawing routine, which contains an endpoint definition.
*
* The endpoint definitions must have the following properies:
*
* - (0,0) is the connection point to the node it attaches to
* - The endpoints are orientated to the positive x-direction
* - The length of the endpoint is at most 1
*
* As long as the endpoint classes remain simple and not too numerous, they will
* be contained within this module.
* All classes here except `EndPoints` should be considered as private to this module.
*
* -----------------------------------------------------------------------------
* ### Further Actions
*
* After adding a new endpoint here, you also need to do the following things:
*
* - Add the new endpoint name to `network/options.js` in array `endPoints`.
* - Add the new endpoint name to the documentation.
* Scan for 'arrows.to.type` and add it to the description.
* - Add the endpoint to the examples. At the very least, add it to example
* `edgeStyles/arrowTypes`.
* =============================================================================
*/ /**
* Common methods for endpoints
*
* @class
*/class EndPoint{/**
* Apply transformation on points for display.
*
* The following is done:
* - rotate by the specified angle
* - multiply the (normalized) coordinates by the passed length
* - offset by the target coordinates
*
* @param points - The point(s) to be transformed.
* @param arrowData - The data determining the result of the transformation.
*/static transform(points,arrowData){if(!Array.isArray(points)){points=[points];}const x=arrowData.point.x;const y=arrowData.point.y;const angle=arrowData.angle;const length=arrowData.length;for(let i=0;i<points.length;++i){const p=points[i];const xt=p.x*Math.cos(angle)-p.y*Math.sin(angle);const yt=p.x*Math.sin(angle)+p.y*Math.cos(angle);p.x=x+length*xt;p.y=y+length*yt;}}/**
* Draw a closed path using the given real coordinates.
*
* @param ctx - The path will be rendered into this context.
* @param points - The points of the path.
*/static drawPath(ctx,points){ctx.beginPath();ctx.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;++i){ctx.lineTo(points[i].x,points[i].y);}ctx.closePath();}}/**
* Drawing methods for the arrow endpoint.
*/let Image$1=class Image extends EndPoint{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns False as there is no way to fill an image.
*/static draw(ctx,arrowData){if(arrowData.image){ctx.save();ctx.translate(arrowData.point.x,arrowData.point.y);ctx.rotate(Math.PI/2+arrowData.angle);const width=arrowData.imageWidth!=null?arrowData.imageWidth:arrowData.image.width;const height=arrowData.imageHeight!=null?arrowData.imageHeight:arrowData.image.height;arrowData.image.drawImageAtPosition(ctx,1,// scale
-width/2,// x
0,// y
width,height);ctx.restore();}return false;}};/**
* Drawing methods for the arrow endpoint.
*/class Arrow extends EndPoint{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:0,y:0},{x:-1,y:0.3},{x:-0.9,y:0},{x:-1,y:-0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the crow endpoint.
*/class Crow{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:-1,y:0},{x:0,y:0.3},{x:-0.4,y:0},{x:0,y:-0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the curve endpoint.
*/class Curve{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const point={x:-0.4,y:0};EndPoint.transform(point,arrowData);// Update endpoint style for drawing transparent arc.
ctx.strokeStyle=ctx.fillStyle;ctx.fillStyle="rgba(0, 0, 0, 0)";// Define curve endpoint as semicircle.
const pi=Math.PI;const startAngle=arrowData.angle-pi/2;const endAngle=arrowData.angle+pi/2;ctx.beginPath();ctx.arc(point.x,point.y,arrowData.length*0.4,startAngle,endAngle,false);ctx.stroke();return true;}}/**
* Drawing methods for the inverted curve endpoint.
*/class InvertedCurve{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const point={x:-0.3,y:0};EndPoint.transform(point,arrowData);// Update endpoint style for drawing transparent arc.
ctx.strokeStyle=ctx.fillStyle;ctx.fillStyle="rgba(0, 0, 0, 0)";// Define inverted curve endpoint as semicircle.
const pi=Math.PI;const startAngle=arrowData.angle+pi/2;const endAngle=arrowData.angle+3*pi/2;ctx.beginPath();ctx.arc(point.x,point.y,arrowData.length*0.4,startAngle,endAngle,false);ctx.stroke();return true;}}/**
* Drawing methods for the trinagle endpoint.
*/class Triangle{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:0.02,y:0},{x:-1,y:0.3},{x:-1,y:-0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the inverted trinagle endpoint.
*/class InvertedTriangle{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:0,y:0.3},{x:0,y:-0.3},{x:-1,y:0}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the circle endpoint.
*/class Circle{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){const point={x:-0.4,y:0};EndPoint.transform(point,arrowData);drawCircle(ctx,point.x,point.y,arrowData.length*0.4);return true;}}/**
* Drawing methods for the bar endpoint.
*/class Bar{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){/*
var points = [
{x:0, y:0.5},
{x:0, y:-0.5}
];
EndPoint.transform(points, arrowData);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineTo(points[1].x, points[1].y);
ctx.stroke();
*/const points=[{x:0,y:0.5},{x:0,y:-0.5},{x:-0.15,y:-0.5},{x:-0.15,y:0.5}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the box endpoint.
*/class Box{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){const points=[{x:0,y:0.3},{x:0,y:-0.3},{x:-0.6,y:-0.3},{x:-0.6,y:0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the diamond endpoint.
*/class Diamond{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){const points=[{x:0,y:0},{x:-0.5,y:-0.3},{x:-1,y:0},{x:-0.5,y:0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the vee endpoint.
*/class Vee{/**
* Draw this shape at the end of a line.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True because ctx.fill() can be used to fill the arrow.
*/static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:-1,y:0.3},{x:-0.5,y:0},{x:-1,y:-0.3},{x:0,y:0}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
* Drawing methods for the endpoints.
*/class EndPoints{/**
* Draw an endpoint.
*
* @param ctx - The shape will be rendered into this context.
* @param arrowData - The data determining the shape.
* @returns True if ctx.fill() can be used to fill the arrow, false otherwise.
*/static draw(ctx,arrowData){let type;if(arrowData.type){type=arrowData.type.toLowerCase();}switch(type){case"image":return Image$1.draw(ctx,arrowData);case"circle":return Circle.draw(ctx,arrowData);case"box":return Box.draw(ctx,arrowData);case"crow":return Crow.draw(ctx,arrowData);case"curve":return Curve.draw(ctx,arrowData);case"diamond":return Diamond.draw(ctx,arrowData);case"inv_curve":return InvertedCurve.draw(ctx,arrowData);case"triangle":return Triangle.draw(ctx,arrowData);case"inv_triangle":return InvertedTriangle.draw(ctx,arrowData);case"bar":return Bar.draw(ctx,arrowData);case"vee":return Vee.draw(ctx,arrowData);case"arrow":// fall-through
default:return Arrow.draw(ctx,arrowData);}}}/**
* The Base Class for all edges.
*/class EdgeBase{/**
* Create a new instance.
*
* @param options - The options object of given edge.
* @param _body - The body of the network.
* @param _labelModule - Label module.
*/constructor(options,_body,_labelModule){this._body=_body;this._labelModule=_labelModule;this.color={};this.colorDirty=true;this.hoverWidth=1.5;this.selectionWidth=2;this.setOptions(options);this.fromPoint=this.from;this.toPoint=this.to;}/** @inheritDoc */connect(){this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];}/** @inheritDoc */cleanup(){return false;}/**
* Set new edge options.
*
* @param options - The new edge options object.
*/setOptions(options){this.options=options;this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];this.id=this.options.id;}/** @inheritDoc */drawLine(ctx,values,_selected,_hover,viaNode=this.getViaNode()){// set style
ctx.strokeStyle=this.getColor(ctx,values);ctx.lineWidth=values.width;if(values.dashes!==false){this._drawDashedLine(ctx,values,viaNode);}else {this._drawLine(ctx,values,viaNode);}}/**
* Draw a line with given style between two nodes through supplied node(s).
*
* @param ctx - The context that will be used for rendering.
* @param values - Formatting values like color, opacity or shadow.
* @param viaNode - Additional control point(s) for the edge.
* @param fromPoint - TODO: Seems ignored, remove?
* @param toPoint - TODO: Seems ignored, remove?
*/_drawLine(ctx,values,viaNode,fromPoint,toPoint){if(this.from!=this.to){// draw line
this._line(ctx,values,viaNode,fromPoint,toPoint);}else {const[x,y,radius]=this._getCircleData(ctx);this._circle(ctx,values,x,y,radius);}}/**
* Draw a dashed line with given style between two nodes through supplied node(s).
*
* @param ctx - The context that will be used for rendering.
* @param values - Formatting values like color, opacity or shadow.
* @param viaNode - Additional control point(s) for the edge.
* @param _fromPoint - Ignored (TODO: remove in the future).
* @param _toPoint - Ignored (TODO: remove in the future).
*/_drawDashedLine(ctx,values,viaNode,_fromPoint,_toPoint){ctx.lineCap="round";const pattern=Array.isArray(values.dashes)?values.dashes:[5,5];// only firefox and chrome support this method, else we use the legacy one.
if(ctx.setLineDash!==undefined){ctx.save();// set dash settings for chrome or firefox
ctx.setLineDash(pattern);ctx.lineDashOffset=0;// draw the line
if(this.from!=this.to){// draw line
this._line(ctx,values,viaNode);}else {const[x,y,radius]=this._getCircleData(ctx);this._circle(ctx,values,x,y,radius);}// restore the dash settings.
ctx.setLineDash([0]);ctx.lineDashOffset=0;ctx.restore();}else {// unsupporting smooth lines
if(this.from!=this.to){// draw line
drawDashedLine(ctx,this.from.x,this.from.y,this.to.x,this.to.y,pattern);}else {const[x,y,radius]=this._getCircleData(ctx);this._circle(ctx,values,x,y,radius);}// draw shadow if enabled
this.enableShadow(ctx,values);ctx.stroke();// disable shadows for other elements.
this.disableShadow(ctx,values);}}/**
* Find the intersection between the border of the node and the edge.
*
* @param node - The node (either from or to node of the edge).
* @param ctx - The context that will be used for rendering.
* @param options - Additional options.
* @returns Cartesian coordinates of the intersection between the border of the node and the edge.
*/findBorderPosition(node,ctx,options){if(this.from!=this.to){return this._findBorderPosition(node,ctx,options);}else {return this._findBorderPositionCircle(node,ctx,options);}}/** @inheritDoc */findBorderPositions(ctx){if(this.from!=this.to){return {from:this._findBorderPosition(this.from,ctx),to:this._findBorderPosition(this.to,ctx)};}else {const[x,y]=this._getCircleData(ctx).slice(0,2);return {from:this._findBorderPositionCircle(this.from,ctx,{x,y,low:0.25,high:0.6,direction:-1}),to:this._findBorderPositionCircle(this.from,ctx,{x,y,low:0.6,high:0.8,direction:1})};}}/**
* Compute the center point and radius of an edge connected to the same node at both ends.
*
* @param ctx - The context that will be used for rendering.
* @returns `[x, y, radius]`
*/_getCircleData(ctx){const radius=this.options.selfReference.size;if(ctx!==undefined){if(this.from.shape.width===undefined){this.from.shape.resize(ctx);}}// get circle coordinates
const coordinates=getSelfRefCoordinates(ctx,this.options.selfReference.angle,radius,this.from);return [coordinates.x,coordinates.y,radius];}/**
* Get a point on a circle.
*
* @param x - Center of the circle on the x axis.
* @param y - Center of the circle on the y axis.
* @param radius - Radius of the circle.
* @param position - Value between 0 (line start) and 1 (line end).
* @returns Cartesian coordinates of requested point on the circle.
*/_pointOnCircle(x,y,radius,position){const angle=position*2*Math.PI;return {x:x+radius*Math.cos(angle),y:y-radius*Math.sin(angle)};}/**
* Find the intersection between the border of the node and the edge.
*
* @remarks
* This function uses binary search to look for the point where the circle crosses the border of the node.
* @param nearNode - The node (either from or to node of the edge).
* @param ctx - The context that will be used for rendering.
* @param options - Additional options.
* @returns Cartesian coordinates of the intersection between the border of the node and the edge.
*/_findBorderPositionCircle(nearNode,ctx,options){const x=options.x;const y=options.y;let low=options.low;let high=options.high;const direction=options.direction;const maxIterations=10;const radius=this.options.selfReference.size;const threshold=0.05;let pos;let middle=(low+high)*0.5;let endPointOffset=0;if(this.options.arrowStrikethrough===true){if(direction===-1){endPointOffset=this.options.endPointOffset.from;}else if(direction===1){endPointOffset=this.options.endPointOffset.to;}}let iteration=0;do{middle=(low+high)*0.5;pos=this._pointOnCircle(x,y,radius,middle);const angle=Math.atan2(nearNode.y-pos.y,nearNode.x-pos.x);const distanceToBorder=nearNode.distanceToBorder(ctx,angle)+endPointOffset;const distanceToPoint=Math.sqrt(Math.pow(pos.x-nearNode.x,2)+Math.pow(pos.y-nearNode.y,2));const difference=distanceToBorder-distanceToPoint;if(Math.abs(difference)<threshold){break;// found
}else if(difference>0){// distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
if(direction>0){low=middle;}else {high=middle;}}else {if(direction>0){high=middle;}else {low=middle;}}++iteration;}while(low<=high&&iteration<maxIterations);return {...pos,t:middle};}/**
* Get the line width of the edge. Depends on width and whether one of the connected nodes is selected.
*
* @param selected - Determines wheter the line is selected.
* @param hover - Determines wheter the line is being hovered, only applies if selected is false.
* @returns The width of the line.
*/getLineWidth(selected,hover){if(selected===true){return Math.max(this.selectionWidth,0.3/this._body.view.scale);}else if(hover===true){return Math.max(this.hoverWidth,0.3/this._body.view.scale);}else {return Math.max(this.options.width,0.3/this._body.view.scale);}}/**
* Compute the color or gradient for given edge.
*
* @param ctx - The context that will be used for rendering.
* @param values - Formatting values like color, opacity or shadow.
* @param _selected - Ignored (TODO: remove in the future).
* @param _hover - Ignored (TODO: remove in the future).
* @returns Color string if single color is inherited or gradient if two.
*/getColor(ctx,values){if(values.inheritsColor!==false){// when this is a loop edge, just use the 'from' method
if(values.inheritsColor==="both"&&this.from.id!==this.to.id){const grd=ctx.createLinearGradient(this.from.x,this.from.y,this.to.x,this.to.y);let fromColor=this.from.options.color.highlight.border;let toColor=this.to.options.color.highlight.border;if(this.from.selected===false&&this.to.selected===false){fromColor=overrideOpacity(this.from.options.color.border,values.opacity);toColor=overrideOpacity(this.to.options.color.border,values.opacity);}else if(this.from.selected===true&&this.to.selected===false){toColor=this.to.options.color.border;}else if(this.from.selected===false&&this.to.selected===true){fromColor=this.from.options.color.border;}grd.addColorStop(0,fromColor);grd.addColorStop(1,toColor);// -------------------- this returns -------------------- //
return grd;}if(values.inheritsColor==="to"){return overrideOpacity(this.to.options.color.border,values.opacity);}else {// "from"
return overrideOpacity(this.from.options.color.border,values.opacity);}}else {return overrideOpacity(values.color,values.opacity);}}/**
* Draw a line from a node to itself, a circle.
*
* @param ctx - The context that will be used for rendering.
* @param values - Formatting values like color, opacity or shadow.
* @param x - Center of the circle on the x axis.
* @param y - Center of the circle on the y axis.
* @param radius - Radius of the circle.
*/_circle(ctx,values,x,y,radius){// draw shadow if enabled
this.enableShadow(ctx,values);//full circle
let angleFrom=0;let angleTo=Math.PI*2;if(!this.options.selfReference.renderBehindTheNode){//render only parts which are not overlaping with parent node
//need to find x,y of from point and x,y to point
//calculating radians
const low=this.options.selfReference.angle;const high=this.options.selfReference.angle+Math.PI;const pointTFrom=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:-1});const pointTTo=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:1});angleFrom=Math.atan2(pointTFrom.y-y,pointTFrom.x-x);angleTo=Math.atan2(pointTTo.y-y,pointTTo.x-x);}// draw a circle
ctx.beginPath();ctx.arc(x,y,radius,angleFrom,angleTo,false);ctx.stroke();// disable shadows for other elements.
this.disableShadow(ctx,values);}/**
* @inheritDoc
* @remarks
* http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
*/getDistanceToEdge(x1,y1,x2,y2,x3,y3){if(this.from!=this.to){return this._getDistanceToEdge(x1,y1,x2,y2,x3,y3);}else {const[x,y,radius]=this._getCircleData(undefined);const dx=x-x3;const dy=y-y3;return Math.abs(Math.sqrt(dx*dx+dy*dy)-radius);}}/**
* Calculate the distance between a point (x3, y3) and a line segment from (x1, y1) to (x2, y2).
*
* @param x1 - First end of the line segment on the x axis.
* @param y1 - First end of the line segment on the y axis.
* @param x2 - Second end of the line segment on the x axis.
* @param y2 - Second end of the line segment on the y axis.
* @param x3 - Position of the point on the x axis.
* @param y3 - Position of the point on the y axis.
* @returns The distance between the line segment and the point.
*/_getDistanceToLine(x1,y1,x2,y2,x3,y3){const px=x2-x1;const py=y2-y1;const something=px*px+py*py;let u=((x3-x1)*px+(y3-y1)*py)/something;if(u>1){u=1;}else if(u<0){u=0;}const x=x1+u*px;const y=y1+u*py;const dx=x-x3;const dy=y-y3;//# Note: If the actual distance does not matter,
//# if you only want to compare what this function
//# returns to other results of this function, you
//# can just return the squared distance instead
//# (i.e. remove the sqrt) to gain a little performance
return Math.sqrt(dx*dx+dy*dy);}/** @inheritDoc */getArrowData(ctx,position,viaNode,_selected,_hover,values){// set lets
let angle;let arrowPoint;let node1;let node2;let reversed;let scaleFactor;let type;const lineWidth=values.width;if(position==="from"){node1=this.from;node2=this.to;reversed=values.fromArrowScale<0;scaleFactor=Math.abs(values.fromArrowScale);type=values.fromArrowType;}else if(position==="to"){node1=this.to;node2=this.from;reversed=values.toArrowScale<0;scaleFactor=Math.abs(values.toArrowScale);type=values.toArrowType;}else {node1=this.to;node2=this.from;reversed=values.middleArrowScale<0;scaleFactor=Math.abs(values.middleArrowScale);type=values.middleArrowType;}const length=15*scaleFactor+3*lineWidth;// 3* lineWidth is the width of the edge.
// if not connected to itself
if(node1!=node2){const approximateEdgeLength=Math.hypot(node1.x-node2.x,node1.y-node2.y);const relativeLength=length/approximateEdgeLength;if(position!=="middle"){// draw arrow head
if(this.options.smooth.enabled===true){const pointT=this._findBorderPosition(node1,ctx,{via:viaNode});const guidePos=this.getPoint(pointT.t+relativeLength*(position==="from"?1:-1),viaNode);angle=Math.atan2(pointT.y-guidePos.y,pointT.x-guidePos.x);arrowPoint=pointT;}else {angle=Math.atan2(node1.y-node2.y,node1.x-node2.x);arrowPoint=this._findBorderPosition(node1,ctx);}}else {// Negative half length reverses arrow direction.
const halfLength=(reversed?-relativeLength:relativeLength)/2;const guidePos1=this.getPoint(0.5+halfLength,viaNode);const guidePos2=this.getPoint(0.5-halfLength,viaNode);angle=Math.atan2(guidePos1.y-guidePos2.y,guidePos1.x-guidePos2.x);arrowPoint=this.getPoint(0.5,viaNode);}}else {// draw circle
const[x,y,radius]=this._getCircleData(ctx);if(position==="from"){const low=this.options.selfReference.angle;const high=this.options.selfReference.angle+Math.PI;const pointT=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:-1});angle=pointT.t*-2*Math.PI+1.5*Math.PI+0.1*Math.PI;arrowPoint=pointT;}else if(position==="to"){const low=this.options.selfReference.angle;const high=this.options.selfReference.angle+Math.PI;const pointT=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:1});angle=pointT.t*-2*Math.PI+1.5*Math.PI-1.1*Math.PI;arrowPoint=pointT;}else {const pos=this.options.selfReference.angle/(2*Math.PI);arrowPoint=this._pointOnCircle(x,y,radius,pos);angle=pos*-2*Math.PI+1.5*Math.PI+0.1*Math.PI;}}const xi=arrowPoint.x-length*0.9*Math.cos(angle);const yi=arrowPoint.y-length*0.9*Math.sin(angle);const arrowCore={x:xi,y:yi};return {point:arrowPoint,core:arrowCore,angle:angle,length:length,type:type};}/** @inheritDoc */drawArrowHead(ctx,values,_selected,_hover,arrowData){// set style
ctx.strokeStyle=this.getColor(ctx,values);ctx.fillStyle=ctx.strokeStyle;ctx.lineWidth=values.width;const canFill=EndPoints.draw(ctx,arrowData);if(canFill){// draw shadow if enabled
this.enableShadow(ctx,values);ctx.fill();// disable shadows for other elements.
this.disableShadow(ctx,values);}}/**
* Set the shadow formatting values in the context if enabled, do nothing otherwise.
*
* @param ctx - The context that will be used for rendering.
* @param values - Formatting values for the shadow.
*/enableShadow(ctx,values){if(values.shadow===true){ctx.shadowColor=values.shadowColor;ctx.shadowBlur=values.shadowSize;ctx.shadowOffsetX=values.shadowX;ctx.shadowOffsetY=values.shadowY;}}/**
* Reset the shadow formatting values in the context if enabled, do nothing otherwise.
*
* @param ctx - The context that will be used for rendering.
* @param values - Formatting values for the shadow.
*/disableShadow(ctx,values){if(values.shadow===true){ctx.shadowColor="rgba(0,0,0,0)";ctx.shadowBlur=0;ctx.shadowOffsetX=0;ctx.shadowOffsetY=0;}}/**
* Render the background according to the formatting values.
*
* @param ctx - The context that will be used for rendering.
* @param values - Formatting values for the background.
*/drawBackground(ctx,values){if(values.background!==false){// save original line attrs
const origCtxAttr={strokeStyle:ctx.strokeStyle,lineWidth:ctx.lineWidth,dashes:ctx.dashes};ctx.strokeStyle=values.backgroundColor;ctx.lineWidth=values.backgroundSize;this.setStrokeDashed(ctx,values.backgroundDashes);ctx.stroke();// restore original line attrs
ctx.strokeStyle=origCtxAttr.strokeStyle;ctx.lineWidth=origCtxAttr.lineWidth;ctx.dashes=origCtxAttr.dashes;this.setStrokeDashed(ctx,values.dashes);}}/**
* Set the line dash pattern if supported. Logs a warning to the console if it isn't supported.
*
* @param ctx - The context that will be used for rendering.
* @param dashes - The pattern [line, space, line…], true for default dashed line or false for normal line.
*/setStrokeDashed(ctx,dashes){if(dashes!==false){if(ctx.setLineDash!==undefined){const pattern=Array.isArray(dashes)?dashes:[5,5];ctx.setLineDash(pattern);}else {console.warn("setLineDash is not supported in this browser. The dashed stroke cannot be used.");}}else {if(ctx.setLineDash!==undefined){ctx.setLineDash([]);}else {console.warn("setLineDash is not supported in this browser. The dashed stroke cannot be used.");}}}}/**
* The Base Class for all Bezier edges.
* Bezier curves are used to model smooth gradual curves in paths between nodes.
*/class BezierEdgeBase extends EdgeBase{/**
* Create a new instance.
*
* @param options - The options object of given edge.
* @param body - The body of the network.
* @param labelModule - Label module.
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
* Find the intersection between the border of the node and the edge.
*
* @remarks
* This function uses binary search to look for the point where the bezier curve crosses the border of the node.
* @param nearNode - The node (either from or to node of the edge).
* @param ctx - The context that will be used for rendering.
* @param viaNode - Additional node(s) the edge passes through.
* @returns Cartesian coordinates of the intersection between the border of the node and the edge.
*/_findBorderPositionBezier(nearNode,ctx,viaNode=this._getViaCoordinates()){const maxIterations=10;const threshold=0.2;let from=false;let high=1;let low=0;let node=this.to;let pos;let middle;let endPointOffset=this.options.endPointOffset?this.options.endPointOffset.to:0;if(nearNode.id===this.from.id){node=this.from;from=true;endPointOffset=this.options.endPointOffset?this.options.endPointOffset.from:0;}if(this.options.arrowStrikethrough===false){endPointOffset=0;}let iteration=0;do{middle=(low+high)*0.5;pos=this.getPoint(middle,viaNode);const angle=Math.atan2(node.y-pos.y,node.x-pos.x);const distanceToBorder=node.distanceToBorder(ctx,angle)+endPointOffset;const distanceToPoint=Math.sqrt(Math.pow(pos.x-node.x,2)+Math.pow(pos.y-node.y,2));const difference=distanceToBorder-distanceToPoint;if(Math.abs(difference)<threshold){break;// found
}else if(difference<0){// distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
if(from===false){low=middle;}else {high=middle;}}else {if(from===false){high=middle;}else {low=middle;}}++iteration;}while(low<=high&&iteration<maxIterations);return {...pos,t:middle};}/**
* Calculate the distance between a point (x3,y3) and a line segment from (x1,y1) to (x2,y2).
*
* @remarks
* http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
* @param x1 - First end of the line segment on the x axis.
* @param y1 - First end of the line segment on the y axis.
* @param x2 - Second end of the line segment on the x axis.
* @param y2 - Second end of the line segment on the y axis.
* @param x3 - Position of the point on the x axis.
* @param y3 - Position of the point on the y axis.
* @param via - The control point for the edge.
* @returns The distance between the line segment and the point.
*/_getDistanceToBezierEdge(x1,y1,x2,y2,x3,y3,via){// x3,y3 is the point
let minDistance=1e9;let distance;let i,t,x,y;let lastX=x1;let lastY=y1;for(i=1;i<10;i++){t=0.1*i;x=Math.pow(1-t,2)*x1+2*t*(1-t)*via.x+Math.pow(t,2)*x2;y=Math.pow(1-t,2)*y1+2*t*(1-t)*via.y+Math.pow(t,2)*y2;if(i>0){distance=this._getDistanceToLine(lastX,lastY,x,y,x3,y3);minDistance=distance<minDistance?distance:minDistance;}lastX=x;lastY=y;}return minDistance;}/**
* Render a bezier curve between two nodes.
*
* @remarks
* The method accepts zero, one or two control points.
* Passing zero control points just draws a straight line.
* @param ctx - The context that will be used for rendering.
* @param values - Style options for edge drawing.
* @param viaNode1 - First control point for curve drawing.
* @param viaNode2 - Second control point for curve drawing.
*/_bezierCurve(ctx,values,viaNode1,viaNode2){ctx.beginPath();ctx.moveTo(this.fromPoint.x,this.fromPoint.y);if(viaNode1!=null&&viaNode1.x!=null){if(viaNode2!=null&&viaNode2.x!=null){ctx.bezierCurveTo(viaNode1.x,viaNode1.y,viaNode2.x,viaNode2.y,this.toPoint.x,this.toPoint.y);}else {ctx.quadraticCurveTo(viaNode1.x,viaNode1.y,this.toPoint.x,this.toPoint.y);}}else {// fallback to normal straight edge
ctx.lineTo(this.toPoint.x,this.toPoint.y);}// draw a background
this.drawBackground(ctx,values);// draw shadow if enabled
this.enableShadow(ctx,values);ctx.stroke();this.disableShadow(ctx,values);}/** @inheritDoc */getViaNode(){return this._getViaCoordinates();}}/**
* A Dynamic Bezier Edge. Bezier curves are used to model smooth gradual
* curves in paths between nodes. The Dynamic piece refers to how the curve
* reacts to physics changes.
*
* @augments BezierEdgeBase
*/class BezierEdgeDynamic extends BezierEdgeBase{/**
* Create a new instance.
*
* @param options - The options object of given edge.
* @param body - The body of the network.
* @param labelModule - Label module.
*/constructor(options,body,labelModule){//this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked.
super(options,body,labelModule);// --> this calls the setOptions below
this.via=this.via;// constructor → super → super → setOptions → setupSupportNode
this._boundFunction=()=>{this.positionBezierNode();};this._body.emitter.on("_repositionBezierNodes",this._boundFunction);}/** @inheritDoc */setOptions(options){super.setOptions(options);// check if the physics has changed.
let physicsChange=false;if(this.options.physics!==options.physics){physicsChange=true;}// set the options and the to and from nodes
this.options=options;this.id=this.options.id;this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];// setup the support node and connect
this.setupSupportNode();this.connect();// when we change the physics state of the edge, we reposition the support node.
if(physicsChange===true){this.via.setOptions({physics:this.options.physics});this.positionBezierNode();}}/** @inheritDoc */connect(){this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];if(this.from===undefined||this.to===undefined||this.options.physics===false){this.via.setOptions({physics:false});}else {// fix weird behaviour where a self referencing node has physics enabled
if(this.from.id===this.to.id){this.via.setOptions({physics:false});}else {this.via.setOptions({physics:true});}}}/** @inheritDoc */cleanup(){this._body.emitter.off("_repositionBezierNodes",this._boundFunction);if(this.via!==undefined){delete this._body.nodes[this.via.id];this.via=undefined;return true;}return false;}/**
* Create and add a support node if not already present.
*
* @remarks
* Bezier curves require an anchor point to calculate the smooth flow.
* These points are nodes.
* These nodes are invisible but are used for the force calculation.
*
* The changed data is not called, if needed, it is returned by the main edge constructor.
*/setupSupportNode(){if(this.via===undefined){const nodeId="edgeId:"+this.id;const node=this._body.functions.createNode({id:nodeId,shape:"circle",physics:true,hidden:true});this._body.nodes[nodeId]=node;this.via=node;this.via.parentEdgeId=this.id;this.positionBezierNode();}}/**
* Position bezier node.
*/positionBezierNode(){if(this.via!==undefined&&this.from!==undefined&&this.to!==undefined){this.via.x=0.5*(this.from.x+this.to.x);this.via.y=0.5*(this.from.y+this.to.y);}else if(this.via!==undefined){this.via.x=0;this.via.y=0;}}/** @inheritDoc */_line(ctx,values,viaNode){this._bezierCurve(ctx,values,viaNode);}/** @inheritDoc */_getViaCoordinates(){return this.via;}/** @inheritDoc */getViaNode(){return this.via;}/** @inheritDoc */getPoint(position,viaNode=this.via){if(this.from===this.to){const[cx,cy,cr]=this._getCircleData();const a=2*Math.PI*(1-position);return {x:cx+cr*Math.sin(a),y:cy+cr-cr*(1-Math.cos(a))};}else {return {x:Math.pow(1-position,2)*this.fromPoint.x+2*position*(1-position)*viaNode.x+Math.pow(position,2)*this.toPoint.x,y:Math.pow(1-position,2)*this.fromPoint.y+2*position*(1-position)*viaNode.y+Math.pow(position,2)*this.toPoint.y};}}/** @inheritDoc */_findBorderPosition(nearNode,ctx){return this._findBorderPositionBezier(nearNode,ctx,this.via);}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3){// x3,y3 is the point
return this._getDistanceToBezierEdge(x1,y1,x2,y2,x3,y3,this.via);}}/**
* A Static Bezier Edge. Bezier curves are used to model smooth gradual curves in paths between nodes.
*/class BezierEdgeStatic extends BezierEdgeBase{/**
* Create a new instance.
*
* @param options - The options object of given edge.
* @param body - The body of the network.
* @param labelModule - Label module.
*/constructor(options,body,labelModule){super(options,body,labelModule);}/** @inheritDoc */_line(ctx,values,viaNode){this._bezierCurve(ctx,values,viaNode);}/** @inheritDoc */getViaNode(){return this._getViaCoordinates();}/**
* Compute the coordinates of the via node.
*
* @remarks
* We do not use the to and fromPoints here to make the via nodes the same as edges without arrows.
* @returns Cartesian coordinates of the via node.
*/_getViaCoordinates(){// Assumption: x/y coordinates in from/to always defined
const factor=this.options.smooth.roundness;const type=this.options.smooth.type;let dx=Math.abs(this.from.x-this.to.x);let dy=Math.abs(this.from.y-this.to.y);if(type==="discrete"||type==="diagonalCross"){let stepX;let stepY;if(dx<=dy){stepX=stepY=factor*dy;}else {stepX=stepY=factor*dx;}if(this.from.x>this.to.x){stepX=-stepX;}if(this.from.y>=this.to.y){stepY=-stepY;}let xVia=this.from.x+stepX;let yVia=this.from.y+stepY;if(type==="discrete"){if(dx<=dy){xVia=dx<factor*dy?this.from.x:xVia;}else {yVia=dy<factor*dx?this.from.y:yVia;}}return {x:xVia,y:yVia};}else if(type==="straightCross"){let stepX=(1-factor)*dx;let stepY=(1-factor)*dy;if(dx<=dy){// up - down
stepX=0;if(this.from.y<this.to.y){stepY=-stepY;}}else {// left - right
if(this.from.x<this.to.x){stepX=-stepX;}stepY=0;}return {x:this.to.x+stepX,y:this.to.y+stepY};}else if(type==="horizontal"){let stepX=(1-factor)*dx;if(this.from.x<this.to.x){stepX=-stepX;}return {x:this.to.x+stepX,y:this.from.y};}else if(type==="vertical"){let stepY=(1-factor)*dy;if(this.from.y<this.to.y){stepY=-stepY;}return {x:this.from.x,y:this.to.y+stepY};}else if(type==="curvedCW"){dx=this.to.x-this.from.x;dy=this.from.y-this.to.y;const radius=Math.sqrt(dx*dx+dy*dy);const pi=Math.PI;const originalAngle=Math.atan2(dy,dx);const myAngle=(originalAngle+(factor*0.5+0.5)*pi)%(2*pi);return {x:this.from.x+(factor*0.5+0.5)*radius*Math.sin(myAngle),y:this.from.y+(factor*0.5+0.5)*radius*Math.cos(myAngle)};}else if(type==="curvedCCW"){dx=this.to.x-this.from.x;dy=this.from.y-this.to.y;const radius=Math.sqrt(dx*dx+dy*dy);const pi=Math.PI;const originalAngle=Math.atan2(dy,dx);const myAngle=(originalAngle+(-factor*0.5+0.5)*pi)%(2*pi);return {x:this.from.x+(factor*0.5+0.5)*radius*Math.sin(myAngle),y:this.from.y+(factor*0.5+0.5)*radius*Math.cos(myAngle)};}else {// continuous
let stepX;let stepY;if(dx<=dy){stepX=stepY=factor*dy;}else {stepX=stepY=factor*dx;}if(this.from.x>this.to.x){stepX=-stepX;}if(this.from.y>=this.to.y){stepY=-stepY;}let xVia=this.from.x+stepX;let yVia=this.from.y+stepY;if(dx<=dy){if(this.from.x<=this.to.x){xVia=this.to.x<xVia?this.to.x:xVia;}else {xVia=this.to.x>xVia?this.to.x:xVia;}}else {if(this.from.y>=this.to.y){yVia=this.to.y>yVia?this.to.y:yVia;}else {yVia=this.to.y<yVia?this.to.y:yVia;}}return {x:xVia,y:yVia};}}/** @inheritDoc */_findBorderPosition(nearNode,ctx,options={}){return this._findBorderPositionBezier(nearNode,ctx,options.via);}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3,viaNode=this._getViaCoordinates()){// x3,y3 is the point
return this._getDistanceToBezierEdge(x1,y1,x2,y2,x3,y3,viaNode);}/** @inheritDoc */getPoint(position,viaNode=this._getViaCoordinates()){const t=position;const x=Math.pow(1-t,2)*this.fromPoint.x+2*t*(1-t)*viaNode.x+Math.pow(t,2)*this.toPoint.x;const y=Math.pow(1-t,2)*this.fromPoint.y+2*t*(1-t)*viaNode.y+Math.pow(t,2)*this.toPoint.y;return {x:x,y:y};}}/**
* A Base Class for all Cubic Bezier Edges. Bezier curves are used to model
* smooth gradual curves in paths between nodes.
*
* @augments BezierEdgeBase
*/class CubicBezierEdgeBase extends BezierEdgeBase{/**
* Create a new instance.
*
* @param options - The options object of given edge.
* @param body - The body of the network.
* @param labelModule - Label module.
*/constructor(options,body,labelModule){super(options,body,labelModule);}/**
* Calculate the distance between a point (x3,y3) and a line segment from (x1,y1) to (x2,y2).
*
* @remarks
* http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
* https://en.wikipedia.org/wiki/B%C3%A9zier_curve
* @param x1 - First end of the line segment on the x axis.
* @param y1 - First end of the line segment on the y axis.
* @param x2 - Second end of the line segment on the x axis.
* @param y2 - Second end of the line segment on the y axis.
* @param x3 - Position of the point on the x axis.
* @param y3 - Position of the point on the y axis.
* @param via1 - The first point this edge passes through.
* @param via2 - The second point this edge passes through.
* @returns The distance between the line segment and the point.
*/_getDistanceToBezierEdge2(x1,y1,x2,y2,x3,y3,via1,via2){// x3,y3 is the point
let minDistance=1e9;let lastX=x1;let lastY=y1;const vec=[0,0,0,0];for(let i=1;i<10;i++){const t=0.1*i;vec[0]=Math.pow(1-t,3);vec[1]=3*t*Math.pow(1-t,2);vec[2]=3*Math.pow(t,2)*(1-t);vec[3]=Math.pow(t,3);const x=vec[0]*x1+vec[1]*via1.x+vec[2]*via2.x+vec[3]*x2;const y=vec[0]*y1+vec[1]*via1.y+vec[2]*via2.y+vec[3]*y2;if(i>0){const distance=this._getDistanceToLine(lastX,lastY,x,y,x3,y3);minDistance=distance<minDistance?distance:minDistance;}lastX=x;lastY=y;}return minDistance;}}/**
* A Cubic Bezier Edge. Bezier curves are used to model smooth gradual curves in paths between nodes.
*/class CubicBezierEdge extends CubicBezierEdgeBase{/**
* Create a new instance.
*
* @param options - The options object of given edge.
* @param body - The body of the network.
* @param labelModule - Label module.
*/constructor(options,body,labelModule){super(options,body,labelModule);}/** @inheritDoc */_line(ctx,values,viaNodes){// get the coordinates of the support points.
const via1=viaNodes[0];const via2=viaNodes[1];this._bezierCurve(ctx,values,via1,via2);}/**
* Compute the additional points the edge passes through.
*
* @returns Cartesian coordinates of the points the edge passes through.
*/_getViaCoordinates(){const dx=this.from.x-this.to.x;const dy=this.from.y-this.to.y;let x1;let y1;let x2;let y2;const roundness=this.options.smooth.roundness;// horizontal if x > y or if direction is forced or if direction is horizontal
if((Math.abs(dx)>Math.abs(dy)||this.options.smooth.forceDirection===true||this.options.smooth.forceDirection==="horizontal")&&this.options.smooth.forceDirection!=="vertical"){y1=this.from.y;y2=this.to.y;x1=this.from.x-roundness*dx;x2=this.to.x+roundness*dx;}else {y1=this.from.y-roundness*dy;y2=this.to.y+roundness*dy;x1=this.from.x;x2=this.to.x;}return [{x:x1,y:y1},{x:x2,y:y2}];}/** @inheritDoc */getViaNode(){return this._getViaCoordinates();}/** @inheritDoc */_findBorderPosition(nearNode,ctx){return this._findBorderPositionBezier(nearNode,ctx);}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3,[via1,via2]=this._getViaCoordinates()){// x3,y3 is the point
return this._getDistanceToBezierEdge2(x1,y1,x2,y2,x3,y3,via1,via2);}/** @inheritDoc */getPoint(position,[via1,via2]=this._getViaCoordinates()){const t=position;const vec=[Math.pow(1-t,3),3*t*Math.pow(1-t,2),3*Math.pow(t,2)*(1-t),Math.pow(t,3)];const x=vec[0]*this.fromPoint.x+vec[1]*via1.x+vec[2]*via2.x+vec[3]*this.toPoint.x;const y=vec[0]*this.fromPoint.y+vec[1]*via1.y+vec[2]*via2.y+vec[3]*this.toPoint.y;return {x:x,y:y};}}/**
* A Straight Edge.
*/class StraightEdge extends EdgeBase{/**
* Create a new instance.
*
* @param options - The options object of given edge.
* @param body - The body of the network.
* @param labelModule - Label module.
*/constructor(options,body,labelModule){super(options,body,labelModule);}/** @inheritDoc */_line(ctx,values){// draw a straight line
ctx.beginPath();ctx.moveTo(this.fromPoint.x,this.fromPoint.y);ctx.lineTo(this.toPoint.x,this.toPoint.y);// draw shadow if enabled
this.enableShadow(ctx,values);ctx.stroke();this.disableShadow(ctx,values);}/** @inheritDoc */getViaNode(){return undefined;}/** @inheritDoc */getPoint(position){return {x:(1-position)*this.fromPoint.x+position*this.toPoint.x,y:(1-position)*this.fromPoint.y+position*this.toPoint.y};}/** @inheritDoc */_findBorderPosition(nearNode,ctx){let node1=this.to;let node2=this.from;if(nearNode.id===this.from.id){node1=this.from;node2=this.to;}const angle=Math.atan2(node1.y-node2.y,node1.x-node2.x);const dx=node1.x-node2.x;const dy=node1.y-node2.y;const edgeSegmentLength=Math.sqrt(dx*dx+dy*dy);const toBorderDist=nearNode.distanceToBorder(ctx,angle);const toBorderPoint=(edgeSegmentLength-toBorderDist)/edgeSegmentLength;return {x:(1-toBorderPoint)*node2.x+toBorderPoint*node1.x,y:(1-toBorderPoint)*node2.y+toBorderPoint*node1.y,t:0};}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3){// x3,y3 is the point
return this._getDistanceToLine(x1,y1,x2,y2,x3,y3);}}/**
* An edge connects two nodes and has a specific direction.
*/class Edge{/**
* @param {object} options values specific to this edge, must contain at least 'from' and 'to'
* @param {object} body shared state from Network instance
* @param {Network.Images} imagelist A list with images. Only needed when the edge has image arrows.
* @param {object} globalOptions options from the EdgesHandler instance
* @param {object} defaultOptions default options from the EdgeHandler instance. Value and reference are constant
*/constructor(options,body,imagelist,globalOptions,defaultOptions){if(body===undefined){throw new Error("No body provided");}// Since globalOptions is constant in values as well as reference,
// Following needs to be done only once.
this.options=bridgeObject(globalOptions);this.globalOptions=globalOptions;this.defaultOptions=defaultOptions;this.body=body;this.imagelist=imagelist;// initialize variables
this.id=undefined;this.fromId=undefined;this.toId=undefined;this.selected=false;this.hover=false;this.labelDirty=true;this.baseWidth=this.options.width;this.baseFontSize=this.options.font.size;this.from=undefined;// a node
this.to=undefined;// a node
this.edgeType=undefined;this.connected=false;this.labelModule=new Label(this.body,this.options,true/* It's an edge label */);this.setOptions(options);}/**
* Set or overwrite options for the edge
*
* @param {object} options an object with options
* @returns {undefined|boolean} undefined if no options, true if layout affecting data changed, false otherwise.
*/setOptions(options){if(!options){return;}// Following options if changed affect the layout.
let affectsLayout=typeof options.physics!=="undefined"&&this.options.physics!==options.physics||typeof options.hidden!=="undefined"&&(this.options.hidden||false)!==(options.hidden||false)||typeof options.from!=="undefined"&&this.options.from!==options.from||typeof options.to!=="undefined"&&this.options.to!==options.to;Edge.parseOptions(this.options,options,true,this.globalOptions);if(options.id!==undefined){this.id=options.id;}if(options.from!==undefined){this.fromId=options.from;}if(options.to!==undefined){this.toId=options.to;}if(options.title!==undefined){this.title=options.title;}if(options.value!==undefined){options.value=parseFloat(options.value);}const pile=[options,this.options,this.defaultOptions];this.chooser=choosify("edge",pile);// update label Module
this.updateLabelModule(options);// Update edge type, this if changed affects the layout.
affectsLayout=this.updateEdgeType()||affectsLayout;// if anything has been updates, reset the selection width and the hover width
this._setInteractionWidths();// A node is connected when it has a from and to node that both exist in the network.body.nodes.
this.connect();return affectsLayout;}/**
*
* @param {object} parentOptions
* @param {object} newOptions
* @param {boolean} [allowDeletion=false]
* @param {object} [globalOptions={}]
* @param {boolean} [copyFromGlobals=false]
*/static parseOptions(parentOptions,newOptions,allowDeletion=false,globalOptions={},copyFromGlobals=false){const fields=["endPointOffset","arrowStrikethrough","id","from","hidden","hoverWidth","labelHighlightBold","length","line","opacity","physics","scaling","selectionWidth","selfReferenceSize","selfReference","to","title","value","width","font","chosen","widthConstraint"];// only deep extend the items in the field array. These do not have shorthand.
selectiveDeepExtend(fields,parentOptions,newOptions,allowDeletion);// Only use endPointOffset values (from and to) if it's valid values
if(newOptions.endPointOffset!==undefined&&newOptions.endPointOffset.from!==undefined){if(Number.isFinite(newOptions.endPointOffset.from)){parentOptions.endPointOffset.from=newOptions.endPointOffset.from;}else {parentOptions.endPointOffset.from=globalOptions.endPointOffset.from!==undefined?globalOptions.endPointOffset.from:0;console.error("endPointOffset.from is not a valid number");}}if(newOptions.endPointOffset!==undefined&&newOptions.endPointOffset.to!==undefined){if(Number.isFinite(newOptions.endPointOffset.to)){parentOptions.endPointOffset.to=newOptions.endPointOffset.to;}else {parentOptions.endPointOffset.to=globalOptions.endPointOffset.to!==undefined?globalOptions.endPointOffset.to:0;console.error("endPointOffset.to is not a valid number");}}// Only copy label if it's a legal value.
if(isValidLabel(newOptions.label)){parentOptions.label=newOptions.label;}else if(!isValidLabel(parentOptions.label)){parentOptions.label=undefined;}mergeOptions(parentOptions,newOptions,"smooth",globalOptions);mergeOptions(parentOptions,newOptions,"shadow",globalOptions);mergeOptions(parentOptions,newOptions,"background",globalOptions);if(newOptions.dashes!==undefined&&newOptions.dashes!==null){parentOptions.dashes=newOptions.dashes;}else if(allowDeletion===true&&newOptions.dashes===null){parentOptions.dashes=Object.create(globalOptions.dashes);// this sets the pointer of the option back to the global option.
}// set the scaling newOptions
if(newOptions.scaling!==undefined&&newOptions.scaling!==null){if(newOptions.scaling.min!==undefined){parentOptions.scaling.min=newOptions.scaling.min;}if(newOptions.scaling.max!==undefined){parentOptions.scaling.max=newOptions.scaling.max;}mergeOptions(parentOptions.scaling,newOptions.scaling,"label",globalOptions.scaling);}else if(allowDeletion===true&&newOptions.scaling===null){parentOptions.scaling=Object.create(globalOptions.scaling);// this sets the pointer of the option back to the global option.
}// handle multiple input cases for arrows
if(newOptions.arrows!==undefined&&newOptions.arrows!==null){if(typeof newOptions.arrows==="string"){const arrows=newOptions.arrows.toLowerCase();parentOptions.arrows.to.enabled=arrows.indexOf("to")!=-1;parentOptions.arrows.middle.enabled=arrows.indexOf("middle")!=-1;parentOptions.arrows.from.enabled=arrows.indexOf("from")!=-1;}else if(typeof newOptions.arrows==="object"){mergeOptions(parentOptions.arrows,newOptions.arrows,"to",globalOptions.arrows);mergeOptions(parentOptions.arrows,newOptions.arrows,"middle",globalOptions.arrows);mergeOptions(parentOptions.arrows,newOptions.arrows,"from",globalOptions.arrows);}else {throw new Error("The arrow newOptions can only be an object or a string. Refer to the documentation. You used:"+JSON.stringify(newOptions.arrows));}}else if(allowDeletion===true&&newOptions.arrows===null){parentOptions.arrows=Object.create(globalOptions.arrows);// this sets the pointer of the option back to the global option.
}// handle multiple input cases for color
if(newOptions.color!==undefined&&newOptions.color!==null){const fromColor=isString(newOptions.color)?{color:newOptions.color,highlight:newOptions.color,hover:newOptions.color,inherit:false,opacity:1}:newOptions.color;const toColor=parentOptions.color;// If passed, fill in values from default options - required in the case of no prototype bridging
if(copyFromGlobals){deepExtend(toColor,globalOptions.color,false,allowDeletion);}else {// Clear local properties - need to do it like this in order to retain prototype bridges
for(const i in toColor){if(Object.prototype.hasOwnProperty.call(toColor,i)){delete toColor[i];}}}if(isString(toColor)){toColor.color=toColor;toColor.highlight=toColor;toColor.hover=toColor;toColor.inherit=false;if(fromColor.opacity===undefined){toColor.opacity=1.0;// set default
}}else {let colorsDefined=false;if(fromColor.color!==undefined){toColor.color=fromColor.color;colorsDefined=true;}if(fromColor.highlight!==undefined){toColor.highlight=fromColor.highlight;colorsDefined=true;}if(fromColor.hover!==undefined){toColor.hover=fromColor.hover;colorsDefined=true;}if(fromColor.inherit!==undefined){toColor.inherit=fromColor.inherit;}if(fromColor.opacity!==undefined){toColor.opacity=Math.min(1,Math.max(0,fromColor.opacity));}if(colorsDefined===true){toColor.inherit=false;}else {if(toColor.inherit===undefined){toColor.inherit="from";// Set default
}}}}else if(allowDeletion===true&&newOptions.color===null){parentOptions.color=bridgeObject(globalOptions.color);// set the object back to the global options
}if(allowDeletion===true&&newOptions.font===null){parentOptions.font=bridgeObject(globalOptions.font);// set the object back to the global options
}if(Object.prototype.hasOwnProperty.call(newOptions,"selfReferenceSize")){console.warn("The selfReferenceSize property has been deprecated. Please use selfReference property instead. The selfReference can be set like thise selfReference:{size:30, angle:Math.PI / 4}");parentOptions.selfReference.size=newOptions.selfReferenceSize;}}/**
*
* @returns {ArrowOptions}
*/getFormattingValues(){const toArrow=this.options.arrows.to===true||this.options.arrows.to.enabled===true;const fromArrow=this.options.arrows.from===true||this.options.arrows.from.enabled===true;const middleArrow=this.options.arrows.middle===true||this.options.arrows.middle.enabled===true;const inheritsColor=this.options.color.inherit;const values={toArrow:toArrow,toArrowScale:this.options.arrows.to.scaleFactor,toArrowType:this.options.arrows.to.type,toArrowSrc:this.options.arrows.to.src,toArrowImageWidth:this.options.arrows.to.imageWidth,toArrowImageHeight:this.options.arrows.to.imageHeight,middleArrow:middleArrow,middleArrowScale:this.options.arrows.middle.scaleFactor,middleArrowType:this.options.arrows.middle.type,middleArrowSrc:this.options.arrows.middle.src,middleArrowImageWidth:this.options.arrows.middle.imageWidth,middleArrowImageHeight:this.options.arrows.middle.imageHeight,fromArrow:fromArrow,fromArrowScale:this.options.arrows.from.scaleFactor,fromArrowType:this.options.arrows.from.type,fromArrowSrc:this.options.arrows.from.src,fromArrowImageWidth:this.options.arrows.from.imageWidth,fromArrowImageHeight:this.options.arrows.from.imageHeight,arrowStrikethrough:this.options.arrowStrikethrough,color:inheritsColor?undefined:this.options.color.color,inheritsColor:inheritsColor,opacity:this.options.color.opacity,hidden:this.options.hidden,length:this.options.length,shadow:this.options.shadow.enabled,shadowColor:this.options.shadow.color,shadowSize:this.options.shadow.size,shadowX:this.options.shadow.x,shadowY:this.options.shadow.y,dashes:this.options.dashes,width:this.options.width,background:this.options.background.enabled,backgroundColor:this.options.background.color,backgroundSize:this.options.background.size,backgroundDashes:this.options.background.dashes};if(this.selected||this.hover){if(this.chooser===true){if(this.selected){const selectedWidth=this.options.selectionWidth;if(typeof selectedWidth==="function"){values.width=selectedWidth(values.width);}else if(typeof selectedWidth==="number"){values.width+=selectedWidth;}values.width=Math.max(values.width,0.3/this.body.view.scale);values.color=this.options.color.highlight;values.shadow=this.options.shadow.enabled;}else if(this.hover){const hoverWidth=this.options.hoverWidth;if(typeof hoverWidth==="function"){values.width=hoverWidth(values.width);}else if(typeof hoverWidth==="number"){values.width+=hoverWidth;}values.width=Math.max(values.width,0.3/this.body.view.scale);values.color=this.options.color.hover;values.shadow=this.options.shadow.enabled;}}else if(typeof this.chooser==="function"){this.chooser(values,this.options.id,this.selected,this.hover);if(values.color!==undefined){values.inheritsColor=false;}if(values.shadow===false){if(values.shadowColor!==this.options.shadow.color||values.shadowSize!==this.options.shadow.size||values.shadowX!==this.options.shadow.x||values.shadowY!==this.options.shadow.y){values.shadow=true;}}}}else {values.shadow=this.options.shadow.enabled;values.width=Math.max(values.width,0.3/this.body.view.scale);}return values;}/**
* update the options in the label module
*
* @param {object} options
*/updateLabelModule(options){const pile=[options,this.options,this.globalOptions,// Currently set global edge options
this.defaultOptions];this.labelModule.update(this.options,pile);if(this.labelModule.baseSize!==undefined){this.baseFontSize=this.labelModule.baseSize;}}/**
* update the edge type, set the options
*
* @returns {boolean}
*/updateEdgeType(){const smooth=this.options.smooth;let dataChanged=false;let changeInType=true;if(this.edgeType!==undefined){if(this.edgeType instanceof BezierEdgeDynamic&&smooth.enabled===true&&smooth.type==="dynamic"||this.edgeType instanceof CubicBezierEdge&&smooth.enabled===true&&smooth.type==="cubicBezier"||this.edgeType instanceof BezierEdgeStatic&&smooth.enabled===true&&smooth.type!=="dynamic"&&smooth.type!=="cubicBezier"||this.edgeType instanceof StraightEdge&&smooth.type.enabled===false){changeInType=false;}if(changeInType===true){dataChanged=this.cleanup();}}if(changeInType===true){if(smooth.enabled===true){if(smooth.type==="dynamic"){dataChanged=true;this.edgeType=new BezierEdgeDynamic(this.options,this.body,this.labelModule);}else if(smooth.type==="cubicBezier"){this.edgeType=new CubicBezierEdge(this.options,this.body,this.labelModule);}else {this.edgeType=new BezierEdgeStatic(this.options,this.body,this.labelModule);}}else {this.edgeType=new StraightEdge(this.options,this.body,this.labelModule);}}else {// if nothing changes, we just set the options.
this.edgeType.setOptions(this.options);}return dataChanged;}/**
* Connect an edge to its nodes
*/connect(){this.disconnect();this.from=this.body.nodes[this.fromId]||undefined;this.to=this.body.nodes[this.toId]||undefined;this.connected=this.from!==undefined&&this.to!==undefined;if(this.connected===true){this.from.attachEdge(this);this.to.attachEdge(this);}else {if(this.from){this.from.detachEdge(this);}if(this.to){this.to.detachEdge(this);}}this.edgeType.connect();}/**
* Disconnect an edge from its nodes
*/disconnect(){if(this.from){this.from.detachEdge(this);this.from=undefined;}if(this.to){this.to.detachEdge(this);this.to=undefined;}this.connected=false;}/**
* get the title of this edge.
*
* @returns {string} title The title of the edge, or undefined when no title
* has been set.
*/getTitle(){return this.title;}/**
* check if this node is selecte
*
* @returns {boolean} selected True if node is selected, else false
*/isSelected(){return this.selected;}/**
* Retrieve the value of the edge. Can be undefined
*
* @returns {number} value
*/getValue(){return this.options.value;}/**
* Adjust the value range of the edge. The edge will adjust it's width
* based on its value.
*
* @param {number} min
* @param {number} max
* @param {number} total
*/setValueRange(min,max,total){if(this.options.value!==undefined){const scale=this.options.scaling.customScalingFunction(min,max,total,this.options.value);const widthDiff=this.options.scaling.max-this.options.scaling.min;if(this.options.scaling.label.enabled===true){const fontDiff=this.options.scaling.label.max-this.options.scaling.label.min;this.options.font.size=this.options.scaling.label.min+scale*fontDiff;}this.options.width=this.options.scaling.min+scale*widthDiff;}else {this.options.width=this.baseWidth;this.options.font.size=this.baseFontSize;}this._setInteractionWidths();this.updateLabelModule();}/**
*
* @private
*/_setInteractionWidths(){if(typeof this.options.hoverWidth==="function"){this.edgeType.hoverWidth=this.options.hoverWidth(this.options.width);}else {this.edgeType.hoverWidth=this.options.hoverWidth+this.options.width;}if(typeof this.options.selectionWidth==="function"){this.edgeType.selectionWidth=this.options.selectionWidth(this.options.width);}else {this.edgeType.selectionWidth=this.options.selectionWidth+this.options.width;}}/**
* Redraw a edge
* Draw this edge in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
*
* @param {CanvasRenderingContext2D} ctx
*/draw(ctx){const values=this.getFormattingValues();if(values.hidden){return;}// get the via node from the edge type
const viaNode=this.edgeType.getViaNode();// draw line and label
this.edgeType.drawLine(ctx,values,this.selected,this.hover,viaNode);this.drawLabel(ctx,viaNode);}/**
* Redraw arrows
* Draw this arrows in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
*
* @param {CanvasRenderingContext2D} ctx
*/drawArrows(ctx){const values=this.getFormattingValues();if(values.hidden){return;}// get the via node from the edge type
const viaNode=this.edgeType.getViaNode();const arrowData={};// restore edge targets to defaults
this.edgeType.fromPoint=this.edgeType.from;this.edgeType.toPoint=this.edgeType.to;// from and to arrows give a different end point for edges. we set them here
if(values.fromArrow){arrowData.from=this.edgeType.getArrowData(ctx,"from",viaNode,this.selected,this.hover,values);if(values.arrowStrikethrough===false)this.edgeType.fromPoint=arrowData.from.core;if(values.fromArrowSrc){arrowData.from.image=this.imagelist.load(values.fromArrowSrc);}if(values.fromArrowImageWidth){arrowData.from.imageWidth=values.fromArrowImageWidth;}if(values.fromArrowImageHeight){arrowData.from.imageHeight=values.fromArrowImageHeight;}}if(values.toArrow){arrowData.to=this.edgeType.getArrowData(ctx,"to",viaNode,this.selected,this.hover,values);if(values.arrowStrikethrough===false)this.edgeType.toPoint=arrowData.to.core;if(values.toArrowSrc){arrowData.to.image=this.imagelist.load(values.toArrowSrc);}if(values.toArrowImageWidth){arrowData.to.imageWidth=values.toArrowImageWidth;}if(values.toArrowImageHeight){arrowData.to.imageHeight=values.toArrowImageHeight;}}// the middle arrow depends on the line, which can depend on the to and from arrows so we do this one lastly.
if(values.middleArrow){arrowData.middle=this.edgeType.getArrowData(ctx,"middle",viaNode,this.selected,this.hover,values);if(values.middleArrowSrc){arrowData.middle.image=this.imagelist.load(values.middleArrowSrc);}if(values.middleArrowImageWidth){arrowData.middle.imageWidth=values.middleArrowImageWidth;}if(values.middleArrowImageHeight){arrowData.middle.imageHeight=values.middleArrowImageHeight;}}if(values.fromArrow){this.edgeType.drawArrowHead(ctx,values,this.selected,this.hover,arrowData.from);}if(values.middleArrow){this.edgeType.drawArrowHead(ctx,values,this.selected,this.hover,arrowData.middle);}if(values.toArrow){this.edgeType.drawArrowHead(ctx,values,this.selected,this.hover,arrowData.to);}}/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {Node} viaNode
*/drawLabel(ctx,viaNode){if(this.options.label!==undefined){// set style
const node1=this.from;const node2=this.to;if(this.labelModule.differentState(this.selected,this.hover)){this.labelModule.getTextSize(ctx,this.selected,this.hover);}let point;if(node1.id!=node2.id){this.labelModule.pointToSelf=false;point=this.edgeType.getPoint(0.5,viaNode);ctx.save();const rotationPoint=this._getRotation(ctx);if(rotationPoint.angle!=0){ctx.translate(rotationPoint.x,rotationPoint.y);ctx.rotate(rotationPoint.angle);}// draw the label
this.labelModule.draw(ctx,point.x,point.y,this.selected,this.hover);/*
// Useful debug code: draw a border around the label
// This should **not** be enabled in production!
var size = this.labelModule.getSize();; // ;; intentional so lint catches it
ctx.strokeStyle = "#ff0000";
ctx.strokeRect(size.left, size.top, size.width, size.height);
// End debug code
*/ctx.restore();}else {// Ignore the orientations.
this.labelModule.pointToSelf=true;// get circle coordinates
const coordinates=getSelfRefCoordinates(ctx,this.options.selfReference.angle,this.options.selfReference.size,node1);point=this._pointOnCircle(coordinates.x,coordinates.y,this.options.selfReference.size,this.options.selfReference.angle);this.labelModule.draw(ctx,point.x,point.y,this.selected,this.hover);}}}/**
* Determine all visual elements of this edge instance, in which the given
* point falls within the bounding shape.
*
* @param {point} point
* @returns {Array.<edgeClickItem|edgeLabelClickItem>} list with the items which are on the point
*/getItemsOnPoint(point){const ret=[];if(this.labelModule.visible()){const rotationPoint=this._getRotation();if(pointInRect(this.labelModule.getSize(),point,rotationPoint)){ret.push({edgeId:this.id,labelId:0});}}const obj={left:point.x,top:point.y};if(this.isOverlappingWith(obj)){ret.push({edgeId:this.id});}return ret;}/**
* Check if this object is overlapping with the provided object
*
* @param {object} obj an object with parameters left, top
* @returns {boolean} True if location is located on the edge
*/isOverlappingWith(obj){if(this.connected){const distMax=10;const xFrom=this.from.x;const yFrom=this.from.y;const xTo=this.to.x;const yTo=this.to.y;const xObj=obj.left;const yObj=obj.top;const dist=this.edgeType.getDistanceToEdge(xFrom,yFrom,xTo,yTo,xObj,yObj);return dist<distMax;}else {return false;}}/**
* Determine the rotation point, if any.
*
* @param {CanvasRenderingContext2D} [ctx] if passed, do a recalculation of the label size
* @returns {rotationPoint} the point to rotate around and the angle in radians to rotate
* @private
*/_getRotation(ctx){const viaNode=this.edgeType.getViaNode();const point=this.edgeType.getPoint(0.5,viaNode);if(ctx!==undefined){this.labelModule.calculateLabelSize(ctx,this.selected,this.hover,point.x,point.y);}const ret={x:point.x,y:this.labelModule.size.yLine,angle:0};if(!this.labelModule.visible()){return ret;// Don't even bother doing the atan2, there's nothing to draw
}if(this.options.font.align==="horizontal"){return ret;// No need to calculate angle
}const dy=this.from.y-this.to.y;const dx=this.from.x-this.to.x;let angle=Math.atan2(dy,dx);// radians
// rotate so that label is readable
if(angle<-1&&dx<0||angle>0&&dx<0){angle+=Math.PI;}ret.angle=angle;return ret;}/**
* Get a point on a circle
*
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} angle
* @returns {object} point
* @private
*/_pointOnCircle(x,y,radius,angle){return {x:x+radius*Math.cos(angle),y:y-radius*Math.sin(angle)};}/**
* Sets selected state to true
*/select(){this.selected=true;}/**
* Sets selected state to false
*/unselect(){this.selected=false;}/**
* cleans all required things on delete
*
* @returns {*}
*/cleanup(){return this.edgeType.cleanup();}/**
* Remove edge from the list and perform necessary cleanup.
*/remove(){this.cleanup();this.disconnect();delete this.body.edges[this.id];}/**
* Check if both connecting nodes exist
*
* @returns {boolean}
*/endPointsValid(){return this.body.nodes[this.fromId]!==undefined&&this.body.nodes[this.toId]!==undefined;}}/**
* Handler for Edges
*/class EdgesHandler{/**
* @param {object} body
* @param {Array.<Image>} images
* @param {Array.<Group>} groups
*/constructor(body,images,groups){this.body=body;this.images=images;this.groups=groups;// create the edge API in the body container
this.body.functions.createEdge=this.create.bind(this);this.edgesListeners={add:(event,params)=>{this.add(params.items);},update:(event,params)=>{this.update(params.items);},remove:(event,params)=>{this.remove(params.items);}};this.options={};this.defaultOptions={arrows:{to:{enabled:false,scaleFactor:1,type:"arrow"},// boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1}
middle:{enabled:false,scaleFactor:1,type:"arrow"},from:{enabled:false,scaleFactor:1,type:"arrow"}},endPointOffset:{from:0,to:0},arrowStrikethrough:true,color:{color:"#848484",highlight:"#848484",hover:"#848484",inherit:"from",opacity:1.0},dashes:false,font:{color:"#343434",size:14,// px
face:"arial",background:"none",strokeWidth:2,// px
strokeColor:"#ffffff",align:"horizontal",multi:false,vadjust:0,bold:{mod:"bold"},boldital:{mod:"bold italic"},ital:{mod:"italic"},mono:{mod:"",size:15,// px
face:"courier new",vadjust:2}},hidden:false,hoverWidth:1.5,label:undefined,labelHighlightBold:true,length:undefined,physics:true,scaling:{min:1,max:15,label:{enabled:true,min:14,max:30,maxVisible:30,drawThreshold:5},customScalingFunction:function(min,max,total,value){if(max===min){return 0.5;}else {const scale=1/(max-min);return Math.max(0,(value-min)*scale);}}},selectionWidth:1.5,selfReference:{size:20,angle:Math.PI/4,renderBehindTheNode:true},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:10,x:5,y:5},background:{enabled:false,color:"rgba(111,111,111,1)",size:10,dashes:false},smooth:{enabled:true,type:"dynamic",forceDirection:"none",roundness:0.5},title:undefined,width:1,value:undefined};deepExtend(this.options,this.defaultOptions);this.bindEventListeners();}/**
* Binds event listeners
*/bindEventListeners(){// this allows external modules to force all dynamic curves to turn static.
this.body.emitter.on("_forceDisableDynamicCurves",(type,emit=true)=>{if(type==="dynamic"){type="continuous";}let dataChanged=false;for(const edgeId in this.body.edges){if(Object.prototype.hasOwnProperty.call(this.body.edges,edgeId)){const edge=this.body.edges[edgeId];const edgeData=this.body.data.edges.get(edgeId);// only forcibly remove the smooth curve if the data has been set of the edge has the smooth curves defined.
// this is because a change in the global would not affect these curves.
if(edgeData!=null){const smoothOptions=edgeData.smooth;if(smoothOptions!==undefined){if(smoothOptions.enabled===true&&smoothOptions.type==="dynamic"){if(type===undefined){edge.setOptions({smooth:false});}else {edge.setOptions({smooth:{type:type}});}dataChanged=true;}}}}}if(emit===true&&dataChanged===true){this.body.emitter.emit("_dataChanged");}});// this is called when options of EXISTING nodes or edges have changed.
//
// NOTE: Not true, called when options have NOT changed, for both existing as well as new nodes.
// See update() for logic.
// TODO: Verify and examine the consequences of this. It might still trigger when
// non-option fields have changed, but then reconnecting edges is still useless.
// Alternatively, it might also be called when edges are removed.
//
this.body.emitter.on("_dataUpdated",()=>{this.reconnectEdges();});// refresh the edges. Used when reverting from hierarchical layout
this.body.emitter.on("refreshEdges",this.refresh.bind(this));this.body.emitter.on("refresh",this.refresh.bind(this));this.body.emitter.on("destroy",()=>{forEach(this.edgesListeners,(callback,event)=>{if(this.body.data.edges)this.body.data.edges.off(event,callback);});delete this.body.functions.createEdge;delete this.edgesListeners.add;delete this.edgesListeners.update;delete this.edgesListeners.remove;delete this.edgesListeners;});}/**
*
* @param {object} options
*/setOptions(options){if(options!==undefined){// use the parser from the Edge class to fill in all shorthand notations
Edge.parseOptions(this.options,options,true,this.defaultOptions,true);// update smooth settings in all edges
let dataChanged=false;if(options.smooth!==undefined){for(const edgeId in this.body.edges){if(Object.prototype.hasOwnProperty.call(this.body.edges,edgeId)){dataChanged=this.body.edges[edgeId].updateEdgeType()||dataChanged;}}}// update fonts in all edges
if(options.font!==undefined){for(const edgeId in this.body.edges){if(Object.prototype.hasOwnProperty.call(this.body.edges,edgeId)){this.body.edges[edgeId].updateLabelModule();}}}// update the state of the variables if needed
if(options.hidden!==undefined||options.physics!==undefined||dataChanged===true){this.body.emitter.emit("_dataChanged");}}}/**
* Load edges by reading the data table
*
* @param {Array | DataSet | DataView} edges The data containing the edges.
* @param {boolean} [doNotEmit=false] - Suppress data changed event.
* @private
*/setData(edges,doNotEmit=false){const oldEdgesData=this.body.data.edges;if(isDataViewLike$1("id",edges)){this.body.data.edges=edges;}else if(Array.isArray(edges)){this.body.data.edges=new DataSet();this.body.data.edges.add(edges);}else if(!edges){this.body.data.edges=new DataSet();}else {throw new TypeError("Array or DataSet expected");}// TODO: is this null or undefined or false?
if(oldEdgesData){// unsubscribe from old dataset
forEach(this.edgesListeners,(callback,event)=>{oldEdgesData.off(event,callback);});}// remove drawn edges
this.body.edges={};// TODO: is this null or undefined or false?
if(this.body.data.edges){// subscribe to new dataset
forEach(this.edgesListeners,(callback,event)=>{this.body.data.edges.on(event,callback);});// draw all new nodes
const ids=this.body.data.edges.getIds();this.add(ids,true);}this.body.emitter.emit("_adjustEdgesForHierarchicalLayout");if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
* Add edges
*
* @param {number[] | string[]} ids
* @param {boolean} [doNotEmit=false]
* @private
*/add(ids,doNotEmit=false){const edges=this.body.edges;const edgesData=this.body.data.edges;for(let i=0;i<ids.length;i++){const id=ids[i];const oldEdge=edges[id];if(oldEdge){oldEdge.disconnect();}const data=edgesData.get(id,{showInternalIds:true});edges[id]=this.create(data);}this.body.emitter.emit("_adjustEdgesForHierarchicalLayout");if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
* Update existing edges, or create them when not yet existing
*
* @param {number[] | string[]} ids
* @private
*/update(ids){const edges=this.body.edges;const edgesData=this.body.data.edges;let dataChanged=false;for(let i=0;i<ids.length;i++){const id=ids[i];const data=edgesData.get(id);const edge=edges[id];if(edge!==undefined){// update edge
edge.disconnect();dataChanged=edge.setOptions(data)||dataChanged;// if a support node is added, data can be changed.
edge.connect();}else {// create edge
this.body.edges[id]=this.create(data);dataChanged=true;}}if(dataChanged===true){this.body.emitter.emit("_adjustEdgesForHierarchicalLayout");this.body.emitter.emit("_dataChanged");}else {this.body.emitter.emit("_dataUpdated");}}/**
* Remove existing edges. Non existing ids will be ignored
*
* @param {number[] | string[]} ids
* @param {boolean} [emit=true]
* @private
*/remove(ids,emit=true){if(ids.length===0)return;// early out
const edges=this.body.edges;forEach(ids,id=>{const edge=edges[id];if(edge!==undefined){edge.remove();}});if(emit){this.body.emitter.emit("_dataChanged");}}/**
* Refreshes Edge Handler
*/refresh(){forEach(this.body.edges,(edge,edgeId)=>{const data=this.body.data.edges.get(edgeId);if(data!==undefined){edge.setOptions(data);}});}/**
*
* @param {object} properties
* @returns {Edge}
*/create(properties){return new Edge(properties,this.body,this.images,this.options,this.defaultOptions);}/**
* Reconnect all edges
*
* @private
*/reconnectEdges(){let id;const nodes=this.body.nodes;const edges=this.body.edges;for(id in nodes){if(Object.prototype.hasOwnProperty.call(nodes,id)){nodes[id].edges=[];}}for(id in edges){if(Object.prototype.hasOwnProperty.call(edges,id)){const edge=edges[id];edge.from=null;edge.to=null;edge.connect();}}}/**
*
* @param {Edge.id} edgeId
* @returns {Array}
*/getConnectedNodes(edgeId){const nodeList=[];if(this.body.edges[edgeId]!==undefined){const edge=this.body.edges[edgeId];if(edge.fromId!==undefined){nodeList.push(edge.fromId);}if(edge.toId!==undefined){nodeList.push(edge.toId);}}return nodeList;}/**
* There is no direct relation between the nodes and the edges DataSet,
* so the right place to do call this is in the handler for event `_dataUpdated`.
*/_updateState(){this._addMissingEdges();this._removeInvalidEdges();}/**
* Scan for missing nodes and remove corresponding edges, if any.
*
* @private
*/_removeInvalidEdges(){const edgesToDelete=[];forEach(this.body.edges,(edge,id)=>{const toNode=this.body.nodes[edge.toId];const fromNode=this.body.nodes[edge.fromId];// Skip clustering edges here, let the Clustering module handle those
if(toNode!==undefined&&toNode.isCluster===true||fromNode!==undefined&&fromNode.isCluster===true){return;}if(toNode===undefined||fromNode===undefined){edgesToDelete.push(id);}});this.remove(edgesToDelete,false);}/**
* add all edges from dataset that are not in the cached state
*
* @private
*/_addMissingEdges(){const edgesData=this.body.data.edges;if(edgesData===undefined||edgesData===null){return;// No edges DataSet yet; can happen on startup
}const edges=this.body.edges;const addIds=[];edgesData.forEach((edgeData,edgeId)=>{const edge=edges[edgeId];if(edge===undefined){addIds.push(edgeId);}});this.add(addIds,true);}}/**
* Barnes Hut Solver
*/class BarnesHutSolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.barnesHutTree;this.setOptions(options);this._rng=Alea("BARNES HUT SOLVER");// debug: show grid
// this.body.emitter.on("afterDrawing", (ctx) => {this._debug(ctx,'#ff0000')})
}/**
*
* @param {object} options
*/setOptions(options){this.options=options;this.thetaInversed=1/this.options.theta;// if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius
this.overlapAvoidanceFactor=1-Math.max(0,Math.min(1,this.options.avoidOverlap));}/**
* This function calculates the forces the nodes apply on each other based on a gravitational model.
* The Barnes Hut method is used to speed up this N-body simulation.
*
* @private
*/solve(){if(this.options.gravitationalConstant!==0&&this.physicsBody.physicsNodeIndices.length>0){let node;const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const nodeCount=nodeIndices.length;// create the tree
const barnesHutTree=this._formBarnesHutTree(nodes,nodeIndices);// for debugging
this.barnesHutTree=barnesHutTree;// place the nodes one by one recursively
for(let i=0;i<nodeCount;i++){node=nodes[nodeIndices[i]];if(node.options.mass>0){// starting with root is irrelevant, it never passes the BarnesHutSolver condition
this._getForceContributions(barnesHutTree.root,node);}}}}/**
* @param {object} parentBranch
* @param {Node} node
* @private
*/_getForceContributions(parentBranch,node){this._getForceContribution(parentBranch.children.NW,node);this._getForceContribution(parentBranch.children.NE,node);this._getForceContribution(parentBranch.children.SW,node);this._getForceContribution(parentBranch.children.SE,node);}/**
* This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
* If a region contains a single node, we check if it is not itself, then we apply the force.
*
* @param {object} parentBranch
* @param {Node} node
* @private
*/_getForceContribution(parentBranch,node){// we get no force contribution from an empty region
if(parentBranch.childrenCount>0){// get the distance from the center of mass to the node.
const dx=parentBranch.centerOfMass.x-node.x;const dy=parentBranch.centerOfMass.y-node.y;const distance=Math.sqrt(dx*dx+dy*dy);// BarnesHutSolver condition
// original condition : s/d < theta = passed === d/s > 1/theta = passed
// calcSize = 1/s --> d * 1/s > 1/theta = passed
if(distance*parentBranch.calcSize>this.thetaInversed){this._calculateForces(distance,dx,dy,node,parentBranch);}else {// Did not pass the condition, go into children if available
if(parentBranch.childrenCount===4){this._getForceContributions(parentBranch,node);}else {// parentBranch must have only one node, if it was empty we wouldnt be here
if(parentBranch.children.data.id!=node.id){// if it is not self
this._calculateForces(distance,dx,dy,node,parentBranch);}}}}}/**
* Calculate the forces based on the distance.
*
* @param {number} distance
* @param {number} dx
* @param {number} dy
* @param {Node} node
* @param {object} parentBranch
* @private
*/_calculateForces(distance,dx,dy,node,parentBranch){if(distance===0){distance=0.1;dx=distance;}if(this.overlapAvoidanceFactor<1&&node.shape.radius){distance=Math.max(0.1+this.overlapAvoidanceFactor*node.shape.radius,distance-node.shape.radius);}// the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
// it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
const gravityForce=this.options.gravitationalConstant*parentBranch.mass*node.options.mass/Math.pow(distance,3);const fx=dx*gravityForce;const fy=dy*gravityForce;this.physicsBody.forces[node.id].x+=fx;this.physicsBody.forces[node.id].y+=fy;}/**
* This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
*
* @param {Array.<Node>} nodes
* @param {Array.<number>} nodeIndices
* @returns {{root: {centerOfMass: {x: number, y: number}, mass: number, range: {minX: number, maxX: number, minY: number, maxY: number}, size: number, calcSize: number, children: {data: null}, maxWidth: number, level: number, childrenCount: number}}} BarnesHutTree
* @private
*/_formBarnesHutTree(nodes,nodeIndices){let node;const nodeCount=nodeIndices.length;let minX=nodes[nodeIndices[0]].x;let minY=nodes[nodeIndices[0]].y;let maxX=nodes[nodeIndices[0]].x;let maxY=nodes[nodeIndices[0]].y;// get the range of the nodes
for(let i=1;i<nodeCount;i++){const node=nodes[nodeIndices[i]];const x=node.x;const y=node.y;if(node.options.mass>0){if(x<minX){minX=x;}if(x>maxX){maxX=x;}if(y<minY){minY=y;}if(y>maxY){maxY=y;}}}// make the range a square
const sizeDiff=Math.abs(maxX-minX)-Math.abs(maxY-minY);// difference between X and Y
if(sizeDiff>0){minY-=0.5*sizeDiff;maxY+=0.5*sizeDiff;}// xSize > ySize
else {minX+=0.5*sizeDiff;maxX-=0.5*sizeDiff;}// xSize < ySize
const minimumTreeSize=1e-5;const rootSize=Math.max(minimumTreeSize,Math.abs(maxX-minX));const halfRootSize=0.5*rootSize;const centerX=0.5*(minX+maxX),centerY=0.5*(minY+maxY);// construct the barnesHutTree
const barnesHutTree={root:{centerOfMass:{x:0,y:0},mass:0,range:{minX:centerX-halfRootSize,maxX:centerX+halfRootSize,minY:centerY-halfRootSize,maxY:centerY+halfRootSize},size:rootSize,calcSize:1/rootSize,children:{data:null},maxWidth:0,level:0,childrenCount:4}};this._splitBranch(barnesHutTree.root);// place the nodes one by one recursively
for(let i=0;i<nodeCount;i++){node=nodes[nodeIndices[i]];if(node.options.mass>0){this._placeInTree(barnesHutTree.root,node);}}// make global
return barnesHutTree;}/**
* this updates the mass of a branch. this is increased by adding a node.
*
* @param {object} parentBranch
* @param {Node} node
* @private
*/_updateBranchMass(parentBranch,node){const centerOfMass=parentBranch.centerOfMass;const totalMass=parentBranch.mass+node.options.mass;const totalMassInv=1/totalMass;centerOfMass.x=centerOfMass.x*parentBranch.mass+node.x*node.options.mass;centerOfMass.x*=totalMassInv;centerOfMass.y=centerOfMass.y*parentBranch.mass+node.y*node.options.mass;centerOfMass.y*=totalMassInv;parentBranch.mass=totalMass;const biggestSize=Math.max(Math.max(node.height,node.radius),node.width);parentBranch.maxWidth=parentBranch.maxWidth<biggestSize?biggestSize:parentBranch.maxWidth;}/**
* determine in which branch the node will be placed.
*
* @param {object} parentBranch
* @param {Node} node
* @param {boolean} skipMassUpdate
* @private
*/_placeInTree(parentBranch,node,skipMassUpdate){if(skipMassUpdate!=true||skipMassUpdate===undefined){// update the mass of the branch.
this._updateBranchMass(parentBranch,node);}const range=parentBranch.children.NW.range;let region;if(range.maxX>node.x){// in NW or SW
if(range.maxY>node.y){region="NW";}else {region="SW";}}else {// in NE or SE
if(range.maxY>node.y){region="NE";}else {region="SE";}}this._placeInRegion(parentBranch,node,region);}/**
* actually place the node in a region (or branch)
*
* @param {object} parentBranch
* @param {Node} node
* @param {'NW'| 'NE' | 'SW' | 'SE'} region
* @private
*/_placeInRegion(parentBranch,node,region){const children=parentBranch.children[region];switch(children.childrenCount){case 0:// place node here
children.children.data=node;children.childrenCount=1;this._updateBranchMass(children,node);break;case 1:// convert into children
// if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
// we move one node a little bit and we do not put it in the tree.
if(children.children.data.x===node.x&&children.children.data.y===node.y){node.x+=this._rng();node.y+=this._rng();}else {this._splitBranch(children);this._placeInTree(children,node);}break;case 4:// place in branch
this._placeInTree(children,node);break;}}/**
* this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
* after the split is complete.
*
* @param {object} parentBranch
* @private
*/_splitBranch(parentBranch){// if the branch is shaded with a node, replace the node in the new subset.
let containedNode=null;if(parentBranch.childrenCount===1){containedNode=parentBranch.children.data;parentBranch.mass=0;parentBranch.centerOfMass.x=0;parentBranch.centerOfMass.y=0;}parentBranch.childrenCount=4;parentBranch.children.data=null;this._insertRegion(parentBranch,"NW");this._insertRegion(parentBranch,"NE");this._insertRegion(parentBranch,"SW");this._insertRegion(parentBranch,"SE");if(containedNode!=null){this._placeInTree(parentBranch,containedNode);}}/**
* This function subdivides the region into four new segments.
* Specifically, this inserts a single new segment.
* It fills the children section of the parentBranch
*
* @param {object} parentBranch
* @param {'NW'| 'NE' | 'SW' | 'SE'} region
* @private
*/_insertRegion(parentBranch,region){let minX,maxX,minY,maxY;const childSize=0.5*parentBranch.size;switch(region){case"NW":minX=parentBranch.range.minX;maxX=parentBranch.range.minX+childSize;minY=parentBranch.range.minY;maxY=parentBranch.range.minY+childSize;break;case"NE":minX=parentBranch.range.minX+childSize;maxX=parentBranch.range.maxX;minY=parentBranch.range.minY;maxY=parentBranch.range.minY+childSize;break;case"SW":minX=parentBranch.range.minX;maxX=parentBranch.range.minX+childSize;minY=parentBranch.range.minY+childSize;maxY=parentBranch.range.maxY;break;case"SE":minX=parentBranch.range.minX+childSize;maxX=parentBranch.range.maxX;minY=parentBranch.range.minY+childSize;maxY=parentBranch.range.maxY;break;}parentBranch.children[region]={centerOfMass:{x:0,y:0},mass:0,range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},size:0.5*parentBranch.size,calcSize:2*parentBranch.calcSize,children:{data:null},maxWidth:0,level:parentBranch.level+1,childrenCount:0};}//--------------------------- DEBUGGING BELOW ---------------------------//
/**
* This function is for debugging purposed, it draws the tree.
*
* @param {CanvasRenderingContext2D} ctx
* @param {string} color
* @private
*/_debug(ctx,color){if(this.barnesHutTree!==undefined){ctx.lineWidth=1;this._drawBranch(this.barnesHutTree.root,ctx,color);}}/**
* This function is for debugging purposes. It draws the branches recursively.
*
* @param {object} branch
* @param {CanvasRenderingContext2D} ctx
* @param {string} color
* @private
*/_drawBranch(branch,ctx,color){if(color===undefined){color="#FF0000";}if(branch.childrenCount===4){this._drawBranch(branch.children.NW,ctx);this._drawBranch(branch.children.NE,ctx);this._drawBranch(branch.children.SE,ctx);this._drawBranch(branch.children.SW,ctx);}ctx.strokeStyle=color;ctx.beginPath();ctx.moveTo(branch.range.minX,branch.range.minY);ctx.lineTo(branch.range.maxX,branch.range.minY);ctx.stroke();ctx.beginPath();ctx.moveTo(branch.range.maxX,branch.range.minY);ctx.lineTo(branch.range.maxX,branch.range.maxY);ctx.stroke();ctx.beginPath();ctx.moveTo(branch.range.maxX,branch.range.maxY);ctx.lineTo(branch.range.minX,branch.range.maxY);ctx.stroke();ctx.beginPath();ctx.moveTo(branch.range.minX,branch.range.maxY);ctx.lineTo(branch.range.minX,branch.range.minY);ctx.stroke();/*
if (branch.mass > 0) {
ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
ctx.stroke();
}
*/}}/**
* Repulsion Solver
*/class RepulsionSolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){this._rng=Alea("REPULSION SOLVER");this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
*
* @param {object} options
*/setOptions(options){this.options=options;}/**
* Calculate the forces the nodes apply on each other based on a repulsion field.
* This field is linearly approximated.
*
* @private
*/solve(){let dx,dy,distance,fx,fy,repulsingForce,node1,node2;const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;// repulsing forces between nodes
const nodeDistance=this.options.nodeDistance;// approximation constants
const a=-2/3/nodeDistance;const b=4/3;// we loop from i over all but the last entree in the array
// j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
for(let i=0;i<nodeIndices.length-1;i++){node1=nodes[nodeIndices[i]];for(let j=i+1;j<nodeIndices.length;j++){node2=nodes[nodeIndices[j]];dx=node2.x-node1.x;dy=node2.y-node1.y;distance=Math.sqrt(dx*dx+dy*dy);// same condition as BarnesHutSolver, making sure nodes are never 100% overlapping.
if(distance===0){distance=0.1*this._rng();dx=distance;}if(distance<2*nodeDistance){if(distance<0.5*nodeDistance){repulsingForce=1.0;}else {repulsingForce=a*distance+b;// linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness))
}repulsingForce=repulsingForce/distance;fx=dx*repulsingForce;fy=dy*repulsingForce;forces[node1.id].x-=fx;forces[node1.id].y-=fy;forces[node2.id].x+=fx;forces[node2.id].y+=fy;}}}}}/**
* Hierarchical Repulsion Solver
*/class HierarchicalRepulsionSolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
*
* @param {object} options
*/setOptions(options){this.options=options;this.overlapAvoidanceFactor=Math.max(0,Math.min(1,this.options.avoidOverlap||0));}/**
* Calculate the forces the nodes apply on each other based on a repulsion field.
* This field is linearly approximated.
*
* @private
*/solve(){const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;// repulsing forces between nodes
const nodeDistance=this.options.nodeDistance;// we loop from i over all but the last entree in the array
// j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
for(let i=0;i<nodeIndices.length-1;i++){const node1=nodes[nodeIndices[i]];for(let j=i+1;j<nodeIndices.length;j++){const node2=nodes[nodeIndices[j]];// nodes only affect nodes on their level
if(node1.level===node2.level){const theseNodesDistance=nodeDistance+this.overlapAvoidanceFactor*((node1.shape.radius||0)/2+(node2.shape.radius||0)/2);const dx=node2.x-node1.x;const dy=node2.y-node1.y;const distance=Math.sqrt(dx*dx+dy*dy);const steepness=0.05;let repulsingForce;if(distance<theseNodesDistance){repulsingForce=-Math.pow(steepness*distance,2)+Math.pow(steepness*theseNodesDistance,2);}else {repulsingForce=0;}// normalize force with
if(distance!==0){repulsingForce=repulsingForce/distance;}const fx=dx*repulsingForce;const fy=dy*repulsingForce;forces[node1.id].x-=fx;forces[node1.id].y-=fy;forces[node2.id].x+=fx;forces[node2.id].y+=fy;}}}}}/**
* Spring Solver
*/class SpringSolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
*
* @param {object} options
*/setOptions(options){this.options=options;}/**
* This function calculates the springforces on the nodes, accounting for the support nodes.
*
* @private
*/solve(){let edgeLength,edge;const edgeIndices=this.physicsBody.physicsEdgeIndices;const edges=this.body.edges;let node1,node2,node3;// forces caused by the edges, modelled as springs
for(let i=0;i<edgeIndices.length;i++){edge=edges[edgeIndices[i]];if(edge.connected===true&&edge.toId!==edge.fromId){// only calculate forces if nodes are in the same sector
if(this.body.nodes[edge.toId]!==undefined&&this.body.nodes[edge.fromId]!==undefined){if(edge.edgeType.via!==undefined){edgeLength=edge.options.length===undefined?this.options.springLength:edge.options.length;node1=edge.to;node2=edge.edgeType.via;node3=edge.from;this._calculateSpringForce(node1,node2,0.5*edgeLength);this._calculateSpringForce(node2,node3,0.5*edgeLength);}else {// the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use
// the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger.
edgeLength=edge.options.length===undefined?this.options.springLength*1.5:edge.options.length;this._calculateSpringForce(edge.from,edge.to,edgeLength);}}}}}/**
* This is the code actually performing the calculation for the function above.
*
* @param {Node} node1
* @param {Node} node2
* @param {number} edgeLength
* @private
*/_calculateSpringForce(node1,node2,edgeLength){const dx=node1.x-node2.x;const dy=node1.y-node2.y;const distance=Math.max(Math.sqrt(dx*dx+dy*dy),0.01);// the 1/distance is so the fx and fy can be calculated without sine or cosine.
const springForce=this.options.springConstant*(edgeLength-distance)/distance;const fx=dx*springForce;const fy=dy*springForce;// handle the case where one node is not part of the physcis
if(this.physicsBody.forces[node1.id]!==undefined){this.physicsBody.forces[node1.id].x+=fx;this.physicsBody.forces[node1.id].y+=fy;}if(this.physicsBody.forces[node2.id]!==undefined){this.physicsBody.forces[node2.id].x-=fx;this.physicsBody.forces[node2.id].y-=fy;}}}/**
* Hierarchical Spring Solver
*/class HierarchicalSpringSolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
*
* @param {object} options
*/setOptions(options){this.options=options;}/**
* This function calculates the springforces on the nodes, accounting for the support nodes.
*
* @private
*/solve(){let edgeLength,edge;let dx,dy,fx,fy,springForce,distance;const edges=this.body.edges;const factor=0.5;const edgeIndices=this.physicsBody.physicsEdgeIndices;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;// initialize the spring force counters
for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];forces[nodeId].springFx=0;forces[nodeId].springFy=0;}// forces caused by the edges, modelled as springs
for(let i=0;i<edgeIndices.length;i++){edge=edges[edgeIndices[i]];if(edge.connected===true){edgeLength=edge.options.length===undefined?this.options.springLength:edge.options.length;dx=edge.from.x-edge.to.x;dy=edge.from.y-edge.to.y;distance=Math.sqrt(dx*dx+dy*dy);distance=distance===0?0.01:distance;// the 1/distance is so the fx and fy can be calculated without sine or cosine.
springForce=this.options.springConstant*(edgeLength-distance)/distance;fx=dx*springForce;fy=dy*springForce;if(edge.to.level!=edge.from.level){if(forces[edge.toId]!==undefined){forces[edge.toId].springFx-=fx;forces[edge.toId].springFy-=fy;}if(forces[edge.fromId]!==undefined){forces[edge.fromId].springFx+=fx;forces[edge.fromId].springFy+=fy;}}else {if(forces[edge.toId]!==undefined){forces[edge.toId].x-=factor*fx;forces[edge.toId].y-=factor*fy;}if(forces[edge.fromId]!==undefined){forces[edge.fromId].x+=factor*fx;forces[edge.fromId].y+=factor*fy;}}}}// normalize spring forces
springForce=1;let springFx,springFy;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];springFx=Math.min(springForce,Math.max(-springForce,forces[nodeId].springFx));springFy=Math.min(springForce,Math.max(-springForce,forces[nodeId].springFy));forces[nodeId].x+=springFx;forces[nodeId].y+=springFy;}// retain energy balance
let totalFx=0;let totalFy=0;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];totalFx+=forces[nodeId].x;totalFy+=forces[nodeId].y;}const correctionFx=totalFx/nodeIndices.length;const correctionFy=totalFy/nodeIndices.length;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];forces[nodeId].x-=correctionFx;forces[nodeId].y-=correctionFy;}}}/**
* Central Gravity Solver
*/class CentralGravitySolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
*
* @param {object} options
*/setOptions(options){this.options=options;}/**
* Calculates forces for each node
*/solve(){let dx,dy,distance,node;const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];node=nodes[nodeId];dx=-node.x;dy=-node.y;distance=Math.sqrt(dx*dx+dy*dy);this._calculateForces(distance,dx,dy,forces,node);}}/**
* Calculate the forces based on the distance.
*
* @param {number} distance
* @param {number} dx
* @param {number} dy
* @param {Object<Node.id, vis.Node>} forces
* @param {Node} node
* @private
*/_calculateForces(distance,dx,dy,forces,node){const gravityForce=distance===0?0:this.options.centralGravity/distance;forces[node.id].x=dx*gravityForce;forces[node.id].y=dy*gravityForce;}}/**
* @augments BarnesHutSolver
*/class ForceAtlas2BasedRepulsionSolver extends BarnesHutSolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){super(body,physicsBody,options);this._rng=Alea("FORCE ATLAS 2 BASED REPULSION SOLVER");}/**
* Calculate the forces based on the distance.
*
* @param {number} distance
* @param {number} dx
* @param {number} dy
* @param {Node} node
* @param {object} parentBranch
* @private
*/_calculateForces(distance,dx,dy,node,parentBranch){if(distance===0){distance=0.1*this._rng();dx=distance;}if(this.overlapAvoidanceFactor<1&&node.shape.radius){distance=Math.max(0.1+this.overlapAvoidanceFactor*node.shape.radius,distance-node.shape.radius);}const degree=node.edges.length+1;// the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
// it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
const gravityForce=this.options.gravitationalConstant*parentBranch.mass*node.options.mass*degree/Math.pow(distance,2);const fx=dx*gravityForce;const fy=dy*gravityForce;this.physicsBody.forces[node.id].x+=fx;this.physicsBody.forces[node.id].y+=fy;}}/**
* @augments CentralGravitySolver
*/class ForceAtlas2BasedCentralGravitySolver extends CentralGravitySolver{/**
* @param {object} body
* @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
* @param {object} options
*/constructor(body,physicsBody,options){super(body,physicsBody,options);}/**
* Calculate the forces based on the distance.
*
* @param {number} distance
* @param {number} dx
* @param {number} dy
* @param {Object<Node.id, Node>} forces
* @param {Node} node
* @private
*/_calculateForces(distance,dx,dy,forces,node){if(distance>0){const degree=node.edges.length+1;const gravityForce=this.options.centralGravity*degree*node.options.mass;forces[node.id].x=dx*gravityForce;forces[node.id].y=dy*gravityForce;}}}/**
* The physics engine
*/class PhysicsEngine{/**
* @param {object} body
*/constructor(body){this.body=body;this.physicsBody={physicsNodeIndices:[],physicsEdgeIndices:[],forces:{},velocities:{}};this.physicsEnabled=true;this.simulationInterval=1000/60;this.requiresTimeout=true;this.previousStates={};this.referenceState={};this.freezeCache={};this.renderTimer=undefined;// parameters for the adaptive timestep
this.adaptiveTimestep=false;this.adaptiveTimestepEnabled=false;this.adaptiveCounter=0;this.adaptiveInterval=3;this.stabilized=false;this.startedStabilization=false;this.stabilizationIterations=0;this.ready=false;// will be set to true if the stabilize
// default options
this.options={};this.defaultOptions={enabled:true,barnesHut:{theta:0.5,gravitationalConstant:-2000,centralGravity:0.3,springLength:95,springConstant:0.04,damping:0.09,avoidOverlap:0},forceAtlas2Based:{theta:0.5,gravitationalConstant:-50,centralGravity:0.01,springConstant:0.08,springLength:100,damping:0.4,avoidOverlap:0},repulsion:{centralGravity:0.2,springLength:200,springConstant:0.05,nodeDistance:100,damping:0.09,avoidOverlap:0},hierarchicalRepulsion:{centralGravity:0.0,springLength:100,springConstant:0.01,nodeDistance:120,damping:0.09},maxVelocity:50,minVelocity:0.75,// px/s
solver:"barnesHut",stabilization:{enabled:true,iterations:1000,// maximum number of iteration to stabilize
updateInterval:50,onlyDynamicEdges:false,fit:true},timestep:0.5,adaptiveTimestep:true,wind:{x:0,y:0}};Object.assign(this.options,this.defaultOptions);this.timestep=0.5;this.layoutFailed=false;this.bindEventListeners();}/**
* Binds event listeners
*/bindEventListeners(){this.body.emitter.on("initPhysics",()=>{this.initPhysics();});this.body.emitter.on("_layoutFailed",()=>{this.layoutFailed=true;});this.body.emitter.on("resetPhysics",()=>{this.stopSimulation();this.ready=false;});this.body.emitter.on("disablePhysics",()=>{this.physicsEnabled=false;this.stopSimulation();});this.body.emitter.on("restorePhysics",()=>{this.setOptions(this.options);if(this.ready===true){this.startSimulation();}});this.body.emitter.on("startSimulation",()=>{if(this.ready===true){this.startSimulation();}});this.body.emitter.on("stopSimulation",()=>{this.stopSimulation();});this.body.emitter.on("destroy",()=>{this.stopSimulation(false);this.body.emitter.off();});this.body.emitter.on("_dataChanged",()=>{// Nodes and/or edges have been added or removed, update shortcut lists.
this.updatePhysicsData();});// debug: show forces
// this.body.emitter.on("afterDrawing", (ctx) => {this._drawForces(ctx);});
}/**
* set the physics options
*
* @param {object} options
*/setOptions(options){if(options!==undefined){if(options===false){this.options.enabled=false;this.physicsEnabled=false;this.stopSimulation();}else if(options===true){this.options.enabled=true;this.physicsEnabled=true;this.startSimulation();}else {this.physicsEnabled=true;selectiveNotDeepExtend(["stabilization"],this.options,options);mergeOptions(this.options,options,"stabilization");if(options.enabled===undefined){this.options.enabled=true;}if(this.options.enabled===false){this.physicsEnabled=false;this.stopSimulation();}const wind=this.options.wind;if(wind){if(typeof wind.x!=="number"||Number.isNaN(wind.x)){wind.x=0;}if(typeof wind.y!=="number"||Number.isNaN(wind.y)){wind.y=0;}}// set the timestep
this.timestep=this.options.timestep;}}this.init();}/**
* configure the engine.
*/init(){let options;if(this.options.solver==="forceAtlas2Based"){options=this.options.forceAtlas2Based;this.nodesSolver=new ForceAtlas2BasedRepulsionSolver(this.body,this.physicsBody,options);this.edgesSolver=new SpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new ForceAtlas2BasedCentralGravitySolver(this.body,this.physicsBody,options);}else if(this.options.solver==="repulsion"){options=this.options.repulsion;this.nodesSolver=new RepulsionSolver(this.body,this.physicsBody,options);this.edgesSolver=new SpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new CentralGravitySolver(this.body,this.physicsBody,options);}else if(this.options.solver==="hierarchicalRepulsion"){options=this.options.hierarchicalRepulsion;this.nodesSolver=new HierarchicalRepulsionSolver(this.body,this.physicsBody,options);this.edgesSolver=new HierarchicalSpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new CentralGravitySolver(this.body,this.physicsBody,options);}else {// barnesHut
options=this.options.barnesHut;this.nodesSolver=new BarnesHutSolver(this.body,this.physicsBody,options);this.edgesSolver=new SpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new CentralGravitySolver(this.body,this.physicsBody,options);}this.modelOptions=options;}/**
* initialize the engine
*/initPhysics(){if(this.physicsEnabled===true&&this.options.enabled===true){if(this.options.stabilization.enabled===true){this.stabilize();}else {this.stabilized=false;this.ready=true;this.body.emitter.emit("fit",{},this.layoutFailed);// if the layout failed, we use the approximation for the zoom
this.startSimulation();}}else {this.ready=true;this.body.emitter.emit("fit");}}/**
* Start the simulation
*/startSimulation(){if(this.physicsEnabled===true&&this.options.enabled===true){this.stabilized=false;// when visible, adaptivity is disabled.
this.adaptiveTimestep=false;// this sets the width of all nodes initially which could be required for the avoidOverlap
this.body.emitter.emit("_resizeNodes");if(this.viewFunction===undefined){this.viewFunction=this.simulationStep.bind(this);this.body.emitter.on("initRedraw",this.viewFunction);this.body.emitter.emit("_startRendering");}}else {this.body.emitter.emit("_redraw");}}/**
* Stop the simulation, force stabilization.
*
* @param {boolean} [emit=true]
*/stopSimulation(emit=true){this.stabilized=true;if(emit===true){this._emitStabilized();}if(this.viewFunction!==undefined){this.body.emitter.off("initRedraw",this.viewFunction);this.viewFunction=undefined;if(emit===true){this.body.emitter.emit("_stopRendering");}}}/**
* The viewFunction inserts this step into each render loop. It calls the physics tick and handles the cleanup at stabilized.
*
*/simulationStep(){// check if the physics have settled
const startTime=Date.now();this.physicsTick();const physicsTime=Date.now()-startTime;// run double speed if it is a little graph
if((physicsTime<0.4*this.simulationInterval||this.runDoubleSpeed===true)&&this.stabilized===false){this.physicsTick();// this makes sure there is no jitter. The decision is taken once to run it at double speed.
this.runDoubleSpeed=true;}if(this.stabilized===true){this.stopSimulation();}}/**
* trigger the stabilized event.
*
* @param {number} [amountOfIterations=this.stabilizationIterations]
* @private
*/_emitStabilized(amountOfIterations=this.stabilizationIterations){if(this.stabilizationIterations>1||this.startedStabilization===true){setTimeout(()=>{this.body.emitter.emit("stabilized",{iterations:amountOfIterations});this.startedStabilization=false;this.stabilizationIterations=0;},0);}}/**
* Calculate the forces for one physics iteration and move the nodes.
*
* @private
*/physicsStep(){this.gravitySolver.solve();this.nodesSolver.solve();this.edgesSolver.solve();this.moveNodes();}/**
* Make dynamic adjustments to the timestep, based on current state.
*
* Helper function for physicsTick().
*
* @private
*/adjustTimeStep(){const factor=1.2;// Factor for increasing the timestep on success.
// we compare the two steps. if it is acceptable we double the step.
if(this._evaluateStepQuality()===true){this.timestep=factor*this.timestep;}else {// if not, we decrease the step to a minimum of the options timestep.
// if the decreased timestep is smaller than the options step, we do not reset the counter
// we assume that the options timestep is stable enough.
if(this.timestep/factor<this.options.timestep){this.timestep=this.options.timestep;}else {// if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
// that large instabilities do not form.
this.adaptiveCounter=-1;// check again next iteration
this.timestep=Math.max(this.options.timestep,this.timestep/factor);}}}/**
* A single simulation step (or 'tick') in the physics simulation
*
* @private
*/physicsTick(){this._startStabilizing();// this ensures that there is no start event when the network is already stable.
if(this.stabilized===true)return;// adaptivity means the timestep adapts to the situation, only applicable for stabilization
if(this.adaptiveTimestep===true&&this.adaptiveTimestepEnabled===true){// timestep remains stable for "interval" iterations.
const doAdaptive=this.adaptiveCounter%this.adaptiveInterval===0;if(doAdaptive){// first the big step and revert.
this.timestep=2*this.timestep;this.physicsStep();this.revert();// saves the reference state
// now the normal step. Since this is the last step, it is the more stable one and we will take this.
this.timestep=0.5*this.timestep;// since it's half the step, we do it twice.
this.physicsStep();this.physicsStep();this.adjustTimeStep();}else {this.physicsStep();// normal step, keeping timestep constant
}this.adaptiveCounter+=1;}else {// case for the static timestep, we reset it to the one in options and take a normal step.
this.timestep=this.options.timestep;this.physicsStep();}if(this.stabilized===true)this.revert();this.stabilizationIterations++;}/**
* Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time.
*
* @private
*/updatePhysicsData(){this.physicsBody.forces={};this.physicsBody.physicsNodeIndices=[];this.physicsBody.physicsEdgeIndices=[];const nodes=this.body.nodes;const edges=this.body.edges;// get node indices for physics
for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){if(nodes[nodeId].options.physics===true){this.physicsBody.physicsNodeIndices.push(nodes[nodeId].id);}}}// get edge indices for physics
for(const edgeId in edges){if(Object.prototype.hasOwnProperty.call(edges,edgeId)){if(edges[edgeId].options.physics===true){this.physicsBody.physicsEdgeIndices.push(edges[edgeId].id);}}}// get the velocity and the forces vector
for(let i=0;i<this.physicsBody.physicsNodeIndices.length;i++){const nodeId=this.physicsBody.physicsNodeIndices[i];this.physicsBody.forces[nodeId]={x:0,y:0};// forces can be reset because they are recalculated. Velocities have to persist.
if(this.physicsBody.velocities[nodeId]===undefined){this.physicsBody.velocities[nodeId]={x:0,y:0};}}// clean deleted nodes from the velocity vector
for(const nodeId in this.physicsBody.velocities){if(nodes[nodeId]===undefined){delete this.physicsBody.velocities[nodeId];}}}/**
* Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
*/revert(){const nodeIds=Object.keys(this.previousStates);const nodes=this.body.nodes;const velocities=this.physicsBody.velocities;this.referenceState={};for(let i=0;i<nodeIds.length;i++){const nodeId=nodeIds[i];if(nodes[nodeId]!==undefined){if(nodes[nodeId].options.physics===true){this.referenceState[nodeId]={positions:{x:nodes[nodeId].x,y:nodes[nodeId].y}};velocities[nodeId].x=this.previousStates[nodeId].vx;velocities[nodeId].y=this.previousStates[nodeId].vy;nodes[nodeId].x=this.previousStates[nodeId].x;nodes[nodeId].y=this.previousStates[nodeId].y;}}else {delete this.previousStates[nodeId];}}}/**
* This compares the reference state to the current state
*
* @returns {boolean}
* @private
*/_evaluateStepQuality(){let dx,dy,dpos;const nodes=this.body.nodes;const reference=this.referenceState;const posThreshold=0.3;for(const nodeId in this.referenceState){if(Object.prototype.hasOwnProperty.call(this.referenceState,nodeId)&&nodes[nodeId]!==undefined){dx=nodes[nodeId].x-reference[nodeId].positions.x;dy=nodes[nodeId].y-reference[nodeId].positions.y;dpos=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));if(dpos>posThreshold){return false;}}}return true;}/**
* move the nodes one timestep and check if they are stabilized
*/moveNodes(){const nodeIndices=this.physicsBody.physicsNodeIndices;let maxNodeVelocity=0;let averageNodeVelocity=0;// the velocity threshold (energy in the system) for the adaptivity toggle
const velocityAdaptiveThreshold=5;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];const nodeVelocity=this._performStep(nodeId);// stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
maxNodeVelocity=Math.max(maxNodeVelocity,nodeVelocity);averageNodeVelocity+=nodeVelocity;}// evaluating the stabilized and adaptiveTimestepEnabled conditions
this.adaptiveTimestepEnabled=averageNodeVelocity/nodeIndices.length<velocityAdaptiveThreshold;this.stabilized=maxNodeVelocity<this.options.minVelocity;}/**
* Calculate new velocity for a coordinate direction
*
* @param {number} v velocity for current coordinate
* @param {number} f regular force for current coordinate
* @param {number} m mass of current node
* @returns {number} new velocity for current coordinate
* @private
*/calculateComponentVelocity(v,f,m){const df=this.modelOptions.damping*v;// damping force
const a=(f-df)/m;// acceleration
v+=a*this.timestep;// Put a limit on the velocities if it is really high
const maxV=this.options.maxVelocity||1e9;if(Math.abs(v)>maxV){v=v>0?maxV:-maxV;}return v;}/**
* Perform the actual step
*
* @param {Node.id} nodeId
* @returns {number} the new velocity of given node
* @private
*/_performStep(nodeId){const node=this.body.nodes[nodeId];const force=this.physicsBody.forces[nodeId];if(this.options.wind){force.x+=this.options.wind.x;force.y+=this.options.wind.y;}const velocity=this.physicsBody.velocities[nodeId];// store the state so we can revert
this.previousStates[nodeId]={x:node.x,y:node.y,vx:velocity.x,vy:velocity.y};if(node.options.fixed.x===false){velocity.x=this.calculateComponentVelocity(velocity.x,force.x,node.options.mass);node.x+=velocity.x*this.timestep;}else {force.x=0;velocity.x=0;}if(node.options.fixed.y===false){velocity.y=this.calculateComponentVelocity(velocity.y,force.y,node.options.mass);node.y+=velocity.y*this.timestep;}else {force.y=0;velocity.y=0;}const totalVelocity=Math.sqrt(Math.pow(velocity.x,2)+Math.pow(velocity.y,2));return totalVelocity;}/**
* When initializing and stabilizing, we can freeze nodes with a predefined position.
* This greatly speeds up stabilization because only the supportnodes for the smoothCurves have to settle.
*
* @private
*/_freezeNodes(){const nodes=this.body.nodes;for(const id in nodes){if(Object.prototype.hasOwnProperty.call(nodes,id)){if(nodes[id].x&&nodes[id].y){const fixed=nodes[id].options.fixed;this.freezeCache[id]={x:fixed.x,y:fixed.y};fixed.x=true;fixed.y=true;}}}}/**
* Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
*
* @private
*/_restoreFrozenNodes(){const nodes=this.body.nodes;for(const id in nodes){if(Object.prototype.hasOwnProperty.call(nodes,id)){if(this.freezeCache[id]!==undefined){nodes[id].options.fixed.x=this.freezeCache[id].x;nodes[id].options.fixed.y=this.freezeCache[id].y;}}}this.freezeCache={};}/**
* Find a stable position for all nodes
*
* @param {number} [iterations=this.options.stabilization.iterations]
*/stabilize(iterations=this.options.stabilization.iterations){if(typeof iterations!=="number"){iterations=this.options.stabilization.iterations;console.error("The stabilize method needs a numeric amount of iterations. Switching to default: ",iterations);}if(this.physicsBody.physicsNodeIndices.length===0){this.ready=true;return;}// enable adaptive timesteps
this.adaptiveTimestep=this.options.adaptiveTimestep;// this sets the width of all nodes initially which could be required for the avoidOverlap
this.body.emitter.emit("_resizeNodes");this.stopSimulation();// stop the render loop
this.stabilized=false;// block redraw requests
this.body.emitter.emit("_blockRedraw");this.targetIterations=iterations;// start the stabilization
if(this.options.stabilization.onlyDynamicEdges===true){this._freezeNodes();}this.stabilizationIterations=0;setTimeout(()=>this._stabilizationBatch(),0);}/**
* If not already stabilizing, start it and emit a start event.
*
* @returns {boolean} true if stabilization started with this call
* @private
*/_startStabilizing(){if(this.startedStabilization===true)return false;this.body.emitter.emit("startStabilizing");this.startedStabilization=true;return true;}/**
* One batch of stabilization
*
* @private
*/_stabilizationBatch(){const running=()=>this.stabilized===false&&this.stabilizationIterations<this.targetIterations;const sendProgress=()=>{this.body.emitter.emit("stabilizationProgress",{iterations:this.stabilizationIterations,total:this.targetIterations});};if(this._startStabilizing()){sendProgress();// Ensure that there is at least one start event.
}let count=0;while(running()&&count<this.options.stabilization.updateInterval){this.physicsTick();count++;}sendProgress();if(running()){setTimeout(this._stabilizationBatch.bind(this),0);}else {this._finalizeStabilization();}}/**
* Wrap up the stabilization, fit and emit the events.
*
* @private
*/_finalizeStabilization(){this.body.emitter.emit("_allowRedraw");if(this.options.stabilization.fit===true){this.body.emitter.emit("fit");}if(this.options.stabilization.onlyDynamicEdges===true){this._restoreFrozenNodes();}this.body.emitter.emit("stabilizationIterationsDone");this.body.emitter.emit("_requestRedraw");if(this.stabilized===true){this._emitStabilized();}else {this.startSimulation();}this.ready=true;}//--------------------------- DEBUGGING BELOW ---------------------------//
/**
* Debug function that display arrows for the forces currently active in the network.
*
* Use this when debugging only.
*
* @param {CanvasRenderingContext2D} ctx
* @private
*/_drawForces(ctx){for(let i=0;i<this.physicsBody.physicsNodeIndices.length;i++){const index=this.physicsBody.physicsNodeIndices[i];const node=this.body.nodes[index];const force=this.physicsBody.forces[index];const factor=20;const colorFactor=0.03;const forceSize=Math.sqrt(Math.pow(force.x,2)+Math.pow(force.x,2));const size=Math.min(Math.max(5,forceSize),15);const arrowSize=3*size;const color=HSVToHex((180-Math.min(1,Math.max(0,colorFactor*forceSize))*180)/360,1,1);const point={x:node.x+factor*force.x,y:node.y+factor*force.y};ctx.lineWidth=size;ctx.strokeStyle=color;ctx.beginPath();ctx.moveTo(node.x,node.y);ctx.lineTo(point.x,point.y);ctx.stroke();const angle=Math.atan2(force.y,force.x);ctx.fillStyle=color;EndPoints.draw(ctx,{type:"arrow",point:point,angle:angle,length:arrowSize});ctx.fill();}}}/**
* Utility Class
*/class NetworkUtil{/**
* @ignore
*/constructor(){}/**
* Find the center position of the network considering the bounding boxes
*
* @param {Array.<Node>} allNodes
* @param {Array.<Node>} [specificNodes=[]]
* @returns {{minX: number, maxX: number, minY: number, maxY: number}}
* @static
*/static getRange(allNodes,specificNodes=[]){let minY=1e9,maxY=-1e9,minX=1e9,maxX=-1e9,node;if(specificNodes.length>0){for(let i=0;i<specificNodes.length;i++){node=allNodes[specificNodes[i]];if(minX>node.shape.boundingBox.left){minX=node.shape.boundingBox.left;}if(maxX<node.shape.boundingBox.right){maxX=node.shape.boundingBox.right;}if(minY>node.shape.boundingBox.top){minY=node.shape.boundingBox.top;}// top is negative, bottom is positive
if(maxY<node.shape.boundingBox.bottom){maxY=node.shape.boundingBox.bottom;}// top is negative, bottom is positive
}}if(minX===1e9&&maxX===-1e9&&minY===1e9&&maxY===-1e9){minY=0,maxY=0,minX=0,maxX=0;}return {minX:minX,maxX:maxX,minY:minY,maxY:maxY};}/**
* Find the center position of the network
*
* @param {Array.<Node>} allNodes
* @param {Array.<Node>} [specificNodes=[]]
* @returns {{minX: number, maxX: number, minY: number, maxY: number}}
* @static
*/static getRangeCore(allNodes,specificNodes=[]){let minY=1e9,maxY=-1e9,minX=1e9,maxX=-1e9,node;if(specificNodes.length>0){for(let i=0;i<specificNodes.length;i++){node=allNodes[specificNodes[i]];if(minX>node.x){minX=node.x;}if(maxX<node.x){maxX=node.x;}if(minY>node.y){minY=node.y;}// top is negative, bottom is positive
if(maxY<node.y){maxY=node.y;}// top is negative, bottom is positive
}}if(minX===1e9&&maxX===-1e9&&minY===1e9&&maxY===-1e9){minY=0,maxY=0,minX=0,maxX=0;}return {minX:minX,maxX:maxX,minY:minY,maxY:maxY};}/**
* @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
* @returns {{x: number, y: number}}
* @static
*/static findCenter(range){return {x:0.5*(range.maxX+range.minX),y:0.5*(range.maxY+range.minY)};}/**
* This returns a clone of the options or options of the edge or node to be used for construction of new edges or check functions for new nodes.
*
* @param {vis.Item} item
* @param {'node'|undefined} type
* @returns {{}}
* @static
*/static cloneOptions(item,type){const clonedOptions={};if(type===undefined||type==="node"){deepExtend(clonedOptions,item.options,true);clonedOptions.x=item.x;clonedOptions.y=item.y;clonedOptions.amountOfConnections=item.edges.length;}else {deepExtend(clonedOptions,item.options,true);}return clonedOptions;}}/**
* A Cluster is a special Node that allows a group of Nodes positioned closely together
* to be represented by a single Cluster Node.
*
* @augments Node
*/class Cluster extends Node{/**
* @param {object} options
* @param {object} body
* @param {Array.<HTMLImageElement>}imagelist
* @param {Array} grouplist
* @param {object} globalOptions
* @param {object} defaultOptions Global default options for nodes
*/constructor(options,body,imagelist,grouplist,globalOptions,defaultOptions){super(options,body,imagelist,grouplist,globalOptions,defaultOptions);this.isCluster=true;this.containedNodes={};this.containedEdges={};}/**
* Transfer child cluster data to current and disconnect the child cluster.
*
* Please consult the header comment in 'Clustering.js' for the fields set here.
*
* @param {string|number} childClusterId id of child cluster to open
*/_openChildCluster(childClusterId){const childCluster=this.body.nodes[childClusterId];if(this.containedNodes[childClusterId]===undefined){throw new Error("node with id: "+childClusterId+" not in current cluster");}if(!childCluster.isCluster){throw new Error("node with id: "+childClusterId+" is not a cluster");}// Disconnect child cluster from current cluster
delete this.containedNodes[childClusterId];forEach(childCluster.edges,edge=>{delete this.containedEdges[edge.id];});// Transfer nodes and edges
forEach(childCluster.containedNodes,(node,nodeId)=>{this.containedNodes[nodeId]=node;});childCluster.containedNodes={};forEach(childCluster.containedEdges,(edge,edgeId)=>{this.containedEdges[edgeId]=edge;});childCluster.containedEdges={};// Transfer edges within cluster edges which are clustered
forEach(childCluster.edges,clusterEdge=>{forEach(this.edges,parentClusterEdge=>{// Assumption: a clustered edge can only be present in a single clustering edge
// Not tested here
const index=parentClusterEdge.clusteringEdgeReplacingIds.indexOf(clusterEdge.id);if(index===-1)return;forEach(clusterEdge.clusteringEdgeReplacingIds,srcId=>{parentClusterEdge.clusteringEdgeReplacingIds.push(srcId);// Maintain correct bookkeeping for transferred edge
this.body.edges[srcId].edgeReplacedById=parentClusterEdge.id;});// Remove cluster edge from parent cluster edge
parentClusterEdge.clusteringEdgeReplacingIds.splice(index,1);});});childCluster.edges=[];}}/* ===========================================================================
# TODO
- `edgeReplacedById` not cleaned up yet on cluster edge removal
- allowSingleNodeCluster could be a global option as well; currently needs to always
be passed to clustering methods
----------------------------------------------
# State Model for Clustering
The total state for clustering is non-trivial. It is useful to have a model
available as to how it works. The following documents the relevant state items.
## Network State
The following `network`-members are relevant to clustering:
- `body.nodes` - all nodes actively participating in the network
- `body.edges` - same for edges
- `body.nodeIndices` - id's of nodes that are visible at a given moment
- `body.edgeIndices` - same for edges
This includes:
- helper nodes for dragging in `manipulation`
- helper nodes for edge type `dynamic`
- cluster nodes and edges
- there may be more than this.
A node/edge may be missing in the `Indices` member if:
- it is a helper node
- the node or edge state has option `hidden` set
- It is not visible due to clustering
## Clustering State
For the hashes, the id's of the nodes/edges are used as key.
Member `network.clustering` contains the following items:
- `clusteredNodes` - hash with values: { clusterId: <id of cluster>, node: <node instance>}
- `clusteredEdges` - hash with values: restore information for given edge
Due to nesting of clusters, these members can contain cluster nodes and edges as well.
The important thing to note here, is that the clustered nodes and edges also
appear in the members of the cluster nodes. For data update, it is therefore
important to scan these lists as well as the cluster nodes.
### Cluster Node
A cluster node has the following extra fields:
- `isCluster : true` - indication that this is a cluster node
- `containedNodes` - hash of nodes contained in this cluster
- `containedEdges` - same for edges
- `edges` - array of cluster edges for this node
**NOTE:**
- `containedEdges` can also contain edges which are not clustered; e.g. an edge
connecting two nodes in the same cluster.
### Cluster Edge
These are the items in the `edges` member of a clustered node. They have the
following relevant members:
- 'clusteringEdgeReplacingIds` - array of id's of edges replaced by this edge
Note that it's possible to nest clusters, so that `clusteringEdgeReplacingIds`
can contain edge id's of other clusters.
### Clustered Edge
This is any edge contained by a cluster edge. It gets the following additional
member:
- `edgeReplacedById` - id of the cluster edge in which current edge is clustered
=========================================================================== */ /**
* The clustering engine
*/class ClusterEngine{/**
* @param {object} body
*/constructor(body){this.body=body;this.clusteredNodes={};// key: node id, value: { clusterId: <id of cluster>, node: <node instance>}
this.clusteredEdges={};// key: edge id, value: restore information for given edge
this.options={};this.defaultOptions={};Object.assign(this.options,this.defaultOptions);this.body.emitter.on("_resetData",()=>{this.clusteredNodes={};this.clusteredEdges={};});}/**
*
* @param {number} hubsize
* @param {object} options
*/clusterByHubsize(hubsize,options){if(hubsize===undefined){hubsize=this._getHubSize();}else if(typeof hubsize==="object"){options=this._checkOptions(hubsize);hubsize=this._getHubSize();}const nodesToCluster=[];for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];if(node.edges.length>=hubsize){nodesToCluster.push(node.id);}}for(let i=0;i<nodesToCluster.length;i++){this.clusterByConnection(nodesToCluster[i],options,true);}this.body.emitter.emit("_dataChanged");}/**
* loop over all nodes, check if they adhere to the condition and cluster if needed.
*
* @param {object} options
* @param {boolean} [refreshData=true]
*/cluster(options={},refreshData=true){if(options.joinCondition===undefined){throw new Error("Cannot call clusterByNodeData without a joinCondition function in the options.");}// check if the options object is fine, append if needed
options=this._checkOptions(options);const childNodesObj={};const childEdgesObj={};// collect the nodes that will be in the cluster
forEach(this.body.nodes,(node,nodeId)=>{if(node.options&&options.joinCondition(node.options)===true){childNodesObj[nodeId]=node;// collect the edges that will be in the cluster
forEach(node.edges,edge=>{if(this.clusteredEdges[edge.id]===undefined){childEdgesObj[edge.id]=edge;}});}});this._cluster(childNodesObj,childEdgesObj,options,refreshData);}/**
* Cluster all nodes in the network that have only X edges
*
* @param {number} edgeCount
* @param {object} options
* @param {boolean} [refreshData=true]
*/clusterByEdgeCount(edgeCount,options,refreshData=true){options=this._checkOptions(options);const clusters=[];const usedNodes={};let edge,edges,relevantEdgeCount;// collect the nodes that will be in the cluster
for(let i=0;i<this.body.nodeIndices.length;i++){const childNodesObj={};const childEdgesObj={};const nodeId=this.body.nodeIndices[i];const node=this.body.nodes[nodeId];// if this node is already used in another cluster this session, we do not have to re-evaluate it.
if(usedNodes[nodeId]===undefined){relevantEdgeCount=0;edges=[];for(let j=0;j<node.edges.length;j++){edge=node.edges[j];if(this.clusteredEdges[edge.id]===undefined){if(edge.toId!==edge.fromId){relevantEdgeCount++;}edges.push(edge);}}// this node qualifies, we collect its neighbours to start the clustering process.
if(relevantEdgeCount===edgeCount){const checkJoinCondition=function(node){if(options.joinCondition===undefined||options.joinCondition===null){return true;}const clonedOptions=NetworkUtil.cloneOptions(node);return options.joinCondition(clonedOptions);};let gatheringSuccessful=true;for(let j=0;j<edges.length;j++){edge=edges[j];const childNodeId=this._getConnectedId(edge,nodeId);// add the nodes to the list by the join condition.
if(checkJoinCondition(node)){childEdgesObj[edge.id]=edge;childNodesObj[nodeId]=node;childNodesObj[childNodeId]=this.body.nodes[childNodeId];usedNodes[nodeId]=true;}else {// this node does not qualify after all.
gatheringSuccessful=false;break;}}// add to the cluster queue
if(Object.keys(childNodesObj).length>0&&Object.keys(childEdgesObj).length>0&&gatheringSuccessful===true){/**
* Search for cluster data that contains any of the node id's
*
* @returns {boolean} true if no joinCondition, otherwise return value of joinCondition
*/const findClusterData=function(){for(let n=0;n<clusters.length;++n){// Search for a cluster containing any of the node id's
for(const m in childNodesObj){if(clusters[n].nodes[m]!==undefined){return clusters[n];}}}return undefined;};// If any of the found nodes is part of a cluster found in this method,
// add the current values to that cluster
const foundCluster=findClusterData();if(foundCluster!==undefined){// Add nodes to found cluster if not present
for(const m in childNodesObj){if(foundCluster.nodes[m]===undefined){foundCluster.nodes[m]=childNodesObj[m];}}// Add edges to found cluster, if not present
for(const m in childEdgesObj){if(foundCluster.edges[m]===undefined){foundCluster.edges[m]=childEdgesObj[m];}}}else {// Create a new cluster group
clusters.push({nodes:childNodesObj,edges:childEdgesObj});}}}}}for(let i=0;i<clusters.length;i++){this._cluster(clusters[i].nodes,clusters[i].edges,options,false);}if(refreshData===true){this.body.emitter.emit("_dataChanged");}}/**
* Cluster all nodes in the network that have only 1 edge
*
* @param {object} options
* @param {boolean} [refreshData=true]
*/clusterOutliers(options,refreshData=true){this.clusterByEdgeCount(1,options,refreshData);}/**
* Cluster all nodes in the network that have only 2 edge
*
* @param {object} options
* @param {boolean} [refreshData=true]
*/clusterBridges(options,refreshData=true){this.clusterByEdgeCount(2,options,refreshData);}/**
* suck all connected nodes of a node into the node.
*
* @param {Node.id} nodeId
* @param {object} options
* @param {boolean} [refreshData=true]
*/clusterByConnection(nodeId,options,refreshData=true){// kill conditions
if(nodeId===undefined){throw new Error("No nodeId supplied to clusterByConnection!");}if(this.body.nodes[nodeId]===undefined){throw new Error("The nodeId given to clusterByConnection does not exist!");}const node=this.body.nodes[nodeId];options=this._checkOptions(options,node);if(options.clusterNodeProperties.x===undefined){options.clusterNodeProperties.x=node.x;}if(options.clusterNodeProperties.y===undefined){options.clusterNodeProperties.y=node.y;}if(options.clusterNodeProperties.fixed===undefined){options.clusterNodeProperties.fixed={};options.clusterNodeProperties.fixed.x=node.options.fixed.x;options.clusterNodeProperties.fixed.y=node.options.fixed.y;}const childNodesObj={};const childEdgesObj={};const parentNodeId=node.id;const parentClonedOptions=NetworkUtil.cloneOptions(node);childNodesObj[parentNodeId]=node;// collect the nodes that will be in the cluster
for(let i=0;i<node.edges.length;i++){const edge=node.edges[i];if(this.clusteredEdges[edge.id]===undefined){const childNodeId=this._getConnectedId(edge,parentNodeId);// if the child node is not in a cluster
if(this.clusteredNodes[childNodeId]===undefined){if(childNodeId!==parentNodeId){if(options.joinCondition===undefined){childEdgesObj[edge.id]=edge;childNodesObj[childNodeId]=this.body.nodes[childNodeId];}else {// clone the options and insert some additional parameters that could be interesting.
const childClonedOptions=NetworkUtil.cloneOptions(this.body.nodes[childNodeId]);if(options.joinCondition(parentClonedOptions,childClonedOptions)===true){childEdgesObj[edge.id]=edge;childNodesObj[childNodeId]=this.body.nodes[childNodeId];}}}else {// swallow the edge if it is self-referencing.
childEdgesObj[edge.id]=edge;}}}}const childNodeIDs=Object.keys(childNodesObj).map(function(childNode){return childNodesObj[childNode].id;});for(const childNodeKey in childNodesObj){if(!Object.prototype.hasOwnProperty.call(childNodesObj,childNodeKey))continue;const childNode=childNodesObj[childNodeKey];for(let y=0;y<childNode.edges.length;y++){const childEdge=childNode.edges[y];if(childNodeIDs.indexOf(this._getConnectedId(childEdge,childNode.id))>-1){childEdgesObj[childEdge.id]=childEdge;}}}this._cluster(childNodesObj,childEdgesObj,options,refreshData);}/**
* This function creates the edges that will be attached to the cluster
* It looks for edges that are connected to the nodes from the "outside' of the cluster.
*
* @param {{Node.id: vis.Node}} childNodesObj
* @param {{vis.Edge.id: vis.Edge}} childEdgesObj
* @param {object} clusterNodeProperties
* @param {object} clusterEdgeProperties
* @private
*/_createClusterEdges(childNodesObj,childEdgesObj,clusterNodeProperties,clusterEdgeProperties){let edge,childNodeId,childNode,toId,fromId,otherNodeId;// loop over all child nodes and their edges to find edges going out of the cluster
// these edges will be replaced by clusterEdges.
const childKeys=Object.keys(childNodesObj);const createEdges=[];for(let i=0;i<childKeys.length;i++){childNodeId=childKeys[i];childNode=childNodesObj[childNodeId];// construct new edges from the cluster to others
for(let j=0;j<childNode.edges.length;j++){edge=childNode.edges[j];// we only handle edges that are visible to the system, not the disabled ones from the clustering process.
if(this.clusteredEdges[edge.id]===undefined){// self-referencing edges will be added to the "hidden" list
if(edge.toId==edge.fromId){childEdgesObj[edge.id]=edge;}else {// set up the from and to.
if(edge.toId==childNodeId){// this is a double equals because ints and strings can be interchanged here.
toId=clusterNodeProperties.id;fromId=edge.fromId;otherNodeId=fromId;}else {toId=edge.toId;fromId=clusterNodeProperties.id;otherNodeId=toId;}}// Only edges from the cluster outwards are being replaced.
if(childNodesObj[otherNodeId]===undefined){createEdges.push({edge:edge,fromId:fromId,toId:toId});}}}}//
// Here we actually create the replacement edges.
//
// We could not do this in the loop above as the creation process
// would add an edge to the edges array we are iterating over.
//
// NOTE: a clustered edge can have multiple base edges!
//
const newEdges=[];/**
* Find a cluster edge which matches the given created edge.
*
* @param {vis.Edge} createdEdge
* @returns {vis.Edge}
*/const getNewEdge=function(createdEdge){for(let j=0;j<newEdges.length;j++){const newEdge=newEdges[j];// We replace both to and from edges with a single cluster edge
const matchToDirection=createdEdge.fromId===newEdge.fromId&&createdEdge.toId===newEdge.toId;const matchFromDirection=createdEdge.fromId===newEdge.toId&&createdEdge.toId===newEdge.fromId;if(matchToDirection||matchFromDirection){return newEdge;}}return null;};for(let j=0;j<createEdges.length;j++){const createdEdge=createEdges[j];const edge=createdEdge.edge;let newEdge=getNewEdge(createdEdge);if(newEdge===null){// Create a clustered edge for this connection
newEdge=this._createClusteredEdge(createdEdge.fromId,createdEdge.toId,edge,clusterEdgeProperties);newEdges.push(newEdge);}else {newEdge.clusteringEdgeReplacingIds.push(edge.id);}// also reference the new edge in the old edge
this.body.edges[edge.id].edgeReplacedById=newEdge.id;// hide the replaced edge
this._backupEdgeOptions(edge);edge.setOptions({physics:false});}}/**
* This function checks the options that can be supplied to the different cluster functions
* for certain fields and inserts defaults if needed
*
* @param {object} options
* @returns {*}
* @private
*/_checkOptions(options={}){if(options.clusterEdgeProperties===undefined){options.clusterEdgeProperties={};}if(options.clusterNodeProperties===undefined){options.clusterNodeProperties={};}return options;}/**
*
* @param {object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
* @param {object} childEdgesObj | object with edge objects, id as keys
* @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
* @param {boolean} refreshData | when true, do not wrap up
* @private
*/_cluster(childNodesObj,childEdgesObj,options,refreshData=true){// Remove nodes which are already clustered
const tmpNodesToRemove=[];for(const nodeId in childNodesObj){if(Object.prototype.hasOwnProperty.call(childNodesObj,nodeId)){if(this.clusteredNodes[nodeId]!==undefined){tmpNodesToRemove.push(nodeId);}}}for(let n=0;n<tmpNodesToRemove.length;++n){delete childNodesObj[tmpNodesToRemove[n]];}// kill condition: no nodes don't bother
if(Object.keys(childNodesObj).length==0){return;}// allow clusters of 1 if options allow
if(Object.keys(childNodesObj).length==1&&options.clusterNodeProperties.allowSingleNodeCluster!=true){return;}let clusterNodeProperties=deepExtend({},options.clusterNodeProperties);// construct the clusterNodeProperties
if(options.processProperties!==undefined){// get the childNode options
const childNodesOptions=[];for(const nodeId in childNodesObj){if(Object.prototype.hasOwnProperty.call(childNodesObj,nodeId)){const clonedOptions=NetworkUtil.cloneOptions(childNodesObj[nodeId]);childNodesOptions.push(clonedOptions);}}// get cluster properties based on childNodes
const childEdgesOptions=[];for(const edgeId in childEdgesObj){if(Object.prototype.hasOwnProperty.call(childEdgesObj,edgeId)){// these cluster edges will be removed on creation of the cluster.
if(edgeId.substr(0,12)!=="clusterEdge:"){const clonedOptions=NetworkUtil.cloneOptions(childEdgesObj[edgeId],"edge");childEdgesOptions.push(clonedOptions);}}}clusterNodeProperties=options.processProperties(clusterNodeProperties,childNodesOptions,childEdgesOptions);if(!clusterNodeProperties){throw new Error("The processProperties function does not return properties!");}}// check if we have an unique id;
if(clusterNodeProperties.id===undefined){clusterNodeProperties.id="cluster:"+v4();}const clusterId=clusterNodeProperties.id;if(clusterNodeProperties.label===undefined){clusterNodeProperties.label="cluster";}// give the clusterNode a position if it does not have one.
let pos=undefined;if(clusterNodeProperties.x===undefined){pos=this._getClusterPosition(childNodesObj);clusterNodeProperties.x=pos.x;}if(clusterNodeProperties.y===undefined){if(pos===undefined){pos=this._getClusterPosition(childNodesObj);}clusterNodeProperties.y=pos.y;}// force the ID to remain the same
clusterNodeProperties.id=clusterId;// create the cluster Node
// Note that allowSingleNodeCluster, if present, is stored in the options as well
const clusterNode=this.body.functions.createNode(clusterNodeProperties,Cluster);clusterNode.containedNodes=childNodesObj;clusterNode.containedEdges=childEdgesObj;// cache a copy from the cluster edge properties if we have to reconnect others later on
clusterNode.clusterEdgeProperties=options.clusterEdgeProperties;// finally put the cluster node into global
this.body.nodes[clusterNodeProperties.id]=clusterNode;this._clusterEdges(childNodesObj,childEdgesObj,clusterNodeProperties,options.clusterEdgeProperties);// set ID to undefined so no duplicates arise
clusterNodeProperties.id=undefined;// wrap up
if(refreshData===true){this.body.emitter.emit("_dataChanged");}}/**
*
* @param {Edge} edge
* @private
*/_backupEdgeOptions(edge){if(this.clusteredEdges[edge.id]===undefined){this.clusteredEdges[edge.id]={physics:edge.options.physics};}}/**
*
* @param {Edge} edge
* @private
*/_restoreEdge(edge){const originalOptions=this.clusteredEdges[edge.id];if(originalOptions!==undefined){edge.setOptions({physics:originalOptions.physics});delete this.clusteredEdges[edge.id];}}/**
* Check if a node is a cluster.
*
* @param {Node.id} nodeId
* @returns {*}
*/isCluster(nodeId){if(this.body.nodes[nodeId]!==undefined){return this.body.nodes[nodeId].isCluster===true;}else {console.error("Node does not exist.");return false;}}/**
* get the position of the cluster node based on what's inside
*
* @param {object} childNodesObj | object with node objects, id as keys
* @returns {{x: number, y: number}}
* @private
*/_getClusterPosition(childNodesObj){const childKeys=Object.keys(childNodesObj);let minX=childNodesObj[childKeys[0]].x;let maxX=childNodesObj[childKeys[0]].x;let minY=childNodesObj[childKeys[0]].y;let maxY=childNodesObj[childKeys[0]].y;let node;for(let i=1;i<childKeys.length;i++){node=childNodesObj[childKeys[i]];minX=node.x<minX?node.x:minX;maxX=node.x>maxX?node.x:maxX;minY=node.y<minY?node.y:minY;maxY=node.y>maxY?node.y:maxY;}return {x:0.5*(minX+maxX),y:0.5*(minY+maxY)};}/**
* Open a cluster by calling this function.
*
* @param {vis.Edge.id} clusterNodeId | the ID of the cluster node
* @param {object} options
* @param {boolean} refreshData | wrap up afterwards if not true
*/openCluster(clusterNodeId,options,refreshData=true){// kill conditions
if(clusterNodeId===undefined){throw new Error("No clusterNodeId supplied to openCluster.");}const clusterNode=this.body.nodes[clusterNodeId];if(clusterNode===undefined){throw new Error("The clusterNodeId supplied to openCluster does not exist.");}if(clusterNode.isCluster!==true||clusterNode.containedNodes===undefined||clusterNode.containedEdges===undefined){throw new Error("The node:"+clusterNodeId+" is not a valid cluster.");}// Check if current cluster is clustered itself
const stack=this.findNode(clusterNodeId);const parentIndex=stack.indexOf(clusterNodeId)-1;if(parentIndex>=0){// Current cluster is clustered; transfer contained nodes and edges to parent
const parentClusterNodeId=stack[parentIndex];const parentClusterNode=this.body.nodes[parentClusterNodeId];// clustering.clusteredNodes and clustering.clusteredEdges remain unchanged
parentClusterNode._openChildCluster(clusterNodeId);// All components of child cluster node have been transferred. It can die now.
delete this.body.nodes[clusterNodeId];if(refreshData===true){this.body.emitter.emit("_dataChanged");}return;}// main body
const containedNodes=clusterNode.containedNodes;const containedEdges=clusterNode.containedEdges;// allow the user to position the nodes after release.
if(options!==undefined&&options.releaseFunction!==undefined&&typeof options.releaseFunction==="function"){const positions={};const clusterPosition={x:clusterNode.x,y:clusterNode.y};for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){const containedNode=this.body.nodes[nodeId];positions[nodeId]={x:containedNode.x,y:containedNode.y};}}const newPositions=options.releaseFunction(clusterPosition,positions);for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){const containedNode=this.body.nodes[nodeId];if(newPositions[nodeId]!==undefined){containedNode.x=newPositions[nodeId].x===undefined?clusterNode.x:newPositions[nodeId].x;containedNode.y=newPositions[nodeId].y===undefined?clusterNode.y:newPositions[nodeId].y;}}}}else {// copy the position from the cluster
forEach(containedNodes,function(containedNode){// inherit position
if(containedNode.options.fixed.x===false){containedNode.x=clusterNode.x;}if(containedNode.options.fixed.y===false){containedNode.y=clusterNode.y;}});}// release nodes
for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){const containedNode=this.body.nodes[nodeId];// inherit speed
containedNode.vx=clusterNode.vx;containedNode.vy=clusterNode.vy;containedNode.setOptions({physics:true});delete this.clusteredNodes[nodeId];}}// copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
const edgesToBeDeleted=[];for(let i=0;i<clusterNode.edges.length;i++){edgesToBeDeleted.push(clusterNode.edges[i]);}// actually handling the deleting.
for(let i=0;i<edgesToBeDeleted.length;i++){const edge=edgesToBeDeleted[i];const otherNodeId=this._getConnectedId(edge,clusterNodeId);const otherNode=this.clusteredNodes[otherNodeId];for(let j=0;j<edge.clusteringEdgeReplacingIds.length;j++){const transferId=edge.clusteringEdgeReplacingIds[j];const transferEdge=this.body.edges[transferId];if(transferEdge===undefined)continue;// if the other node is in another cluster, we transfer ownership of this edge to the other cluster
if(otherNode!==undefined){// transfer ownership:
const otherCluster=this.body.nodes[otherNode.clusterId];otherCluster.containedEdges[transferEdge.id]=transferEdge;// delete local reference
delete containedEdges[transferEdge.id];// get to and from
let fromId=transferEdge.fromId;let toId=transferEdge.toId;if(transferEdge.toId==otherNodeId){toId=otherNode.clusterId;}else {fromId=otherNode.clusterId;}// create new cluster edge from the otherCluster
this._createClusteredEdge(fromId,toId,transferEdge,otherCluster.clusterEdgeProperties,{hidden:false,physics:true});}else {this._restoreEdge(transferEdge);}}edge.remove();}// handle the releasing of the edges
for(const edgeId in containedEdges){if(Object.prototype.hasOwnProperty.call(containedEdges,edgeId)){this._restoreEdge(containedEdges[edgeId]);}}// remove clusterNode
delete this.body.nodes[clusterNodeId];if(refreshData===true){this.body.emitter.emit("_dataChanged");}}/**
*
* @param {Cluster.id} clusterId
* @returns {Array.<Node.id>}
*/getNodesInCluster(clusterId){const nodesArray=[];if(this.isCluster(clusterId)===true){const containedNodes=this.body.nodes[clusterId].containedNodes;for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){nodesArray.push(this.body.nodes[nodeId].id);}}}return nodesArray;}/**
* Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
*
* If a node can't be found in the chain, return an empty array.
*
* @param {string|number} nodeId
* @returns {Array}
*/findNode(nodeId){const stack=[];const max=100;let counter=0;let node;while(this.clusteredNodes[nodeId]!==undefined&&counter<max){node=this.body.nodes[nodeId];if(node===undefined)return [];stack.push(node.id);nodeId=this.clusteredNodes[nodeId].clusterId;counter++;}node=this.body.nodes[nodeId];if(node===undefined)return [];stack.push(node.id);stack.reverse();return stack;}/**
* Using a clustered nodeId, update with the new options
*
* @param {Node.id} clusteredNodeId
* @param {object} newOptions
*/updateClusteredNode(clusteredNodeId,newOptions){if(clusteredNodeId===undefined){throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}if(newOptions===undefined){throw new Error("No newOptions supplied to updateClusteredNode.");}if(this.body.nodes[clusteredNodeId]===undefined){throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}this.body.nodes[clusteredNodeId].setOptions(newOptions);this.body.emitter.emit("_dataChanged");}/**
* Using a base edgeId, update all related clustered edges with the new options
*
* @param {vis.Edge.id} startEdgeId
* @param {object} newOptions
*/updateEdge(startEdgeId,newOptions){if(startEdgeId===undefined){throw new Error("No startEdgeId supplied to updateEdge.");}if(newOptions===undefined){throw new Error("No newOptions supplied to updateEdge.");}if(this.body.edges[startEdgeId]===undefined){throw new Error("The startEdgeId supplied to updateEdge does not exist.");}const allEdgeIds=this.getClusteredEdges(startEdgeId);for(let i=0;i<allEdgeIds.length;i++){const edge=this.body.edges[allEdgeIds[i]];edge.setOptions(newOptions);}this.body.emitter.emit("_dataChanged");}/**
* Get a stack of clusterEdgeId's (+base edgeid) that a base edge is the same as. cluster edge C -> cluster edge B -> cluster edge A -> base edge(edgeId)
*
* @param {vis.Edge.id} edgeId
* @returns {Array.<vis.Edge.id>}
*/getClusteredEdges(edgeId){const stack=[];const max=100;let counter=0;while(edgeId!==undefined&&this.body.edges[edgeId]!==undefined&&counter<max){stack.push(this.body.edges[edgeId].id);edgeId=this.body.edges[edgeId].edgeReplacedById;counter++;}stack.reverse();return stack;}/**
* Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
*
* @param {vis.Edge.id} clusteredEdgeId
* @returns {vis.Edge.id} baseEdgeId
*
* TODO: deprecate in 5.0.0. Method getBaseEdges() is the correct one to use.
*/getBaseEdge(clusteredEdgeId){// Just kludge this by returning the first base edge id found
return this.getBaseEdges(clusteredEdgeId)[0];}/**
* Get all regular edges for this clustered edge id.
*
* @param {vis.Edge.id} clusteredEdgeId
* @returns {Array.<vis.Edge.id>} all baseEdgeId's under this clustered edge
*/getBaseEdges(clusteredEdgeId){const IdsToHandle=[clusteredEdgeId];const doneIds=[];const foundIds=[];const max=100;let counter=0;while(IdsToHandle.length>0&&counter<max){const nextId=IdsToHandle.pop();if(nextId===undefined)continue;// Paranoia here and onwards
const nextEdge=this.body.edges[nextId];if(nextEdge===undefined)continue;counter++;const replacingIds=nextEdge.clusteringEdgeReplacingIds;if(replacingIds===undefined){// nextId is a base id
foundIds.push(nextId);}else {// Another cluster edge, unravel this one as well
for(let i=0;i<replacingIds.length;++i){const replacingId=replacingIds[i];// Don't add if already handled
// TODO: never triggers; find a test-case which does
if(IdsToHandle.indexOf(replacingIds)!==-1||doneIds.indexOf(replacingIds)!==-1){continue;}IdsToHandle.push(replacingId);}}doneIds.push(nextId);}return foundIds;}/**
* Get the Id the node is connected to
*
* @param {vis.Edge} edge
* @param {Node.id} nodeId
* @returns {*}
* @private
*/_getConnectedId(edge,nodeId){if(edge.toId!=nodeId){return edge.toId;}else if(edge.fromId!=nodeId){return edge.fromId;}else {return edge.fromId;}}/**
* We determine how many connections denote an important hub.
* We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
*
* @returns {number}
* @private
*/_getHubSize(){let average=0;let averageSquared=0;let hubCounter=0;let largestHub=0;for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];if(node.edges.length>largestHub){largestHub=node.edges.length;}average+=node.edges.length;averageSquared+=Math.pow(node.edges.length,2);hubCounter+=1;}average=average/hubCounter;averageSquared=averageSquared/hubCounter;const variance=averageSquared-Math.pow(average,2);const standardDeviation=Math.sqrt(variance);let hubThreshold=Math.floor(average+2*standardDeviation);// always have at least one to cluster
if(hubThreshold>largestHub){hubThreshold=largestHub;}return hubThreshold;}/**
* Create an edge for the cluster representation.
*
* @param {Node.id} fromId
* @param {Node.id} toId
* @param {vis.Edge} baseEdge
* @param {object} clusterEdgeProperties
* @param {object} extraOptions
* @returns {Edge} newly created clustered edge
* @private
*/_createClusteredEdge(fromId,toId,baseEdge,clusterEdgeProperties,extraOptions){// copy the options of the edge we will replace
const clonedOptions=NetworkUtil.cloneOptions(baseEdge,"edge");// make sure the properties of clusterEdges are superimposed on it
deepExtend(clonedOptions,clusterEdgeProperties);// set up the edge
clonedOptions.from=fromId;clonedOptions.to=toId;clonedOptions.id="clusterEdge:"+v4();// apply the edge specific options to it if specified
if(extraOptions!==undefined){deepExtend(clonedOptions,extraOptions);}const newEdge=this.body.functions.createEdge(clonedOptions);newEdge.clusteringEdgeReplacingIds=[baseEdge.id];newEdge.connect();// Register the new edge
this.body.edges[newEdge.id]=newEdge;return newEdge;}/**
* Add the passed child nodes and edges to the given cluster node.
*
* @param {object | Node} childNodes hash of nodes or single node to add in cluster
* @param {object | Edge} childEdges hash of edges or single edge to take into account when clustering
* @param {Node} clusterNode cluster node to add nodes and edges to
* @param {object} [clusterEdgeProperties]
* @private
*/_clusterEdges(childNodes,childEdges,clusterNode,clusterEdgeProperties){if(childEdges instanceof Edge){const edge=childEdges;const obj={};obj[edge.id]=edge;childEdges=obj;}if(childNodes instanceof Node){const node=childNodes;const obj={};obj[node.id]=node;childNodes=obj;}if(clusterNode===undefined||clusterNode===null){throw new Error("_clusterEdges: parameter clusterNode required");}if(clusterEdgeProperties===undefined){// Take the required properties from the cluster node
clusterEdgeProperties=clusterNode.clusterEdgeProperties;}// create the new edges that will connect to the cluster.
// All self-referencing edges will be added to childEdges here.
this._createClusterEdges(childNodes,childEdges,clusterNode,clusterEdgeProperties);// disable the childEdges
for(const edgeId in childEdges){if(Object.prototype.hasOwnProperty.call(childEdges,edgeId)){if(this.body.edges[edgeId]!==undefined){const edge=this.body.edges[edgeId];// cache the options before changing
this._backupEdgeOptions(edge);// disable physics and hide the edge
edge.setOptions({physics:false});}}}// disable the childNodes
for(const nodeId in childNodes){if(Object.prototype.hasOwnProperty.call(childNodes,nodeId)){this.clusteredNodes[nodeId]={clusterId:clusterNode.id,node:this.body.nodes[nodeId]};this.body.nodes[nodeId].setOptions({physics:false});}}}/**
* Determine in which cluster given nodeId resides.
*
* If not in cluster, return undefined.
*
* NOTE: If you know a cleaner way to do this, please enlighten me (wimrijnders).
*
* @param {Node.id} nodeId
* @returns {Node|undefined} Node instance for cluster, if present
* @private
*/_getClusterNodeForNode(nodeId){if(nodeId===undefined)return undefined;const clusteredNode=this.clusteredNodes[nodeId];// NOTE: If no cluster info found, it should actually be an error
if(clusteredNode===undefined)return undefined;const clusterId=clusteredNode.clusterId;if(clusterId===undefined)return undefined;return this.body.nodes[clusterId];}/**
* Internal helper function for conditionally removing items in array
*
* Done like this because Array.filter() is not fully supported by all IE's.
*
* @param {Array} arr
* @param {Function} callback
* @returns {Array}
* @private
*/_filter(arr,callback){const ret=[];forEach(arr,item=>{if(callback(item)){ret.push(item);}});return ret;}/**
* Scan all edges for changes in clustering and adjust this if necessary.
*
* Call this (internally) after there has been a change in node or edge data.
*
* Pre: States of this.body.nodes and this.body.edges consistent
* Pre: this.clusteredNodes and this.clusteredEdge consistent with containedNodes and containedEdges
* of cluster nodes.
*/_updateState(){let nodeId;const deletedNodeIds=[];const deletedEdgeIds={};/**
* Utility function to iterate over clustering nodes only
*
* @param {Function} callback function to call for each cluster node
*/const eachClusterNode=callback=>{forEach(this.body.nodes,node=>{if(node.isCluster===true){callback(node);}});};//
// Remove deleted regular nodes from clustering
//
// Determine the deleted nodes
for(nodeId in this.clusteredNodes){if(!Object.prototype.hasOwnProperty.call(this.clusteredNodes,nodeId))continue;const node=this.body.nodes[nodeId];if(node===undefined){deletedNodeIds.push(nodeId);}}// Remove nodes from cluster nodes
eachClusterNode(function(clusterNode){for(let n=0;n<deletedNodeIds.length;n++){delete clusterNode.containedNodes[deletedNodeIds[n]];}});// Remove nodes from cluster list
for(let n=0;n<deletedNodeIds.length;n++){delete this.clusteredNodes[deletedNodeIds[n]];}//
// Remove deleted edges from clustering
//
// Add the deleted clustered edges to the list
forEach(this.clusteredEdges,edgeId=>{const edge=this.body.edges[edgeId];if(edge===undefined||!edge.endPointsValid()){deletedEdgeIds[edgeId]=edgeId;}});// Cluster nodes can also contain edges which are not clustered,
// i.e. nodes 1-2 within cluster with an edge in between.
// So the cluster nodes also need to be scanned for invalid edges
eachClusterNode(function(clusterNode){forEach(clusterNode.containedEdges,(edge,edgeId)=>{if(!edge.endPointsValid()&&!deletedEdgeIds[edgeId]){deletedEdgeIds[edgeId]=edgeId;}});});// Also scan for cluster edges which need to be removed in the active list.
// Regular edges have been removed beforehand, so this only picks up the cluster edges.
forEach(this.body.edges,(edge,edgeId)=>{// Explicitly scan the contained edges for validity
let isValid=true;const replacedIds=edge.clusteringEdgeReplacingIds;if(replacedIds!==undefined){let numValid=0;forEach(replacedIds,containedEdgeId=>{const containedEdge=this.body.edges[containedEdgeId];if(containedEdge!==undefined&&containedEdge.endPointsValid()){numValid+=1;}});isValid=numValid>0;}if(!edge.endPointsValid()||!isValid){deletedEdgeIds[edgeId]=edgeId;}});// Remove edges from cluster nodes
eachClusterNode(clusterNode=>{forEach(deletedEdgeIds,deletedEdgeId=>{delete clusterNode.containedEdges[deletedEdgeId];forEach(clusterNode.edges,(edge,m)=>{if(edge.id===deletedEdgeId){clusterNode.edges[m]=null;// Don't want to directly delete here, because in the loop
return;}edge.clusteringEdgeReplacingIds=this._filter(edge.clusteringEdgeReplacingIds,function(id){return !deletedEdgeIds[id];});});// Clean up the nulls
clusterNode.edges=this._filter(clusterNode.edges,function(item){return item!==null;});});});// Remove from cluster list
forEach(deletedEdgeIds,edgeId=>{delete this.clusteredEdges[edgeId];});// Remove cluster edges from active list (this.body.edges).
// deletedEdgeIds still contains id of regular edges, but these should all
// be gone when you reach here.
forEach(deletedEdgeIds,edgeId=>{delete this.body.edges[edgeId];});//
// Check changed cluster state of edges
//
// Iterating over keys here, because edges may be removed in the loop
const ids=Object.keys(this.body.edges);forEach(ids,edgeId=>{const edge=this.body.edges[edgeId];const shouldBeClustered=this._isClusteredNode(edge.fromId)||this._isClusteredNode(edge.toId);if(shouldBeClustered===this._isClusteredEdge(edge.id)){return;// all is well
}if(shouldBeClustered){// add edge to clustering
const clusterFrom=this._getClusterNodeForNode(edge.fromId);if(clusterFrom!==undefined){this._clusterEdges(this.body.nodes[edge.fromId],edge,clusterFrom);}const clusterTo=this._getClusterNodeForNode(edge.toId);if(clusterTo!==undefined){this._clusterEdges(this.body.nodes[edge.toId],edge,clusterTo);}// TODO: check that it works for both edges clustered
// (This might be paranoia)
}else {delete this._clusterEdges[edgeId];this._restoreEdge(edge);// This should not be happening, the state should
// be properly updated at this point.
//
// If it *is* reached during normal operation, then we have to implement
// undo clustering for this edge here.
// throw new Error('remove edge from clustering not implemented!')
}});// Clusters may be nested to any level. Keep on opening until nothing to open
let changed=false;let continueLoop=true;while(continueLoop){const clustersToOpen=[];// Determine the id's of clusters that need opening
eachClusterNode(function(clusterNode){const numNodes=Object.keys(clusterNode.containedNodes).length;const allowSingle=clusterNode.options.allowSingleNodeCluster===true;if(allowSingle&&numNodes<1||!allowSingle&&numNodes<2){clustersToOpen.push(clusterNode.id);}});// Open them
for(let n=0;n<clustersToOpen.length;++n){this.openCluster(clustersToOpen[n],{},false/* Don't refresh, we're in an refresh/update already */);}continueLoop=clustersToOpen.length>0;changed=changed||continueLoop;}if(changed){this._updateState();// Redo this method (recursion possible! should be safe)
}}/**
* Determine if node with given id is part of a cluster.
*
* @param {Node.id} nodeId
* @returns {boolean} true if part of a cluster.
*/_isClusteredNode(nodeId){return this.clusteredNodes[nodeId]!==undefined;}/**
* Determine if edge with given id is not visible due to clustering.
*
* An edge is considered clustered if:
* - it is directly replaced by a clustering edge
* - any of its connecting nodes is in a cluster
*
* @param {vis.Edge.id} edgeId
* @returns {boolean} true if part of a cluster.
*/_isClusteredEdge(edgeId){return this.clusteredEdges[edgeId]!==undefined;}}/**
* Initializes window.requestAnimationFrame() to a usable form.
*
* Specifically, set up this method for the case of running on node.js with jsdom enabled.
*
* NOTES:
*
* On node.js, when calling this directly outside of this class, `window` is not defined.
* This happens even if jsdom is used.
* For node.js + jsdom, `window` is available at the moment the constructor is called.
* For this reason, the called is placed within the constructor.
* Even then, `window.requestAnimationFrame()` is not defined, so it still needs to be added.
* During unit testing, it happens that the window object is reset during execution, causing
* a runtime error due to missing `requestAnimationFrame()`. This needs to be compensated for,
* see `_requestNextFrame()`.
* Since this is a global object, it may affect other modules besides `Network`. With normal
* usage, this does not cause any problems. During unit testing, errors may occur. These have
* been compensated for, see comment block in _requestNextFrame().
*
* @private
*/function _initRequestAnimationFrame(){let func;if(window!==undefined){func=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame;}if(func===undefined){// window or method not present, setting mock requestAnimationFrame
window.requestAnimationFrame=function(callback){//console.log("Called mock requestAnimationFrame");
callback();};}else {window.requestAnimationFrame=func;}}/**
* The canvas renderer
*/class CanvasRenderer{/**
* @param {object} body
* @param {Canvas} canvas
*/constructor(body,canvas){_initRequestAnimationFrame();this.body=body;this.canvas=canvas;this.redrawRequested=false;this.renderTimer=undefined;this.requiresTimeout=true;this.renderingActive=false;this.renderRequests=0;this.allowRedraw=true;this.dragging=false;this.zooming=false;this.options={};this.defaultOptions={hideEdgesOnDrag:false,hideEdgesOnZoom:false,hideNodesOnDrag:false};Object.assign(this.options,this.defaultOptions);this._determineBrowserMethod();this.bindEventListeners();}/**
* Binds event listeners
*/bindEventListeners(){this.body.emitter.on("dragStart",()=>{this.dragging=true;});this.body.emitter.on("dragEnd",()=>{this.dragging=false;});this.body.emitter.on("zoom",()=>{this.zooming=true;window.clearTimeout(this.zoomTimeoutId);this.zoomTimeoutId=window.setTimeout(()=>{this.zooming=false;this._requestRedraw.bind(this)();},250);});this.body.emitter.on("_resizeNodes",()=>{this._resizeNodes();});this.body.emitter.on("_redraw",()=>{if(this.renderingActive===false){this._redraw();}});this.body.emitter.on("_blockRedraw",()=>{this.allowRedraw=false;});this.body.emitter.on("_allowRedraw",()=>{this.allowRedraw=true;this.redrawRequested=false;});this.body.emitter.on("_requestRedraw",this._requestRedraw.bind(this));this.body.emitter.on("_startRendering",()=>{this.renderRequests+=1;this.renderingActive=true;this._startRendering();});this.body.emitter.on("_stopRendering",()=>{this.renderRequests-=1;this.renderingActive=this.renderRequests>0;this.renderTimer=undefined;});this.body.emitter.on("destroy",()=>{this.renderRequests=0;this.allowRedraw=false;this.renderingActive=false;if(this.requiresTimeout===true){clearTimeout(this.renderTimer);}else {window.cancelAnimationFrame(this.renderTimer);}this.body.emitter.off();});}/**
*
* @param {object} options
*/setOptions(options){if(options!==undefined){const fields=["hideEdgesOnDrag","hideEdgesOnZoom","hideNodesOnDrag"];selectiveDeepExtend(fields,this.options,options);}}/**
* Prepare the drawing of the next frame.
*
* Calls the callback when the next frame can or will be drawn.
*
* @param {Function} callback
* @param {number} delay - timeout case only, wait this number of milliseconds
* @returns {Function | undefined}
* @private
*/_requestNextFrame(callback,delay){// During unit testing, it happens that the mock window object is reset while
// the next frame is still pending. Then, either 'window' is not present, or
// 'requestAnimationFrame()' is not present because it is not defined on the
// mock window object.
//
// As a consequence, unrelated unit tests may appear to fail, even if the problem
// described happens in the current unit test.
//
// This is not something that will happen in normal operation, but we still need
// to take it into account.
//
if(typeof window==="undefined")return;// Doing `if (window === undefined)` does not work here!
let timer;const myWindow=window;// Grab a reference to reduce the possibility that 'window' is reset
// while running this method.
if(this.requiresTimeout===true){// wait given number of milliseconds and perform the animation step function
timer=myWindow.setTimeout(callback,delay);}else {if(myWindow.requestAnimationFrame){timer=myWindow.requestAnimationFrame(callback);}}return timer;}/**
*
* @private
*/_startRendering(){if(this.renderingActive===true){if(this.renderTimer===undefined){this.renderTimer=this._requestNextFrame(this._renderStep.bind(this),this.simulationInterval);}}}/**
*
* @private
*/_renderStep(){if(this.renderingActive===true){// reset the renderTimer so a new scheduled animation step can be set
this.renderTimer=undefined;if(this.requiresTimeout===true){// this schedules a new simulation step
this._startRendering();}this._redraw();if(this.requiresTimeout===false){// this schedules a new simulation step
this._startRendering();}}}/**
* Redraw the network with the current data
* chart will be resized too.
*/redraw(){this.body.emitter.emit("setSize");this._redraw();}/**
* Redraw the network with the current data
*
* @private
*/_requestRedraw(){if(this.redrawRequested!==true&&this.renderingActive===false&&this.allowRedraw===true){this.redrawRequested=true;this._requestNextFrame(()=>{this._redraw(false);},0);}}/**
* Redraw the network with the current data
*
* @param {boolean} [hidden=false] | Used to get the first estimate of the node sizes.
* Only the nodes are drawn after which they are quickly drawn over.
* @private
*/_redraw(hidden=false){if(this.allowRedraw===true){this.body.emitter.emit("initRedraw");this.redrawRequested=false;const drawLater={drawExternalLabels:null};// when the container div was hidden, this fixes it back up!
if(this.canvas.frame.canvas.width===0||this.canvas.frame.canvas.height===0){this.canvas.setSize();}this.canvas.setTransform();const ctx=this.canvas.getContext();// clear the canvas
const w=this.canvas.frame.canvas.clientWidth;const h=this.canvas.frame.canvas.clientHeight;ctx.clearRect(0,0,w,h);// if the div is hidden, we stop the redraw here for performance.
if(this.canvas.frame.clientWidth===0){return;}// set scaling and translation
ctx.save();ctx.translate(this.body.view.translation.x,this.body.view.translation.y);ctx.scale(this.body.view.scale,this.body.view.scale);ctx.beginPath();this.body.emitter.emit("beforeDrawing",ctx);ctx.closePath();if(hidden===false){if((this.dragging===false||this.dragging===true&&this.options.hideEdgesOnDrag===false)&&(this.zooming===false||this.zooming===true&&this.options.hideEdgesOnZoom===false)){this._drawEdges(ctx);}}if(this.dragging===false||this.dragging===true&&this.options.hideNodesOnDrag===false){const{drawExternalLabels}=this._drawNodes(ctx,hidden);drawLater.drawExternalLabels=drawExternalLabels;}// draw the arrows last so they will be at the top
if(hidden===false){if((this.dragging===false||this.dragging===true&&this.options.hideEdgesOnDrag===false)&&(this.zooming===false||this.zooming===true&&this.options.hideEdgesOnZoom===false)){this._drawArrows(ctx);}}if(drawLater.drawExternalLabels!=null){drawLater.drawExternalLabels();}if(hidden===false){this._drawSelectionBox(ctx);}ctx.beginPath();this.body.emitter.emit("afterDrawing",ctx);ctx.closePath();// restore original scaling and translation
ctx.restore();if(hidden===true){ctx.clearRect(0,0,w,h);}}}/**
* Redraw all nodes
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [alwaysShow]
* @private
*/_resizeNodes(){this.canvas.setTransform();const ctx=this.canvas.getContext();ctx.save();ctx.translate(this.body.view.translation.x,this.body.view.translation.y);ctx.scale(this.body.view.scale,this.body.view.scale);const nodes=this.body.nodes;let node;// resize all nodes
for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){node=nodes[nodeId];node.resize(ctx);node.updateBoundingBox(ctx,node.selected);}}// restore original scaling and translation
ctx.restore();}/**
* Redraw all nodes
*
* @param {CanvasRenderingContext2D} ctx 2D context of a HTML canvas
* @param {boolean} [alwaysShow]
* @private
* @returns {object} Callbacks to draw later on higher layers.
*/_drawNodes(ctx,alwaysShow=false){const nodes=this.body.nodes;const nodeIndices=this.body.nodeIndices;let node;const selected=[];const hovered=[];const margin=20;const topLeft=this.canvas.DOMtoCanvas({x:-margin,y:-margin});const bottomRight=this.canvas.DOMtoCanvas({x:this.canvas.frame.canvas.clientWidth+margin,y:this.canvas.frame.canvas.clientHeight+margin});const viewableArea={top:topLeft.y,left:topLeft.x,bottom:bottomRight.y,right:bottomRight.x};const drawExternalLabels=[];// draw unselected nodes;
for(let i=0;i<nodeIndices.length;i++){node=nodes[nodeIndices[i]];// set selected and hovered nodes aside
if(node.hover){hovered.push(nodeIndices[i]);}else if(node.isSelected()){selected.push(nodeIndices[i]);}else {if(alwaysShow===true){const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}else if(node.isBoundingBoxOverlappingWith(viewableArea)===true){const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}else {node.updateBoundingBox(ctx,node.selected);}}}let i;const selectedLength=selected.length;const hoveredLength=hovered.length;// draw the selected nodes on top
for(i=0;i<selectedLength;i++){node=nodes[selected[i]];const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}// draw hovered nodes above everything else: fixes https://github.com/visjs/vis-network/issues/226
for(i=0;i<hoveredLength;i++){node=nodes[hovered[i]];const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}return {drawExternalLabels:()=>{for(const draw of drawExternalLabels){draw();}}};}/**
* Redraw all edges
*
* @param {CanvasRenderingContext2D} ctx 2D context of a HTML canvas
* @private
*/_drawEdges(ctx){const edges=this.body.edges;const edgeIndices=this.body.edgeIndices;for(let i=0;i<edgeIndices.length;i++){const edge=edges[edgeIndices[i]];if(edge.connected===true){edge.draw(ctx);}}}/**
* Redraw all arrows
*
* @param {CanvasRenderingContext2D} ctx 2D context of a HTML canvas
* @private
*/_drawArrows(ctx){const edges=this.body.edges;const edgeIndices=this.body.edgeIndices;for(let i=0;i<edgeIndices.length;i++){const edge=edges[edgeIndices[i]];if(edge.connected===true){edge.drawArrows(ctx);}}}/**
* Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because
* some implementations (safari and IE9) did not support requestAnimationFrame
*
* @private
*/_determineBrowserMethod(){if(typeof window!=="undefined"){const browserType=navigator.userAgent.toLowerCase();this.requiresTimeout=false;if(browserType.indexOf("msie 9.0")!=-1){// IE 9
this.requiresTimeout=true;}else if(browserType.indexOf("safari")!=-1){// safari
if(browserType.indexOf("chrome")<=-1){this.requiresTimeout=true;}}}else {this.requiresTimeout=true;}}/**
* Redraw selection box
*
* @param {CanvasRenderingContext2D} ctx 2D context of a HTML canvas
* @private
*/_drawSelectionBox(ctx){if(this.body.selectionBox.show){ctx.beginPath();const width=this.body.selectionBox.position.end.x-this.body.selectionBox.position.start.x;const height=this.body.selectionBox.position.end.y-this.body.selectionBox.position.start.y;ctx.rect(this.body.selectionBox.position.start.x,this.body.selectionBox.position.start.y,width,height);ctx.fillStyle="rgba(151, 194, 252, 0.2)";ctx.fillRect(this.body.selectionBox.position.start.x,this.body.selectionBox.position.start.y,width,height);ctx.strokeStyle="rgba(151, 194, 252, 1)";ctx.stroke();}else {ctx.closePath();}}}/**
* Register a touch event, taking place before a gesture
*
* @param {Hammer} hammer A hammer instance
* @param {Function} callback Callback, called as callback(event)
*/function onTouch(hammer,callback){callback.inputHandler=function(event){if(event.isFirst){callback(event);}};hammer.on("hammer.input",callback.inputHandler);}/**
* Register a release event, taking place after a gesture
*
* @param {Hammer} hammer A hammer instance
* @param {Function} callback Callback, called as callback(event)
* @returns {*}
*/function onRelease(hammer,callback){callback.inputHandler=function(event){if(event.isFinal){callback(event);}};return hammer.on("hammer.input",callback.inputHandler);}/**
* Create the main frame for the Network.
* This function is executed once when a Network object is created. The frame
* contains a canvas, and this canvas contains all objects like the axis and
* nodes.
*/class Canvas{/**
* @param {object} body
*/constructor(body){this.body=body;this.pixelRatio=1;this.cameraState={};this.initialized=false;this.canvasViewCenter={};this._cleanupCallbacks=[];this.options={};this.defaultOptions={autoResize:true,height:"100%",width:"100%"};Object.assign(this.options,this.defaultOptions);this.bindEventListeners();}/**
* Binds event listeners
*/bindEventListeners(){// bind the events
this.body.emitter.once("resize",obj=>{if(obj.width!==0){this.body.view.translation.x=obj.width*0.5;}if(obj.height!==0){this.body.view.translation.y=obj.height*0.5;}});this.body.emitter.on("setSize",this.setSize.bind(this));this.body.emitter.on("destroy",()=>{this.hammerFrame.destroy();this.hammer.destroy();this._cleanUp();});}/**
* @param {object} options
*/setOptions(options){if(options!==undefined){const fields=["width","height","autoResize"];selectiveDeepExtend(fields,this.options,options);}// Automatically adapt to changing size of the container element.
this._cleanUp();if(this.options.autoResize===true){if(window.ResizeObserver){// decent browsers, immediate reactions
const observer=new ResizeObserver(()=>{const changed=this.setSize();if(changed===true){this.body.emitter.emit("_requestRedraw");}});const{frame}=this;observer.observe(frame);this._cleanupCallbacks.push(()=>{observer.unobserve(frame);});}else {// IE11, continous polling
const resizeTimer=setInterval(()=>{const changed=this.setSize();if(changed===true){this.body.emitter.emit("_requestRedraw");}},1000);this._cleanupCallbacks.push(()=>{clearInterval(resizeTimer);});}// Automatically adapt to changing size of the browser.
const resizeFunction=this._onResize.bind(this);window.addEventListener("resize",resizeFunction);this._cleanupCallbacks.push(()=>{window.removeEventListener("resize",resizeFunction);});}}/**
* @private
*/_cleanUp(){this._cleanupCallbacks.splice(0).reverse().forEach(callback=>{try{callback();}catch(error){console.error(error);}});}/**
* @private
*/_onResize(){this.setSize();this.body.emitter.emit("_redraw");}/**
* Get and store the cameraState
*
* @param {number} [pixelRatio=this.pixelRatio]
* @private
*/_getCameraState(pixelRatio=this.pixelRatio){if(this.initialized===true){this.cameraState.previousWidth=this.frame.canvas.width/pixelRatio;this.cameraState.previousHeight=this.frame.canvas.height/pixelRatio;this.cameraState.scale=this.body.view.scale;this.cameraState.position=this.DOMtoCanvas({x:0.5*this.frame.canvas.width/pixelRatio,y:0.5*this.frame.canvas.height/pixelRatio});}}/**
* Set the cameraState
*
* @private
*/_setCameraState(){if(this.cameraState.scale!==undefined&&this.frame.canvas.clientWidth!==0&&this.frame.canvas.clientHeight!==0&&this.pixelRatio!==0&&this.cameraState.previousWidth>0&&this.cameraState.previousHeight>0){const widthRatio=this.frame.canvas.width/this.pixelRatio/this.cameraState.previousWidth;const heightRatio=this.frame.canvas.height/this.pixelRatio/this.cameraState.previousHeight;let newScale=this.cameraState.scale;if(widthRatio!=1&&heightRatio!=1){newScale=this.cameraState.scale*0.5*(widthRatio+heightRatio);}else if(widthRatio!=1){newScale=this.cameraState.scale*widthRatio;}else if(heightRatio!=1){newScale=this.cameraState.scale*heightRatio;}this.body.view.scale=newScale;// this comes from the view module.
const currentViewCenter=this.DOMtoCanvas({x:0.5*this.frame.canvas.clientWidth,y:0.5*this.frame.canvas.clientHeight});const distanceFromCenter={// offset from view, distance view has to change by these x and y to center the node
x:currentViewCenter.x-this.cameraState.position.x,y:currentViewCenter.y-this.cameraState.position.y};this.body.view.translation.x+=distanceFromCenter.x*this.body.view.scale;this.body.view.translation.y+=distanceFromCenter.y*this.body.view.scale;}}/**
*
* @param {number|string} value
* @returns {string}
* @private
*/_prepareValue(value){if(typeof value==="number"){return value+"px";}else if(typeof value==="string"){if(value.indexOf("%")!==-1||value.indexOf("px")!==-1){return value;}else if(value.indexOf("%")===-1){return value+"px";}}throw new Error("Could not use the value supplied for width or height:"+value);}/**
* Create the HTML
*/_create(){// remove all elements from the container element.
while(this.body.container.hasChildNodes()){this.body.container.removeChild(this.body.container.firstChild);}this.frame=document.createElement("div");this.frame.className="vis-network";this.frame.style.position="relative";this.frame.style.overflow="hidden";this.frame.tabIndex=0;// tab index is required for keycharm to bind keystrokes to the div instead of the window
//////////////////////////////////////////////////////////////////
this.frame.canvas=document.createElement("canvas");this.frame.canvas.style.position="relative";this.frame.appendChild(this.frame.canvas);if(!this.frame.canvas.getContext){const noCanvas=document.createElement("DIV");noCanvas.style.color="red";noCanvas.style.fontWeight="bold";noCanvas.style.padding="10px";noCanvas.innerText="Error: your browser does not support HTML canvas";this.frame.canvas.appendChild(noCanvas);}else {this._setPixelRatio();this.setTransform();}// add the frame to the container element
this.body.container.appendChild(this.frame);this.body.view.scale=1;this.body.view.translation={x:0.5*this.frame.canvas.clientWidth,y:0.5*this.frame.canvas.clientHeight};this._bindHammer();}/**
* This function binds hammer, it can be repeated over and over due to the uniqueness check.
*
* @private
*/_bindHammer(){if(this.hammer!==undefined){this.hammer.destroy();}this.drag={};this.pinch={};// init hammer
this.hammer=new Hammer$2(this.frame.canvas);this.hammer.get("pinch").set({enable:true});// enable to get better response, todo: test on mobile.
this.hammer.get("pan").set({threshold:5,direction:Hammer$2.DIRECTION_ALL});onTouch(this.hammer,event=>{this.body.eventListeners.onTouch(event);});this.hammer.on("tap",event=>{this.body.eventListeners.onTap(event);});this.hammer.on("doubletap",event=>{this.body.eventListeners.onDoubleTap(event);});this.hammer.on("press",event=>{this.body.eventListeners.onHold(event);});this.hammer.on("panstart",event=>{this.body.eventListeners.onDragStart(event);});this.hammer.on("panmove",event=>{this.body.eventListeners.onDrag(event);});this.hammer.on("panend",event=>{this.body.eventListeners.onDragEnd(event);});this.hammer.on("pinch",event=>{this.body.eventListeners.onPinch(event);});// TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work?
this.frame.canvas.addEventListener("wheel",event=>{this.body.eventListeners.onMouseWheel(event);});this.frame.canvas.addEventListener("mousemove",event=>{this.body.eventListeners.onMouseMove(event);});this.frame.canvas.addEventListener("contextmenu",event=>{this.body.eventListeners.onContext(event);});this.hammerFrame=new Hammer$2(this.frame);onRelease(this.hammerFrame,event=>{this.body.eventListeners.onRelease(event);});}/**
* Set a new size for the network
*
* @param {string} width Width in pixels or percentage (for example '800px'
* or '50%')
* @param {string} height Height in pixels or percentage (for example '400px'
* or '30%')
* @returns {boolean}
*/setSize(width=this.options.width,height=this.options.height){width=this._prepareValue(width);height=this._prepareValue(height);let emitEvent=false;const oldWidth=this.frame.canvas.width;const oldHeight=this.frame.canvas.height;// update the pixel ratio
//
// NOTE: Comment in following is rather inconsistent; this is the ONLY place in the code
// where it is assumed that the pixel ratio could change at runtime.
// The only way I can think of this happening is a rotating screen or tablet; but then
// there should be a mechanism for reloading the data (TODO: check if this is present).
//
// If the assumption is true (i.e. pixel ratio can change at runtime), then *all* usage
// of pixel ratio must be overhauled for this.
//
// For the time being, I will humor the assumption here, and in the rest of the code assume it is
// constant.
const previousRatio=this.pixelRatio;// we cache this because the camera state storage needs the old value
this._setPixelRatio();if(width!=this.options.width||height!=this.options.height||this.frame.style.width!=width||this.frame.style.height!=height){this._getCameraState(previousRatio);this.frame.style.width=width;this.frame.style.height=height;this.frame.canvas.style.width="100%";this.frame.canvas.style.height="100%";this.frame.canvas.width=Math.round(this.frame.canvas.clientWidth*this.pixelRatio);this.frame.canvas.height=Math.round(this.frame.canvas.clientHeight*this.pixelRatio);this.options.width=width;this.options.height=height;this.canvasViewCenter={x:0.5*this.frame.clientWidth,y:0.5*this.frame.clientHeight};emitEvent=true;}else {// this would adapt the width of the canvas to the width from 100% if and only if
// there is a change.
const newWidth=Math.round(this.frame.canvas.clientWidth*this.pixelRatio);const newHeight=Math.round(this.frame.canvas.clientHeight*this.pixelRatio);// store the camera if there is a change in size.
if(this.frame.canvas.width!==newWidth||this.frame.canvas.height!==newHeight){this._getCameraState(previousRatio);}if(this.frame.canvas.width!==newWidth){this.frame.canvas.width=newWidth;emitEvent=true;}if(this.frame.canvas.height!==newHeight){this.frame.canvas.height=newHeight;emitEvent=true;}}if(emitEvent===true){this.body.emitter.emit("resize",{width:Math.round(this.frame.canvas.width/this.pixelRatio),height:Math.round(this.frame.canvas.height/this.pixelRatio),oldWidth:Math.round(oldWidth/this.pixelRatio),oldHeight:Math.round(oldHeight/this.pixelRatio)});// restore the camera on change.
this._setCameraState();}// set initialized so the get and set camera will work from now on.
this.initialized=true;return emitEvent;}/**
*
* @returns {CanvasRenderingContext2D}
*/getContext(){return this.frame.canvas.getContext("2d");}/**
* Determine the pixel ratio for various browsers.
*
* @returns {number}
* @private
*/_determinePixelRatio(){const ctx=this.getContext();if(ctx===undefined){throw new Error("Could not get canvax context");}let numerator=1;if(typeof window!=="undefined"){// (window !== undefined) doesn't work here!
// Protection during unit tests, where 'window' can be missing
numerator=window.devicePixelRatio||1;}const denominator=ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1;return numerator/denominator;}/**
* Lazy determination of pixel ratio.
*
* @private
*/_setPixelRatio(){this.pixelRatio=this._determinePixelRatio();}/**
* Set the transform in the contained context, based on its pixelRatio
*/setTransform(){const ctx=this.getContext();if(ctx===undefined){throw new Error("Could not get canvax context");}ctx.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);}/**
* Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
* the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
*
* @param {number} x
* @returns {number}
* @private
*/_XconvertDOMtoCanvas(x){return (x-this.body.view.translation.x)/this.body.view.scale;}/**
* Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
* the X coordinate in DOM-space (coordinate point in browser relative to the container div)
*
* @param {number} x
* @returns {number}
* @private
*/_XconvertCanvasToDOM(x){return x*this.body.view.scale+this.body.view.translation.x;}/**
* Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
* the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
*
* @param {number} y
* @returns {number}
* @private
*/_YconvertDOMtoCanvas(y){return (y-this.body.view.translation.y)/this.body.view.scale;}/**
* Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
* the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
*
* @param {number} y
* @returns {number}
* @private
*/_YconvertCanvasToDOM(y){return y*this.body.view.scale+this.body.view.translation.y;}/**
* @param {point} pos
* @returns {point}
*/canvasToDOM(pos){return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)};}/**
*
* @param {point} pos
* @returns {point}
*/DOMtoCanvas(pos){return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)};}}/**
* Validate the fit options, replace missing optional values by defaults etc.
*
* @param rawOptions - The raw options.
* @param allNodeIds - All node ids that will be used if nodes are omitted in
* the raw options.
* @returns Options with everything filled in and validated.
*/function normalizeFitOptions(rawOptions,allNodeIds){const options=Object.assign({nodes:allNodeIds,minZoomLevel:Number.MIN_VALUE,maxZoomLevel:1},rawOptions!==null&&rawOptions!==void 0?rawOptions:{});if(!Array.isArray(options.nodes)){throw new TypeError("Nodes has to be an array of ids.");}if(options.nodes.length===0){options.nodes=allNodeIds;}if(!(typeof options.minZoomLevel==="number"&&options.minZoomLevel>0)){throw new TypeError("Min zoom level has to be a number higher than zero.");}if(!(typeof options.maxZoomLevel==="number"&&options.minZoomLevel<=options.maxZoomLevel)){throw new TypeError("Max zoom level has to be a number higher than min zoom level.");}return options;}/**
* The view
*/class View{/**
* @param {object} body
* @param {Canvas} canvas
*/constructor(body,canvas){this.body=body;this.canvas=canvas;this.animationSpeed=1/this.renderRefreshRate;this.animationEasingFunction="easeInOutQuint";this.easingTime=0;this.sourceScale=0;this.targetScale=0;this.sourceTranslation=0;this.targetTranslation=0;this.lockedOnNodeId=undefined;this.lockedOnNodeOffset=undefined;this.touchTime=0;this.viewFunction=undefined;this.body.emitter.on("fit",this.fit.bind(this));this.body.emitter.on("animationFinished",()=>{this.body.emitter.emit("_stopRendering");});this.body.emitter.on("unlockNode",this.releaseNode.bind(this));}/**
*
* @param {object} [options={}]
*/setOptions(options={}){this.options=options;}/**
* This function zooms out to fit all data on screen based on amount of nodes
*
* @param {object} [options={{nodes=Array}}]
* @param options
* @param {boolean} [initialZoom=false] | zoom based on fitted formula or range, true = fitted, default = false;
*/fit(options,initialZoom=false){options=normalizeFitOptions(options,this.body.nodeIndices);const canvasWidth=this.canvas.frame.canvas.clientWidth;const canvasHeight=this.canvas.frame.canvas.clientHeight;let range;let zoomLevel;if(canvasWidth===0||canvasHeight===0){// There's no point in trying to fit into zero sized canvas. This could
// potentially even result in invalid values being computed. For example
// for network without nodes and zero sized canvas the zoom level would
// end up being computed as 0/0 which results in NaN. In any other case
// this would be 0/something which is again pointless to compute.
zoomLevel=1;range=NetworkUtil.getRange(this.body.nodes,options.nodes);}else if(initialZoom===true){// check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation.
let positionDefined=0;for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){const node=this.body.nodes[nodeId];if(node.predefinedPosition===true){positionDefined+=1;}}}if(positionDefined>0.5*this.body.nodeIndices.length){this.fit(options,false);return;}range=NetworkUtil.getRange(this.body.nodes,options.nodes);const numberOfNodes=this.body.nodeIndices.length;zoomLevel=12.662/(numberOfNodes+7.4147)+0.0964822;// this is obtained from fitting a dataset from 5 points with scale levels that looked good.
// correct for larger canvasses.
const factor=Math.min(canvasWidth/600,canvasHeight/600);zoomLevel*=factor;}else {this.body.emitter.emit("_resizeNodes");range=NetworkUtil.getRange(this.body.nodes,options.nodes);const xDistance=Math.abs(range.maxX-range.minX)*1.1;const yDistance=Math.abs(range.maxY-range.minY)*1.1;const xZoomLevel=canvasWidth/xDistance;const yZoomLevel=canvasHeight/yDistance;zoomLevel=xZoomLevel<=yZoomLevel?xZoomLevel:yZoomLevel;}if(zoomLevel>options.maxZoomLevel){zoomLevel=options.maxZoomLevel;}else if(zoomLevel<options.minZoomLevel){zoomLevel=options.minZoomLevel;}const center=NetworkUtil.findCenter(range);const animationOptions={position:center,scale:zoomLevel,animation:options.animation};this.moveTo(animationOptions);}// animation
/**
* Center a node in view.
*
* @param {number} nodeId
* @param {number} [options]
*/focus(nodeId,options={}){if(this.body.nodes[nodeId]!==undefined){const nodePosition={x:this.body.nodes[nodeId].x,y:this.body.nodes[nodeId].y};options.position=nodePosition;options.lockedOnNode=nodeId;this.moveTo(options);}else {console.error("Node: "+nodeId+" cannot be found.");}}/**
*
* @param {object} options | options.offset = {x:number, y:number} // offset from the center in DOM pixels
* | options.scale = number // scale to move to
* | options.position = {x:number, y:number} // position to move to
* | options.animation = {duration:number, easingFunction:String} || Boolean // position to move to
*/moveTo(options){if(options===undefined){options={};return;}if(options.offset!=null){if(options.offset.x!=null){// Coerce and verify that x is valid.
options.offset.x=+options.offset.x;if(!Number.isFinite(options.offset.x)){throw new TypeError('The option "offset.x" has to be a finite number.');}}else {options.offset.x=0;}if(options.offset.y!=null){// Coerce and verify that y is valid.
options.offset.y=+options.offset.y;if(!Number.isFinite(options.offset.y)){throw new TypeError('The option "offset.y" has to be a finite number.');}}else {options.offset.x=0;}}else {options.offset={x:0,y:0};}if(options.position!=null){if(options.position.x!=null){// Coerce and verify that x is valid.
options.position.x=+options.position.x;if(!Number.isFinite(options.position.x)){throw new TypeError('The option "position.x" has to be a finite number.');}}else {options.position.x=0;}if(options.position.y!=null){// Coerce and verify that y is valid.
options.position.y=+options.position.y;if(!Number.isFinite(options.position.y)){throw new TypeError('The option "position.y" has to be a finite number.');}}else {options.position.x=0;}}else {options.position=this.getViewPosition();}if(options.scale!=null){// Coerce and verify that the scale is valid.
options.scale=+options.scale;if(!(options.scale>0)){throw new TypeError('The option "scale" has to be a number greater than zero.');}}else {options.scale=this.body.view.scale;}if(options.animation===undefined){options.animation={duration:0};}if(options.animation===false){options.animation={duration:0};}if(options.animation===true){options.animation={};}if(options.animation.duration===undefined){options.animation.duration=1000;}// default duration
if(options.animation.easingFunction===undefined){options.animation.easingFunction="easeInOutQuad";}// default easing function
this.animateView(options);}/**
*
* @param {object} options | options.offset = {x:number, y:number} // offset from the center in DOM pixels
* | options.time = number // animation time in milliseconds
* | options.scale = number // scale to animate to
* | options.position = {x:number, y:number} // position to animate to
* | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
* // easeInCubic, easeOutCubic, easeInOutCubic,
* // easeInQuart, easeOutQuart, easeInOutQuart,
* // easeInQuint, easeOutQuint, easeInOutQuint
*/animateView(options){if(options===undefined){return;}this.animationEasingFunction=options.animation.easingFunction;// release if something focussed on the node
this.releaseNode();if(options.locked===true){this.lockedOnNodeId=options.lockedOnNode;this.lockedOnNodeOffset=options.offset;}// forcefully complete the old animation if it was still running
if(this.easingTime!=0){this._transitionRedraw(true);// by setting easingtime to 1, we finish the animation.
}this.sourceScale=this.body.view.scale;this.sourceTranslation=this.body.view.translation;this.targetScale=options.scale;// set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
// but at least then we'll have the target transition
this.body.view.scale=this.targetScale;const viewCenter=this.canvas.DOMtoCanvas({x:0.5*this.canvas.frame.canvas.clientWidth,y:0.5*this.canvas.frame.canvas.clientHeight});const distanceFromCenter={// offset from view, distance view has to change by these x and y to center the node
x:viewCenter.x-options.position.x,y:viewCenter.y-options.position.y};this.targetTranslation={x:this.sourceTranslation.x+distanceFromCenter.x*this.targetScale+options.offset.x,y:this.sourceTranslation.y+distanceFromCenter.y*this.targetScale+options.offset.y};// if the time is set to 0, don't do an animation
if(options.animation.duration===0){if(this.lockedOnNodeId!=undefined){this.viewFunction=this._lockedRedraw.bind(this);this.body.emitter.on("initRedraw",this.viewFunction);}else {this.body.view.scale=this.targetScale;this.body.view.translation=this.targetTranslation;this.body.emitter.emit("_requestRedraw");}}else {this.animationSpeed=1/(60*options.animation.duration*0.001)||1/60;// 60 for 60 seconds, 0.001 for milli's
this.animationEasingFunction=options.animation.easingFunction;this.viewFunction=this._transitionRedraw.bind(this);this.body.emitter.on("initRedraw",this.viewFunction);this.body.emitter.emit("_startRendering");}}/**
* used to animate smoothly by hijacking the redraw function.
*
* @private
*/_lockedRedraw(){const nodePosition={x:this.body.nodes[this.lockedOnNodeId].x,y:this.body.nodes[this.lockedOnNodeId].y};const viewCenter=this.canvas.DOMtoCanvas({x:0.5*this.canvas.frame.canvas.clientWidth,y:0.5*this.canvas.frame.canvas.clientHeight});const distanceFromCenter={// offset from view, distance view has to change by these x and y to center the node
x:viewCenter.x-nodePosition.x,y:viewCenter.y-nodePosition.y};const sourceTranslation=this.body.view.translation;const targetTranslation={x:sourceTranslation.x+distanceFromCenter.x*this.body.view.scale+this.lockedOnNodeOffset.x,y:sourceTranslation.y+distanceFromCenter.y*this.body.view.scale+this.lockedOnNodeOffset.y};this.body.view.translation=targetTranslation;}/**
* Resets state of a locked on Node
*/releaseNode(){if(this.lockedOnNodeId!==undefined&&this.viewFunction!==undefined){this.body.emitter.off("initRedraw",this.viewFunction);this.lockedOnNodeId=undefined;this.lockedOnNodeOffset=undefined;}}/**
* @param {boolean} [finished=false]
* @private
*/_transitionRedraw(finished=false){this.easingTime+=this.animationSpeed;this.easingTime=finished===true?1.0:this.easingTime;const progress=easingFunctions[this.animationEasingFunction](this.easingTime);this.body.view.scale=this.sourceScale+(this.targetScale-this.sourceScale)*progress;this.body.view.translation={x:this.sourceTranslation.x+(this.targetTranslation.x-this.sourceTranslation.x)*progress,y:this.sourceTranslation.y+(this.targetTranslation.y-this.sourceTranslation.y)*progress};// cleanup
if(this.easingTime>=1.0){this.body.emitter.off("initRedraw",this.viewFunction);this.easingTime=0;if(this.lockedOnNodeId!=undefined){this.viewFunction=this._lockedRedraw.bind(this);this.body.emitter.on("initRedraw",this.viewFunction);}this.body.emitter.emit("animationFinished");}}/**
*
* @returns {number}
*/getScale(){return this.body.view.scale;}/**
*
* @returns {{x: number, y: number}}
*/getViewPosition(){return this.canvas.DOMtoCanvas({x:0.5*this.canvas.frame.canvas.clientWidth,y:0.5*this.canvas.frame.canvas.clientHeight});}}/**
* Navigation Handler
*/class NavigationHandler{/**
* @param {object} body
* @param {Canvas} canvas
*/constructor(body,canvas){this.body=body;this.canvas=canvas;this.iconsCreated=false;this.navigationHammers=[];this.boundFunctions={};this.touchTime=0;this.activated=false;this.body.emitter.on("activate",()=>{this.activated=true;this.configureKeyboardBindings();});this.body.emitter.on("deactivate",()=>{this.activated=false;this.configureKeyboardBindings();});this.body.emitter.on("destroy",()=>{if(this.keycharm!==undefined){this.keycharm.destroy();}});this.options={};}/**
*
* @param {object} options
*/setOptions(options){if(options!==undefined){this.options=options;this.create();}}/**
* Creates or refreshes navigation and sets key bindings
*/create(){if(this.options.navigationButtons===true){if(this.iconsCreated===false){this.loadNavigationElements();}}else if(this.iconsCreated===true){this.cleanNavigation();}this.configureKeyboardBindings();}/**
* Cleans up previous navigation items
*/cleanNavigation(){// clean hammer bindings
if(this.navigationHammers.length!=0){for(let i=0;i<this.navigationHammers.length;i++){this.navigationHammers[i].destroy();}this.navigationHammers=[];}// clean up previous navigation items
if(this.navigationDOM&&this.navigationDOM["wrapper"]&&this.navigationDOM["wrapper"].parentNode){this.navigationDOM["wrapper"].parentNode.removeChild(this.navigationDOM["wrapper"]);}this.iconsCreated=false;}/**
* Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
* they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
* on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
* This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
*
* @private
*/loadNavigationElements(){this.cleanNavigation();this.navigationDOM={};const navigationDivs=["up","down","left","right","zoomIn","zoomOut","zoomExtends"];const navigationDivActions=["_moveUp","_moveDown","_moveLeft","_moveRight","_zoomIn","_zoomOut","_fit"];this.navigationDOM["wrapper"]=document.createElement("div");this.navigationDOM["wrapper"].className="vis-navigation";this.canvas.frame.appendChild(this.navigationDOM["wrapper"]);for(let i=0;i<navigationDivs.length;i++){this.navigationDOM[navigationDivs[i]]=document.createElement("div");this.navigationDOM[navigationDivs[i]].className="vis-button vis-"+navigationDivs[i];this.navigationDOM["wrapper"].appendChild(this.navigationDOM[navigationDivs[i]]);const hammer=new Hammer$2(this.navigationDOM[navigationDivs[i]]);if(navigationDivActions[i]==="_fit"){onTouch(hammer,this._fit.bind(this));}else {onTouch(hammer,this.bindToRedraw.bind(this,navigationDivActions[i]));}this.navigationHammers.push(hammer);}// use a hammer for the release so we do not require the one used in the rest of the network
// the one the rest uses can be overloaded by the manipulation system.
const hammerFrame=new Hammer$2(this.canvas.frame);onRelease(hammerFrame,()=>{this._stopMovement();});this.navigationHammers.push(hammerFrame);this.iconsCreated=true;}/**
*
* @param {string} action
*/bindToRedraw(action){if(this.boundFunctions[action]===undefined){this.boundFunctions[action]=this[action].bind(this);this.body.emitter.on("initRedraw",this.boundFunctions[action]);this.body.emitter.emit("_startRendering");}}/**
*
* @param {string} action
*/unbindFromRedraw(action){if(this.boundFunctions[action]!==undefined){this.body.emitter.off("initRedraw",this.boundFunctions[action]);this.body.emitter.emit("_stopRendering");delete this.boundFunctions[action];}}/**
* this stops all movement induced by the navigation buttons
*
* @private
*/_fit(){if(new Date().valueOf()-this.touchTime>700){// TODO: fix ugly hack to avoid hammer's double fireing of event (because we use release?)
this.body.emitter.emit("fit",{duration:700});this.touchTime=new Date().valueOf();}}/**
* this stops all movement induced by the navigation buttons
*
* @private
*/_stopMovement(){for(const boundAction in this.boundFunctions){if(Object.prototype.hasOwnProperty.call(this.boundFunctions,boundAction)){this.body.emitter.off("initRedraw",this.boundFunctions[boundAction]);this.body.emitter.emit("_stopRendering");}}this.boundFunctions={};}/**
*
* @private
*/_moveUp(){this.body.view.translation.y+=this.options.keyboard.speed.y;}/**
*
* @private
*/_moveDown(){this.body.view.translation.y-=this.options.keyboard.speed.y;}/**
*
* @private
*/_moveLeft(){this.body.view.translation.x+=this.options.keyboard.speed.x;}/**
*
* @private
*/_moveRight(){this.body.view.translation.x-=this.options.keyboard.speed.x;}/**
*
* @private
*/_zoomIn(){const scaleOld=this.body.view.scale;const scale=this.body.view.scale*(1+this.options.keyboard.speed.zoom);const translation=this.body.view.translation;const scaleFrac=scale/scaleOld;const tx=(1-scaleFrac)*this.canvas.canvasViewCenter.x+translation.x*scaleFrac;const ty=(1-scaleFrac)*this.canvas.canvasViewCenter.y+translation.y*scaleFrac;this.body.view.scale=scale;this.body.view.translation={x:tx,y:ty};this.body.emitter.emit("zoom",{direction:"+",scale:this.body.view.scale,pointer:null});}/**
*
* @private
*/_zoomOut(){const scaleOld=this.body.view.scale;const scale=this.body.view.scale/(1+this.options.keyboard.speed.zoom);const translation=this.body.view.translation;const scaleFrac=scale/scaleOld;const tx=(1-scaleFrac)*this.canvas.canvasViewCenter.x+translation.x*scaleFrac;const ty=(1-scaleFrac)*this.canvas.canvasViewCenter.y+translation.y*scaleFrac;this.body.view.scale=scale;this.body.view.translation={x:tx,y:ty};this.body.emitter.emit("zoom",{direction:"-",scale:this.body.view.scale,pointer:null});}/**
* bind all keys using keycharm.
*/configureKeyboardBindings(){if(this.keycharm!==undefined){this.keycharm.destroy();}if(this.options.keyboard.enabled===true){if(this.options.keyboard.bindToWindow===true){this.keycharm=keycharm({container:window,preventDefault:true});}else {this.keycharm=keycharm({container:this.canvas.frame,preventDefault:true});}this.keycharm.reset();if(this.activated===true){this.keycharm.bind("up",()=>{this.bindToRedraw("_moveUp");},"keydown");this.keycharm.bind("down",()=>{this.bindToRedraw("_moveDown");},"keydown");this.keycharm.bind("left",()=>{this.bindToRedraw("_moveLeft");},"keydown");this.keycharm.bind("right",()=>{this.bindToRedraw("_moveRight");},"keydown");this.keycharm.bind("=",()=>{this.bindToRedraw("_zoomIn");},"keydown");this.keycharm.bind("num+",()=>{this.bindToRedraw("_zoomIn");},"keydown");this.keycharm.bind("num-",()=>{this.bindToRedraw("_zoomOut");},"keydown");this.keycharm.bind("-",()=>{this.bindToRedraw("_zoomOut");},"keydown");this.keycharm.bind("[",()=>{this.bindToRedraw("_zoomOut");},"keydown");this.keycharm.bind("]",()=>{this.bindToRedraw("_zoomIn");},"keydown");this.keycharm.bind("pageup",()=>{this.bindToRedraw("_zoomIn");},"keydown");this.keycharm.bind("pagedown",()=>{this.bindToRedraw("_zoomOut");},"keydown");this.keycharm.bind("up",()=>{this.unbindFromRedraw("_moveUp");},"keyup");this.keycharm.bind("down",()=>{this.unbindFromRedraw("_moveDown");},"keyup");this.keycharm.bind("left",()=>{this.unbindFromRedraw("_moveLeft");},"keyup");this.keycharm.bind("right",()=>{this.unbindFromRedraw("_moveRight");},"keyup");this.keycharm.bind("=",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");this.keycharm.bind("num+",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");this.keycharm.bind("num-",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");this.keycharm.bind("-",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");this.keycharm.bind("[",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");this.keycharm.bind("]",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");this.keycharm.bind("pageup",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");this.keycharm.bind("pagedown",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");}}}}/**
* Handler for interactions
*/class InteractionHandler{/**
* @param {object} body
* @param {Canvas} canvas
* @param {SelectionHandler} selectionHandler
*/constructor(body,canvas,selectionHandler){this.body=body;this.canvas=canvas;this.selectionHandler=selectionHandler;this.navigationHandler=new NavigationHandler(body,canvas);// bind the events from hammer to functions in this object
this.body.eventListeners.onTap=this.onTap.bind(this);this.body.eventListeners.onTouch=this.onTouch.bind(this);this.body.eventListeners.onDoubleTap=this.onDoubleTap.bind(this);this.body.eventListeners.onHold=this.onHold.bind(this);this.body.eventListeners.onDragStart=this.onDragStart.bind(this);this.body.eventListeners.onDrag=this.onDrag.bind(this);this.body.eventListeners.onDragEnd=this.onDragEnd.bind(this);this.body.eventListeners.onMouseWheel=this.onMouseWheel.bind(this);this.body.eventListeners.onPinch=this.onPinch.bind(this);this.body.eventListeners.onMouseMove=this.onMouseMove.bind(this);this.body.eventListeners.onRelease=this.onRelease.bind(this);this.body.eventListeners.onContext=this.onContext.bind(this);this.touchTime=0;this.drag={};this.pinch={};this.popup=undefined;this.popupObj=undefined;this.popupTimer=undefined;this.body.functions.getPointer=this.getPointer.bind(this);this.options={};this.defaultOptions={dragNodes:true,dragView:true,hover:false,keyboard:{enabled:false,speed:{x:10,y:10,zoom:0.02},bindToWindow:true,autoFocus:true},navigationButtons:false,tooltipDelay:300,zoomView:true,zoomSpeed:1};Object.assign(this.options,this.defaultOptions);this.bindEventListeners();}/**
* Binds event listeners
*/bindEventListeners(){this.body.emitter.on("destroy",()=>{clearTimeout(this.popupTimer);delete this.body.functions.getPointer;});}/**
*
* @param {object} options
*/setOptions(options){if(options!==undefined){// extend all but the values in fields
const fields=["hideEdgesOnDrag","hideEdgesOnZoom","hideNodesOnDrag","keyboard","multiselect","selectable","selectConnectedEdges"];selectiveNotDeepExtend(fields,this.options,options);// merge the keyboard options in.
mergeOptions(this.options,options,"keyboard");if(options.tooltip){Object.assign(this.options.tooltip,options.tooltip);if(options.tooltip.color){this.options.tooltip.color=parseColor(options.tooltip.color);}}}this.navigationHandler.setOptions(this.options);}/**
* Get the pointer location from a touch location
*
* @param {{x: number, y: number}} touch
* @returns {{x: number, y: number}} pointer
* @private
*/getPointer(touch){return {x:touch.x-getAbsoluteLeft(this.canvas.frame.canvas),y:touch.y-getAbsoluteTop(this.canvas.frame.canvas)};}/**
* On start of a touch gesture, store the pointer
*
* @param {Event} event The event
* @private
*/onTouch(event){if(new Date().valueOf()-this.touchTime>50){this.drag.pointer=this.getPointer(event.center);this.drag.pinched=false;this.pinch.scale=this.body.view.scale;// to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
this.touchTime=new Date().valueOf();}}/**
* handle tap/click event: select/unselect a node
*
* @param {Event} event
* @private
*/onTap(event){const pointer=this.getPointer(event.center);const multiselect=this.selectionHandler.options.multiselect&&(event.changedPointers[0].ctrlKey||event.changedPointers[0].metaKey);this.checkSelectionChanges(pointer,multiselect);this.selectionHandler.commitAndEmit(pointer,event);this.selectionHandler.generateClickEvent("click",event,pointer);}/**
* handle doubletap event
*
* @param {Event} event
* @private
*/onDoubleTap(event){const pointer=this.getPointer(event.center);this.selectionHandler.generateClickEvent("doubleClick",event,pointer);}/**
* handle long tap event: multi select nodes
*
* @param {Event} event
* @private
*/onHold(event){const pointer=this.getPointer(event.center);const multiselect=this.selectionHandler.options.multiselect;this.checkSelectionChanges(pointer,multiselect);this.selectionHandler.commitAndEmit(pointer,event);this.selectionHandler.generateClickEvent("click",event,pointer);this.selectionHandler.generateClickEvent("hold",event,pointer);}/**
* handle the release of the screen
*
* @param {Event} event
* @private
*/onRelease(event){if(new Date().valueOf()-this.touchTime>10){const pointer=this.getPointer(event.center);this.selectionHandler.generateClickEvent("release",event,pointer);// to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
this.touchTime=new Date().valueOf();}}/**
*
* @param {Event} event
*/onContext(event){const pointer=this.getPointer({x:event.clientX,y:event.clientY});this.selectionHandler.generateClickEvent("oncontext",event,pointer);}/**
* Select and deselect nodes depending current selection change.
*
* @param {{x: number, y: number}} pointer
* @param {boolean} [add=false]
*/checkSelectionChanges(pointer,add=false){if(add===true){this.selectionHandler.selectAdditionalOnPoint(pointer);}else {this.selectionHandler.selectOnPoint(pointer);}}/**
* Remove all node and edge id's from the first set that are present in the second one.
*
* @param {{nodes: Array.<Node>, edges: Array.<vis.Edge>}} firstSet
* @param {{nodes: Array.<Node>, edges: Array.<vis.Edge>}} secondSet
* @returns {{nodes: Array.<Node>, edges: Array.<vis.Edge>}}
* @private
*/_determineDifference(firstSet,secondSet){const arrayDiff=function(firstArr,secondArr){const result=[];for(let i=0;i<firstArr.length;i++){const value=firstArr[i];if(secondArr.indexOf(value)===-1){result.push(value);}}return result;};return {nodes:arrayDiff(firstSet.nodes,secondSet.nodes),edges:arrayDiff(firstSet.edges,secondSet.edges)};}/**
* This function is called by onDragStart.
* It is separated out because we can then overload it for the datamanipulation system.
*
* @param {Event} event
* @private
*/onDragStart(event){// if already dragging, do not start
// this can happen on touch screens with multiple fingers
if(this.drag.dragging){return;}//in case the touch event was triggered on an external div, do the initial touch now.
if(this.drag.pointer===undefined){this.onTouch(event);}// note: drag.pointer is set in onTouch to get the initial touch location
const node=this.selectionHandler.getNodeAt(this.drag.pointer);this.drag.dragging=true;this.drag.selection=[];this.drag.translation=Object.assign({},this.body.view.translation);// copy the object
this.drag.nodeId=undefined;if(event.srcEvent.shiftKey){this.body.selectionBox.show=true;const pointer=this.getPointer(event.center);this.body.selectionBox.position.start={x:this.canvas._XconvertDOMtoCanvas(pointer.x),y:this.canvas._YconvertDOMtoCanvas(pointer.y)};this.body.selectionBox.position.end={x:this.canvas._XconvertDOMtoCanvas(pointer.x),y:this.canvas._YconvertDOMtoCanvas(pointer.y)};}else if(node!==undefined&&this.options.dragNodes===true){this.drag.nodeId=node.id;// select the clicked node if not yet selected
if(node.isSelected()===false){this.selectionHandler.setSelection({nodes:[node.id]});}// after select to contain the node
this.selectionHandler.generateClickEvent("dragStart",event,this.drag.pointer);// create an array with the selected nodes and their original location and status
for(const node of this.selectionHandler.getSelectedNodes()){const s={id:node.id,node:node,// store original x, y, xFixed and yFixed, make the node temporarily Fixed
x:node.x,y:node.y,xFixed:node.options.fixed.x,yFixed:node.options.fixed.y};node.options.fixed.x=true;node.options.fixed.y=true;this.drag.selection.push(s);}}else {// fallback if no node is selected and thus the view is dragged.
this.selectionHandler.generateClickEvent("dragStart",event,this.drag.pointer,undefined,true);}}/**
* handle drag event
*
* @param {Event} event
* @private
*/onDrag(event){if(this.drag.pinched===true){return;}// remove the focus on node if it is focussed on by the focusOnNode
this.body.emitter.emit("unlockNode");const pointer=this.getPointer(event.center);const selection=this.drag.selection;if(selection&&selection.length&&this.options.dragNodes===true){this.selectionHandler.generateClickEvent("dragging",event,pointer);// calculate delta's and new location
const deltaX=pointer.x-this.drag.pointer.x;const deltaY=pointer.y-this.drag.pointer.y;// update position of all selected nodes
selection.forEach(selection=>{const node=selection.node;// only move the node if it was not fixed initially
if(selection.xFixed===false){node.x=this.canvas._XconvertDOMtoCanvas(this.canvas._XconvertCanvasToDOM(selection.x)+deltaX);}// only move the node if it was not fixed initially
if(selection.yFixed===false){node.y=this.canvas._YconvertDOMtoCanvas(this.canvas._YconvertCanvasToDOM(selection.y)+deltaY);}});// start the simulation of the physics
this.body.emitter.emit("startSimulation");}else {// create selection box
if(event.srcEvent.shiftKey){this.selectionHandler.generateClickEvent("dragging",event,pointer,undefined,true);// if the drag was not started properly because the click started outside the network div, start it now.
if(this.drag.pointer===undefined){this.onDragStart(event);return;}this.body.selectionBox.position.end={x:this.canvas._XconvertDOMtoCanvas(pointer.x),y:this.canvas._YconvertDOMtoCanvas(pointer.y)};this.body.emitter.emit("_requestRedraw");}// move the network
if(this.options.dragView===true&&!event.srcEvent.shiftKey){this.selectionHandler.generateClickEvent("dragging",event,pointer,undefined,true);// if the drag was not started properly because the click started outside the network div, start it now.
if(this.drag.pointer===undefined){this.onDragStart(event);return;}const diffX=pointer.x-this.drag.pointer.x;const diffY=pointer.y-this.drag.pointer.y;this.body.view.translation={x:this.drag.translation.x+diffX,y:this.drag.translation.y+diffY};this.body.emitter.emit("_requestRedraw");}}}/**
* handle drag start event
*
* @param {Event} event
* @private
*/onDragEnd(event){this.drag.dragging=false;if(this.body.selectionBox.show){this.body.selectionBox.show=false;const selectionBoxPosition=this.body.selectionBox.position;const selectionBoxPositionMinMax={minX:Math.min(selectionBoxPosition.start.x,selectionBoxPosition.end.x),minY:Math.min(selectionBoxPosition.start.y,selectionBoxPosition.end.y),maxX:Math.max(selectionBoxPosition.start.x,selectionBoxPosition.end.x),maxY:Math.max(selectionBoxPosition.start.y,selectionBoxPosition.end.y)};const toBeSelectedNodes=this.body.nodeIndices.filter(nodeId=>{const node=this.body.nodes[nodeId];return node.x>=selectionBoxPositionMinMax.minX&&node.x<=selectionBoxPositionMinMax.maxX&&node.y>=selectionBoxPositionMinMax.minY&&node.y<=selectionBoxPositionMinMax.maxY;});toBeSelectedNodes.forEach(nodeId=>this.selectionHandler.selectObject(this.body.nodes[nodeId]));const pointer=this.getPointer(event.center);this.selectionHandler.commitAndEmit(pointer,event);this.selectionHandler.generateClickEvent("dragEnd",event,this.getPointer(event.center),undefined,true);this.body.emitter.emit("_requestRedraw");}else {const selection=this.drag.selection;if(selection&&selection.length){selection.forEach(function(s){// restore original xFixed and yFixed
s.node.options.fixed.x=s.xFixed;s.node.options.fixed.y=s.yFixed;});this.selectionHandler.generateClickEvent("dragEnd",event,this.getPointer(event.center));this.body.emitter.emit("startSimulation");}else {this.selectionHandler.generateClickEvent("dragEnd",event,this.getPointer(event.center),undefined,true);this.body.emitter.emit("_requestRedraw");}}}/**
* Handle pinch event
*
* @param {Event} event The event
* @private
*/onPinch(event){const pointer=this.getPointer(event.center);this.drag.pinched=true;if(this.pinch["scale"]===undefined){this.pinch.scale=1;}// TODO: enabled moving while pinching?
const scale=this.pinch.scale*event.scale;this.zoom(scale,pointer);}/**
* Zoom the network in or out
*
* @param {number} scale a number around 1, and between 0.01 and 10
* @param {{x: number, y: number}} pointer Position on screen
* @private
*/zoom(scale,pointer){if(this.options.zoomView===true){const scaleOld=this.body.view.scale;if(scale<0.00001){scale=0.00001;}if(scale>10){scale=10;}let preScaleDragPointer=undefined;if(this.drag!==undefined){if(this.drag.dragging===true){preScaleDragPointer=this.canvas.DOMtoCanvas(this.drag.pointer);}}// + this.canvas.frame.canvas.clientHeight / 2
const translation=this.body.view.translation;const scaleFrac=scale/scaleOld;const tx=(1-scaleFrac)*pointer.x+translation.x*scaleFrac;const ty=(1-scaleFrac)*pointer.y+translation.y*scaleFrac;this.body.view.scale=scale;this.body.view.translation={x:tx,y:ty};if(preScaleDragPointer!=undefined){const postScaleDragPointer=this.canvas.canvasToDOM(preScaleDragPointer);this.drag.pointer.x=postScaleDragPointer.x;this.drag.pointer.y=postScaleDragPointer.y;}this.body.emitter.emit("_requestRedraw");if(scaleOld<scale){this.body.emitter.emit("zoom",{direction:"+",scale:this.body.view.scale,pointer:pointer});}else {this.body.emitter.emit("zoom",{direction:"-",scale:this.body.view.scale,pointer:pointer});}}}/**
* Event handler for mouse wheel event, used to zoom the timeline
* See http://adomas.org/javascript-mouse-wheel/
* https://github.com/EightMedia/hammer.js/issues/256
*
* @param {MouseEvent} event
* @private
*/onMouseWheel(event){if(this.options.zoomView===true){// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if(event.deltaY!==0){// calculate the new scale
let scale=this.body.view.scale;scale*=1+(event.deltaY<0?1:-1)*(this.options.zoomSpeed*0.1);// calculate the pointer location
const pointer=this.getPointer({x:event.clientX,y:event.clientY});// apply the new scale
this.zoom(scale,pointer);}// Prevent default actions caused by mouse wheel.
event.preventDefault();}}/**
* Mouse move handler for checking whether the title moves over a node with a title.
*
* @param {Event} event
* @private
*/onMouseMove(event){const pointer=this.getPointer({x:event.clientX,y:event.clientY});let popupVisible=false;// check if the previously selected node is still selected
if(this.popup!==undefined){if(this.popup.hidden===false){this._checkHidePopup(pointer);}// if the popup was not hidden above
if(this.popup.hidden===false){popupVisible=true;this.popup.setPosition(pointer.x+3,pointer.y-5);this.popup.show();}}// if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over.
if(this.options.keyboard.autoFocus&&this.options.keyboard.bindToWindow===false&&this.options.keyboard.enabled===true){this.canvas.frame.focus();}// start a timeout that will check if the mouse is positioned above an element
if(popupVisible===false){if(this.popupTimer!==undefined){clearInterval(this.popupTimer);// stop any running calculationTimer
this.popupTimer=undefined;}if(!this.drag.dragging){this.popupTimer=setTimeout(()=>this._checkShowPopup(pointer),this.options.tooltipDelay);}}// adding hover highlights
if(this.options.hover===true){this.selectionHandler.hoverObject(event,pointer);}}/**
* Check if there is an element on the given position in the network
* (a node or edge). If so, and if this element has a title,
* show a popup window with its title.
*
* @param {{x:number, y:number}} pointer
* @private
*/_checkShowPopup(pointer){const x=this.canvas._XconvertDOMtoCanvas(pointer.x);const y=this.canvas._YconvertDOMtoCanvas(pointer.y);const pointerObj={left:x,top:y,right:x,bottom:y};const previousPopupObjId=this.popupObj===undefined?undefined:this.popupObj.id;let nodeUnderCursor=false;let popupType="node";// check if a node is under the cursor.
if(this.popupObj===undefined){// search the nodes for overlap, select the top one in case of multiple nodes
const nodeIndices=this.body.nodeIndices;const nodes=this.body.nodes;let node;const overlappingNodes=[];for(let i=0;i<nodeIndices.length;i++){node=nodes[nodeIndices[i]];if(node.isOverlappingWith(pointerObj)===true){nodeUnderCursor=true;if(node.getTitle()!==undefined){overlappingNodes.push(nodeIndices[i]);}}}if(overlappingNodes.length>0){// if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
this.popupObj=nodes[overlappingNodes[overlappingNodes.length-1]];// if you hover over a node, the title of the edge is not supposed to be shown.
nodeUnderCursor=true;}}if(this.popupObj===undefined&&nodeUnderCursor===false){// search the edges for overlap
const edgeIndices=this.body.edgeIndices;const edges=this.body.edges;let edge;const overlappingEdges=[];for(let i=0;i<edgeIndices.length;i++){edge=edges[edgeIndices[i]];if(edge.isOverlappingWith(pointerObj)===true){if(edge.connected===true&&edge.getTitle()!==undefined){overlappingEdges.push(edgeIndices[i]);}}}if(overlappingEdges.length>0){this.popupObj=edges[overlappingEdges[overlappingEdges.length-1]];popupType="edge";}}if(this.popupObj!==undefined){// show popup message window
if(this.popupObj.id!==previousPopupObjId){if(this.popup===undefined){this.popup=new Popup$2(this.canvas.frame);}this.popup.popupTargetType=popupType;this.popup.popupTargetId=this.popupObj.id;// adjust a small offset such that the mouse cursor is located in the
// bottom left location of the popup, and you can easily move over the
// popup area
this.popup.setPosition(pointer.x+3,pointer.y-5);this.popup.setText(this.popupObj.getTitle());this.popup.show();this.body.emitter.emit("showPopup",this.popupObj.id);}}else {if(this.popup!==undefined){this.popup.hide();this.body.emitter.emit("hidePopup");}}}/**
* Check if the popup must be hidden, which is the case when the mouse is no
* longer hovering on the object
*
* @param {{x:number, y:number}} pointer
* @private
*/_checkHidePopup(pointer){const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);let stillOnObj=false;if(this.popup.popupTargetType==="node"){if(this.body.nodes[this.popup.popupTargetId]!==undefined){stillOnObj=this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);// if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it.
// we initially only check stillOnObj because this is much faster.
if(stillOnObj===true){const overNode=this.selectionHandler.getNodeAt(pointer);stillOnObj=overNode===undefined?false:overNode.id===this.popup.popupTargetId;}}}else {if(this.selectionHandler.getNodeAt(pointer)===undefined){if(this.body.edges[this.popup.popupTargetId]!==undefined){stillOnObj=this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);}}}if(stillOnObj===false){this.popupObj=undefined;this.popup.hide();this.body.emitter.emit("hidePopup");}}}/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol */function __classPrivateFieldGet(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver);}function __classPrivateFieldSet(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value;}typeof SuppressedError==="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e;};var _SingleTypeSelectionAccumulator_previousSelection,_SingleTypeSelectionAccumulator_selection,_SelectionAccumulator_nodes,_SelectionAccumulator_edges,_SelectionAccumulator_commitHandler;/**
* @param prev
* @param next
*/function diffSets(prev,next){const diff=new Set();for(const item of next){if(!prev.has(item)){diff.add(item);}}return diff;}class SingleTypeSelectionAccumulator{constructor(){_SingleTypeSelectionAccumulator_previousSelection.set(this,new Set());_SingleTypeSelectionAccumulator_selection.set(this,new Set());}get size(){return __classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f").size;}add(...items){for(const item of items){__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f").add(item);}}delete(...items){for(const item of items){__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f").delete(item);}}clear(){__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f").clear();}getSelection(){return [...__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f")];}getChanges(){return {added:[...diffSets(__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_previousSelection,"f"),__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f"))],deleted:[...diffSets(__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f"),__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_previousSelection,"f"))],previous:[...new Set(__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_previousSelection,"f"))],current:[...new Set(__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f"))]};}commit(){const changes=this.getChanges();__classPrivateFieldSet(this,_SingleTypeSelectionAccumulator_previousSelection,__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_selection,"f"),"f");__classPrivateFieldSet(this,_SingleTypeSelectionAccumulator_selection,new Set(__classPrivateFieldGet(this,_SingleTypeSelectionAccumulator_previousSelection,"f")),"f");for(const item of changes.added){item.select();}for(const item of changes.deleted){item.unselect();}return changes;}}_SingleTypeSelectionAccumulator_previousSelection=new WeakMap(),_SingleTypeSelectionAccumulator_selection=new WeakMap();class SelectionAccumulator{constructor(commitHandler=()=>{}){_SelectionAccumulator_nodes.set(this,new SingleTypeSelectionAccumulator());_SelectionAccumulator_edges.set(this,new SingleTypeSelectionAccumulator());_SelectionAccumulator_commitHandler.set(this,void 0);__classPrivateFieldSet(this,_SelectionAccumulator_commitHandler,commitHandler,"f");}get sizeNodes(){return __classPrivateFieldGet(this,_SelectionAccumulator_nodes,"f").size;}get sizeEdges(){return __classPrivateFieldGet(this,_SelectionAccumulator_edges,"f").size;}getNodes(){return __classPrivateFieldGet(this,_SelectionAccumulator_nodes,"f").getSelection();}getEdges(){return __classPrivateFieldGet(this,_SelectionAccumulator_edges,"f").getSelection();}addNodes(...nodes){__classPrivateFieldGet(this,_SelectionAccumulator_nodes,"f").add(...nodes);}addEdges(...edges){__classPrivateFieldGet(this,_SelectionAccumulator_edges,"f").add(...edges);}deleteNodes(node){__classPrivateFieldGet(this,_SelectionAccumulator_nodes,"f").delete(node);}deleteEdges(edge){__classPrivateFieldGet(this,_SelectionAccumulator_edges,"f").delete(edge);}clear(){__classPrivateFieldGet(this,_SelectionAccumulator_nodes,"f").clear();__classPrivateFieldGet(this,_SelectionAccumulator_edges,"f").clear();}commit(...rest){const summary={nodes:__classPrivateFieldGet(this,_SelectionAccumulator_nodes,"f").commit(),edges:__classPrivateFieldGet(this,_SelectionAccumulator_edges,"f").commit()};__classPrivateFieldGet(this,_SelectionAccumulator_commitHandler,"f").call(this,summary,...rest);return summary;}}_SelectionAccumulator_nodes=new WeakMap(),_SelectionAccumulator_edges=new WeakMap(),_SelectionAccumulator_commitHandler=new WeakMap();/**
* The handler for selections
*/class SelectionHandler{/**
* @param {object} body
* @param {Canvas} canvas
*/constructor(body,canvas){this.body=body;this.canvas=canvas;// TODO: Consider firing an event on any change to the selection, not
// only those caused by clicks and taps. It would be easy to implement
// now and (at least to me) it seems like something that could be
// quite useful.
this._selectionAccumulator=new SelectionAccumulator();this.hoverObj={nodes:{},edges:{}};this.options={};this.defaultOptions={multiselect:false,selectable:true,selectConnectedEdges:true,hoverConnectedEdges:true};Object.assign(this.options,this.defaultOptions);this.body.emitter.on("_dataChanged",()=>{this.updateSelection();});}/**
*
* @param {object} [options]
*/setOptions(options){if(options!==undefined){const fields=["multiselect","hoverConnectedEdges","selectable","selectConnectedEdges"];selectiveDeepExtend(fields,this.options,options);}}/**
* handles the selection part of the tap;
*
* @param {{x: number, y: number}} pointer
* @returns {boolean}
*/selectOnPoint(pointer){let selected=false;if(this.options.selectable===true){const obj=this.getNodeAt(pointer)||this.getEdgeAt(pointer);// unselect after getting the objects in order to restore width and height.
this.unselectAll();if(obj!==undefined){selected=this.selectObject(obj);}this.body.emitter.emit("_requestRedraw");}return selected;}/**
*
* @param {{x: number, y: number}} pointer
* @returns {boolean}
*/selectAdditionalOnPoint(pointer){let selectionChanged=false;if(this.options.selectable===true){const obj=this.getNodeAt(pointer)||this.getEdgeAt(pointer);if(obj!==undefined){selectionChanged=true;if(obj.isSelected()===true){this.deselectObject(obj);}else {this.selectObject(obj);}this.body.emitter.emit("_requestRedraw");}}return selectionChanged;}/**
* Create an object containing the standard fields for an event.
*
* @param {Event} event
* @param {{x: number, y: number}} pointer Object with the x and y screen coordinates of the mouse
* @returns {{}}
* @private
*/_initBaseEvent(event,pointer){const properties={};properties["pointer"]={DOM:{x:pointer.x,y:pointer.y},canvas:this.canvas.DOMtoCanvas(pointer)};properties["event"]=event;return properties;}/**
* Generate an event which the user can catch.
*
* This adds some extra data to the event with respect to cursor position and
* selected nodes and edges.
*
* @param {string} eventType Name of event to send
* @param {Event} event
* @param {{x: number, y: number}} pointer Object with the x and y screen coordinates of the mouse
* @param {object | undefined} oldSelection If present, selection state before event occured
* @param {boolean|undefined} [emptySelection=false] Indicate if selection data should be passed
*/generateClickEvent(eventType,event,pointer,oldSelection,emptySelection=false){const properties=this._initBaseEvent(event,pointer);if(emptySelection===true){properties.nodes=[];properties.edges=[];}else {const tmp=this.getSelection();properties.nodes=tmp.nodes;properties.edges=tmp.edges;}if(oldSelection!==undefined){properties["previousSelection"]=oldSelection;}if(eventType=="click"){// For the time being, restrict this functionality to
// just the click event.
properties.items=this.getClickedItems(pointer);}if(event.controlEdge!==undefined){properties.controlEdge=event.controlEdge;}this.body.emitter.emit(eventType,properties);}/**
*
* @param {object} obj
* @param {boolean} [highlightEdges=this.options.selectConnectedEdges]
* @returns {boolean}
*/selectObject(obj,highlightEdges=this.options.selectConnectedEdges){if(obj!==undefined){if(obj instanceof Node){if(highlightEdges===true){this._selectionAccumulator.addEdges(...obj.edges);}this._selectionAccumulator.addNodes(obj);}else {this._selectionAccumulator.addEdges(obj);}return true;}return false;}/**
*
* @param {object} obj
*/deselectObject(obj){if(obj.isSelected()===true){obj.selected=false;this._removeFromSelection(obj);}}/**
* retrieve all nodes overlapping with given object
*
* @param {object} object An object with parameters left, top, right, bottom
* @returns {number[]} An array with id's of the overlapping nodes
* @private
*/_getAllNodesOverlappingWith(object){const overlappingNodes=[];const nodes=this.body.nodes;for(let i=0;i<this.body.nodeIndices.length;i++){const nodeId=this.body.nodeIndices[i];if(nodes[nodeId].isOverlappingWith(object)){overlappingNodes.push(nodeId);}}return overlappingNodes;}/**
* Return a position object in canvasspace from a single point in screenspace
*
* @param {{x: number, y: number}} pointer
* @returns {{left: number, top: number, right: number, bottom: number}}
* @private
*/_pointerToPositionObject(pointer){const canvasPos=this.canvas.DOMtoCanvas(pointer);return {left:canvasPos.x-1,top:canvasPos.y+1,right:canvasPos.x+1,bottom:canvasPos.y-1};}/**
* Get the top node at the passed point (like a click)
*
* @param {{x: number, y: number}} pointer
* @param {boolean} [returnNode=true]
* @returns {Node | undefined} node
*/getNodeAt(pointer,returnNode=true){// we first check if this is an navigation controls element
const positionObject=this._pointerToPositionObject(pointer);const overlappingNodes=this._getAllNodesOverlappingWith(positionObject);// if there are overlapping nodes, select the last one, this is the
// one which is drawn on top of the others
if(overlappingNodes.length>0){if(returnNode===true){return this.body.nodes[overlappingNodes[overlappingNodes.length-1]];}else {return overlappingNodes[overlappingNodes.length-1];}}else {return undefined;}}/**
* retrieve all edges overlapping with given object, selector is around center
*
* @param {object} object An object with parameters left, top, right, bottom
* @param {number[]} overlappingEdges An array with id's of the overlapping nodes
* @private
*/_getEdgesOverlappingWith(object,overlappingEdges){const edges=this.body.edges;for(let i=0;i<this.body.edgeIndices.length;i++){const edgeId=this.body.edgeIndices[i];if(edges[edgeId].isOverlappingWith(object)){overlappingEdges.push(edgeId);}}}/**
* retrieve all nodes overlapping with given object
*
* @param {object} object An object with parameters left, top, right, bottom
* @returns {number[]} An array with id's of the overlapping nodes
* @private
*/_getAllEdgesOverlappingWith(object){const overlappingEdges=[];this._getEdgesOverlappingWith(object,overlappingEdges);return overlappingEdges;}/**
* Get the edges nearest to the passed point (like a click)
*
* @param {{x: number, y: number}} pointer
* @param {boolean} [returnEdge=true]
* @returns {Edge | undefined} node
*/getEdgeAt(pointer,returnEdge=true){// Iterate over edges, pick closest within 10
const canvasPos=this.canvas.DOMtoCanvas(pointer);let mindist=10;let overlappingEdge=null;const edges=this.body.edges;for(let i=0;i<this.body.edgeIndices.length;i++){const edgeId=this.body.edgeIndices[i];const edge=edges[edgeId];if(edge.connected){const xFrom=edge.from.x;const yFrom=edge.from.y;const xTo=edge.to.x;const yTo=edge.to.y;const dist=edge.edgeType.getDistanceToEdge(xFrom,yFrom,xTo,yTo,canvasPos.x,canvasPos.y);if(dist<mindist){overlappingEdge=edgeId;mindist=dist;}}}if(overlappingEdge!==null){if(returnEdge===true){return this.body.edges[overlappingEdge];}else {return overlappingEdge;}}else {return undefined;}}/**
* Add object to the selection array.
*
* @param {object} obj
* @private
*/_addToHover(obj){if(obj instanceof Node){this.hoverObj.nodes[obj.id]=obj;}else {this.hoverObj.edges[obj.id]=obj;}}/**
* Remove a single option from selection.
*
* @param {object} obj
* @private
*/_removeFromSelection(obj){if(obj instanceof Node){this._selectionAccumulator.deleteNodes(obj);this._selectionAccumulator.deleteEdges(...obj.edges);}else {this._selectionAccumulator.deleteEdges(obj);}}/**
* Unselect all nodes and edges.
*/unselectAll(){this._selectionAccumulator.clear();}/**
* return the number of selected nodes
*
* @returns {number}
*/getSelectedNodeCount(){return this._selectionAccumulator.sizeNodes;}/**
* return the number of selected edges
*
* @returns {number}
*/getSelectedEdgeCount(){return this._selectionAccumulator.sizeEdges;}/**
* select the edges connected to the node that is being selected
*
* @param {Node} node
* @private
*/_hoverConnectedEdges(node){for(let i=0;i<node.edges.length;i++){const edge=node.edges[i];edge.hover=true;this._addToHover(edge);}}/**
* Remove the highlight from a node or edge, in response to mouse movement
*
* @param {Event} event
* @param {{x: number, y: number}} pointer object with the x and y screen coordinates of the mouse
* @param {Node|vis.Edge} object
* @private
*/emitBlurEvent(event,pointer,object){const properties=this._initBaseEvent(event,pointer);if(object.hover===true){object.hover=false;if(object instanceof Node){properties.node=object.id;this.body.emitter.emit("blurNode",properties);}else {properties.edge=object.id;this.body.emitter.emit("blurEdge",properties);}}}/**
* Create the highlight for a node or edge, in response to mouse movement
*
* @param {Event} event
* @param {{x: number, y: number}} pointer object with the x and y screen coordinates of the mouse
* @param {Node|vis.Edge} object
* @returns {boolean} hoverChanged
* @private
*/emitHoverEvent(event,pointer,object){const properties=this._initBaseEvent(event,pointer);let hoverChanged=false;if(object.hover===false){object.hover=true;this._addToHover(object);hoverChanged=true;if(object instanceof Node){properties.node=object.id;this.body.emitter.emit("hoverNode",properties);}else {properties.edge=object.id;this.body.emitter.emit("hoverEdge",properties);}}return hoverChanged;}/**
* Perform actions in response to a mouse movement.
*
* @param {Event} event
* @param {{x: number, y: number}} pointer | object with the x and y screen coordinates of the mouse
*/hoverObject(event,pointer){let object=this.getNodeAt(pointer);if(object===undefined){object=this.getEdgeAt(pointer);}let hoverChanged=false;// remove all node hover highlights
for(const nodeId in this.hoverObj.nodes){if(Object.prototype.hasOwnProperty.call(this.hoverObj.nodes,nodeId)){if(object===undefined||object instanceof Node&&object.id!=nodeId||object instanceof Edge){this.emitBlurEvent(event,pointer,this.hoverObj.nodes[nodeId]);delete this.hoverObj.nodes[nodeId];hoverChanged=true;}}}// removing all edge hover highlights
for(const edgeId in this.hoverObj.edges){if(Object.prototype.hasOwnProperty.call(this.hoverObj.edges,edgeId)){// if the hover has been changed here it means that the node has been hovered over or off
// we then do not use the emitBlurEvent method here.
if(hoverChanged===true){this.hoverObj.edges[edgeId].hover=false;delete this.hoverObj.edges[edgeId];}// if the blur remains the same and the object is undefined (mouse off) or another
// edge has been hovered, or another node has been hovered we blur the edge.
else if(object===undefined||object instanceof Edge&&object.id!=edgeId||object instanceof Node&&!object.hover){this.emitBlurEvent(event,pointer,this.hoverObj.edges[edgeId]);delete this.hoverObj.edges[edgeId];hoverChanged=true;}}}if(object!==undefined){const hoveredEdgesCount=Object.keys(this.hoverObj.edges).length;const hoveredNodesCount=Object.keys(this.hoverObj.nodes).length;const newOnlyHoveredEdge=object instanceof Edge&&hoveredEdgesCount===0&&hoveredNodesCount===0;const newOnlyHoveredNode=object instanceof Node&&hoveredEdgesCount===0&&hoveredNodesCount===0;if(hoverChanged||newOnlyHoveredEdge||newOnlyHoveredNode){hoverChanged=this.emitHoverEvent(event,pointer,object);}if(object instanceof Node&&this.options.hoverConnectedEdges===true){this._hoverConnectedEdges(object);}}if(hoverChanged===true){this.body.emitter.emit("_requestRedraw");}}/**
* Commit the selection changes but don't emit any events.
*/commitWithoutEmitting(){this._selectionAccumulator.commit();}/**
* Select and deselect nodes depending current selection change.
*
* For changing nodes, select/deselect events are fired.
*
* NOTE: For a given edge, if one connecting node is deselected and with the
* same click the other node is selected, no events for the edge will fire. It
* was selected and it will remain selected.
*
* @param {{x: number, y: number}} pointer - The x and y coordinates of the
* click, tap, dragend… that triggered this.
* @param {UIEvent} event - The event that triggered this.
*/commitAndEmit(pointer,event){let selected=false;const selectionChanges=this._selectionAccumulator.commit();const previousSelection={nodes:selectionChanges.nodes.previous,edges:selectionChanges.edges.previous};if(selectionChanges.edges.deleted.length>0){this.generateClickEvent("deselectEdge",event,pointer,previousSelection);selected=true;}if(selectionChanges.nodes.deleted.length>0){this.generateClickEvent("deselectNode",event,pointer,previousSelection);selected=true;}if(selectionChanges.nodes.added.length>0){this.generateClickEvent("selectNode",event,pointer);selected=true;}if(selectionChanges.edges.added.length>0){this.generateClickEvent("selectEdge",event,pointer);selected=true;}// fire the select event if anything has been selected or deselected
if(selected===true){// select or unselect
this.generateClickEvent("select",event,pointer);}}/**
* Retrieve the currently selected node and edge ids.
*
* @returns {{nodes: Array.<string>, edges: Array.<string>}} Arrays with the
* ids of the selected nodes and edges.
*/getSelection(){return {nodes:this.getSelectedNodeIds(),edges:this.getSelectedEdgeIds()};}/**
* Retrieve the currently selected nodes.
*
* @returns {Array} An array with selected nodes.
*/getSelectedNodes(){return this._selectionAccumulator.getNodes();}/**
* Retrieve the currently selected edges.
*
* @returns {Array} An array with selected edges.
*/getSelectedEdges(){return this._selectionAccumulator.getEdges();}/**
* Retrieve the currently selected node ids.
*
* @returns {Array} An array with the ids of the selected nodes.
*/getSelectedNodeIds(){return this._selectionAccumulator.getNodes().map(node=>node.id);}/**
* Retrieve the currently selected edge ids.
*
* @returns {Array} An array with the ids of the selected edges.
*/getSelectedEdgeIds(){return this._selectionAccumulator.getEdges().map(edge=>edge.id);}/**
* Updates the current selection
*
* @param {{nodes: Array.<string>, edges: Array.<string>}} selection
* @param {object} options Options
*/setSelection(selection,options={}){if(!selection||!selection.nodes&&!selection.edges){throw new TypeError("Selection must be an object with nodes and/or edges properties");}// first unselect any selected node, if option is true or undefined
if(options.unselectAll||options.unselectAll===undefined){this.unselectAll();}if(selection.nodes){for(const id of selection.nodes){const node=this.body.nodes[id];if(!node){throw new RangeError('Node with id "'+id+'" not found');}// don't select edges with it
this.selectObject(node,options.highlightEdges);}}if(selection.edges){for(const id of selection.edges){const edge=this.body.edges[id];if(!edge){throw new RangeError('Edge with id "'+id+'" not found');}this.selectObject(edge);}}this.body.emitter.emit("_requestRedraw");this._selectionAccumulator.commit();}/**
* select zero or more nodes with the option to highlight edges
*
* @param {number[] | string[]} selection An array with the ids of the
* selected nodes.
* @param {boolean} [highlightEdges]
*/selectNodes(selection,highlightEdges=true){if(!selection||selection.length===undefined)throw "Selection must be an array with ids";this.setSelection({nodes:selection},{highlightEdges:highlightEdges});}/**
* select zero or more edges
*
* @param {number[] | string[]} selection An array with the ids of the
* selected nodes.
*/selectEdges(selection){if(!selection||selection.length===undefined)throw "Selection must be an array with ids";this.setSelection({edges:selection});}/**
* Validate the selection: remove ids of nodes which no longer exist
*
* @private
*/updateSelection(){for(const node in this._selectionAccumulator.getNodes()){if(!Object.prototype.hasOwnProperty.call(this.body.nodes,node.id)){this._selectionAccumulator.deleteNodes(node);}}for(const edge in this._selectionAccumulator.getEdges()){if(!Object.prototype.hasOwnProperty.call(this.body.edges,edge.id)){this._selectionAccumulator.deleteEdges(edge);}}}/**
* Determine all the visual elements clicked which are on the given point.
*
* All elements are returned; this includes nodes, edges and their labels.
* The order returned is from highest to lowest, i.e. element 0 of the return
* value is the topmost item clicked on.
*
* The return value consists of an array of the following possible elements:
*
* - `{nodeId:number}` - node with given id clicked on
* - `{nodeId:number, labelId:0}` - label of node with given id clicked on
* - `{edgeId:number}` - edge with given id clicked on
* - `{edge:number, labelId:0}` - label of edge with given id clicked on
*
* ## NOTES
*
* - Currently, there is only one label associated with a node or an edge,
* but this is expected to change somewhere in the future.
* - Since there is no z-indexing yet, it is not really possible to set the nodes and
* edges in the correct order. For the time being, nodes come first.
*
* @param {point} pointer mouse position in screen coordinates
* @returns {Array.<nodeClickItem|nodeLabelClickItem|edgeClickItem|edgeLabelClickItem>}
* @private
*/getClickedItems(pointer){const point=this.canvas.DOMtoCanvas(pointer);const items=[];// Note reverse order; we want the topmost clicked items to be first in the array
// Also note that selected nodes are disregarded here; these normally display on top
const nodeIndices=this.body.nodeIndices;const nodes=this.body.nodes;for(let i=nodeIndices.length-1;i>=0;i--){const node=nodes[nodeIndices[i]];const ret=node.getItemsOnPoint(point);items.push.apply(items,ret);// Append the return value to the running list.
}const edgeIndices=this.body.edgeIndices;const edges=this.body.edges;for(let i=edgeIndices.length-1;i>=0;i--){const edge=edges[edgeIndices[i]];const ret=edge.getItemsOnPoint(point);items.push.apply(items,ret);// Append the return value to the running list.
}return items;}}/**
* Helper classes for LayoutEngine.
*
* Strategy pattern for usage of direction methods for hierarchical layouts.
*/ /**
* Interface definition for direction strategy classes.
*
* This class describes the interface for the Strategy
* pattern classes used to differentiate horizontal and vertical
* direction of hierarchical results.
*
* For a given direction, one coordinate will be 'fixed', meaning that it is
* determined by level.
* The other coordinate is 'unfixed', meaning that the nodes on a given level
* can still move along that coordinate. So:
*
* - `vertical` layout: `x` unfixed, `y` fixed per level
* - `horizontal` layout: `x` fixed per level, `y` unfixed
*
* The local methods are stubs and should be regarded as abstract.
* Derived classes **must** implement all the methods themselves.
*
* @private
*/class DirectionInterface{/**
* @ignore
*/abstract(){throw new Error("Can't instantiate abstract class!");}/**
* This is a dummy call which is used to suppress the jsdoc errors of type:
*
* "'param' is assigned a value but never used"
*
* @ignore
*/fake_use(){// Do nothing special
}/**
* Type to use to translate dynamic curves to, in the case of hierarchical layout.
* Dynamic curves do not work for these.
*
* The value should be perpendicular to the actual direction of the layout.
*
* @returns {string} Direction, either 'vertical' or 'horizontal'
*/curveType(){return this.abstract();}/**
* Return the value of the coordinate that is not fixed for this direction.
*
* @param {Node} node The node to read
* @returns {number} Value of the unfixed coordinate
*/getPosition(node){this.fake_use(node);return this.abstract();}/**
* Set the value of the coordinate that is not fixed for this direction.
*
* @param {Node} node The node to adjust
* @param {number} position
* @param {number} [level] if specified, the hierarchy level that this node should be fixed to
*/setPosition(node,position,level=undefined){this.fake_use(node,position,level);this.abstract();}/**
* Get the width of a tree.
*
* A `tree` here is a subset of nodes within the network which are not connected to other nodes,
* only among themselves. In essence, it is a sub-network.
*
* @param {number} index The index number of a tree
* @returns {number} the width of a tree in the view coordinates
*/getTreeSize(index){this.fake_use(index);return this.abstract();}/**
* Sort array of nodes on the unfixed coordinates.
*
* Note:** chrome has non-stable sorting implementation, which
* has a tendency to change the order of the array items,
* even if the custom sort function returns 0.
*
* For this reason, an external sort implementation is used,
* which has the added benefit of being faster than the standard
* platforms implementation. This has been verified on `node.js`,
* `firefox` and `chrome` (all linux).
*
* @param {Array.<Node>} nodeArray array of nodes to sort
*/sort(nodeArray){this.fake_use(nodeArray);this.abstract();}/**
* Assign the fixed coordinate of the node to the given level
*
* @param {Node} node The node to adjust
* @param {number} level The level to fix to
*/fix(node,level){this.fake_use(node,level);this.abstract();}/**
* Add an offset to the unfixed coordinate of the given node.
*
* @param {NodeId} nodeId Id of the node to adjust
* @param {number} diff Offset to add to the unfixed coordinate
*/shift(nodeId,diff){this.fake_use(nodeId,diff);this.abstract();}}/**
* Vertical Strategy
*
* Coordinate `y` is fixed on levels, coordinate `x` is unfixed.
*
* @augments DirectionInterface
* @private
*/class VerticalStrategy extends DirectionInterface{/**
* Constructor
*
* @param {object} layout reference to the parent LayoutEngine instance.
*/constructor(layout){super();this.layout=layout;}/** @inheritDoc */curveType(){return "horizontal";}/** @inheritDoc */getPosition(node){return node.x;}/** @inheritDoc */setPosition(node,position,level=undefined){if(level!==undefined){this.layout.hierarchical.addToOrdering(node,level);}node.x=position;}/** @inheritDoc */getTreeSize(index){const res=this.layout.hierarchical.getTreeSize(this.layout.body.nodes,index);return {min:res.min_x,max:res.max_x};}/** @inheritDoc */sort(nodeArray){nodeArray.sort(function(a,b){return a.x-b.x;});}/** @inheritDoc */fix(node,level){node.y=this.layout.options.hierarchical.levelSeparation*level;node.options.fixed.y=true;}/** @inheritDoc */shift(nodeId,diff){this.layout.body.nodes[nodeId].x+=diff;}}/**
* Horizontal Strategy
*
* Coordinate `x` is fixed on levels, coordinate `y` is unfixed.
*
* @augments DirectionInterface
* @private
*/class HorizontalStrategy extends DirectionInterface{/**
* Constructor
*
* @param {object} layout reference to the parent LayoutEngine instance.
*/constructor(layout){super();this.layout=layout;}/** @inheritDoc */curveType(){return "vertical";}/** @inheritDoc */getPosition(node){return node.y;}/** @inheritDoc */setPosition(node,position,level=undefined){if(level!==undefined){this.layout.hierarchical.addToOrdering(node,level);}node.y=position;}/** @inheritDoc */getTreeSize(index){const res=this.layout.hierarchical.getTreeSize(this.layout.body.nodes,index);return {min:res.min_y,max:res.max_y};}/** @inheritDoc */sort(nodeArray){nodeArray.sort(function(a,b){return a.y-b.y;});}/** @inheritDoc */fix(node,level){node.x=this.layout.options.hierarchical.levelSeparation*level;node.options.fixed.x=true;}/** @inheritDoc */shift(nodeId,diff){this.layout.body.nodes[nodeId].y+=diff;}}/**
* Try to assign levels to nodes according to their positions in the cyclic “hierarchy”.
*
* @param nodes - Visible nodes of the graph.
* @param levels - If present levels will be added to it, if not a new object will be created.
* @returns Populated node levels.
*/function fillLevelsByDirectionCyclic(nodes,levels){const edges=new Set();nodes.forEach(node=>{node.edges.forEach(edge=>{if(edge.connected){edges.add(edge);}});});edges.forEach(edge=>{const fromId=edge.from.id;const toId=edge.to.id;if(levels[fromId]==null){levels[fromId]=0;}if(levels[toId]==null||levels[fromId]>=levels[toId]){levels[toId]=levels[fromId]+1;}});return levels;}/**
* Assign levels to nodes according to their positions in the hierarchy. Leaves will be lined up at the bottom and all other nodes as close to their children as possible.
*
* @param nodes - Visible nodes of the graph.
* @returns Populated node levels.
*/function fillLevelsByDirectionLeaves(nodes){return fillLevelsByDirection(// Pick only leaves (nodes without children).
node=>node.edges// Take only visible nodes into account.
.filter(edge=>nodes.has(edge.toId))// Check that all edges lead to this node (leaf).
.every(edge=>edge.to===node),// Use the lowest level.
(newLevel,oldLevel)=>oldLevel>newLevel,// Go against the direction of the edges.
"from",nodes);}/**
* Assign levels to nodes according to their positions in the hierarchy. Roots will be lined up at the top and all nodes as close to their parents as possible.
*
* @param nodes - Visible nodes of the graph.
* @returns Populated node levels.
*/function fillLevelsByDirectionRoots(nodes){return fillLevelsByDirection(// Pick only roots (nodes without parents).
node=>node.edges// Take only visible nodes into account.
.filter(edge=>nodes.has(edge.toId))// Check that all edges lead from this node (root).
.every(edge=>edge.from===node),// Use the highest level.
(newLevel,oldLevel)=>oldLevel<newLevel,// Go in the direction of the edges.
"to",nodes);}/**
* Assign levels to nodes according to their positions in the hierarchy.
*
* @param isEntryNode - Checks and return true if the graph should be traversed from this node.
* @param shouldLevelBeReplaced - Checks and returns true if the level of given node should be updated to the new value.
* @param direction - Wheter the graph should be traversed in the direction of the edges `"to"` or in the other way `"from"`.
* @param nodes - Visible nodes of the graph.
* @returns Populated node levels.
*/function fillLevelsByDirection(isEntryNode,shouldLevelBeReplaced,direction,nodes){const levels=Object.create(null);// If acyclic, the graph can be walked through with (most likely way) fewer
// steps than the number bellow. The exact value isn't too important as long
// as it's quick to compute (doesn't impact acyclic graphs too much), is
// higher than the number of steps actually needed (doesn't cut off before
// acyclic graph is walked through) and prevents infinite loops (cuts off for
// cyclic graphs).
const limit=[...nodes.values()].reduce((acc,node)=>acc+1+node.edges.length,0);const edgeIdProp=direction+"Id";const newLevelDiff=direction==="to"?1:-1;for(const[entryNodeId,entryNode]of nodes){if(// Skip if the node is not visible.
!nodes.has(entryNodeId)||// Skip if the node is not an entry node.
!isEntryNode(entryNode)){continue;}// Line up all the entry nodes on level 0.
levels[entryNodeId]=0;const stack=[entryNode];let done=0;let node;while(node=stack.pop()){if(!nodes.has(entryNodeId)){// Skip if the node is not visible.
continue;}const newLevel=levels[node.id]+newLevelDiff;node.edges.filter(edge=>// Ignore disconnected edges.
edge.connected&&// Ignore circular edges.
edge.to!==edge.from&&// Ignore edges leading to the node that's currently being processed.
edge[direction]!==node&&// Ignore edges connecting to an invisible node.
nodes.has(edge.toId)&&// Ignore edges connecting from an invisible node.
nodes.has(edge.fromId)).forEach(edge=>{const targetNodeId=edge[edgeIdProp];const oldLevel=levels[targetNodeId];if(oldLevel==null||shouldLevelBeReplaced(newLevel,oldLevel)){levels[targetNodeId]=newLevel;stack.push(edge[direction]);}});if(done>limit){// This would run forever on a cyclic graph.
return fillLevelsByDirectionCyclic(nodes,levels);}else {++done;}}}return levels;}/**
* There's a mix-up with terms in the code. Following are the formal definitions:
*
* tree - a strict hierarchical network, i.e. every node has at most one parent
* forest - a collection of trees. These distinct trees are thus not connected.
*
* So:
* - in a network that is not a tree, there exist nodes with multiple parents.
* - a network consisting of unconnected sub-networks, of which at least one
* is not a tree, is not a forest.
*
* In the code, the definitions are:
*
* tree - any disconnected sub-network, strict hierarchical or not.
* forest - a bunch of these sub-networks
*
* The difference between tree and not-tree is important in the code, notably within
* to the block-shifting algorithm. The algorithm assumes formal trees and fails
* for not-trees, often in a spectacular manner (search for 'exploding network' in the issues).
*
* In order to distinguish the definitions in the following code, the adjective 'formal' is
* used. If 'formal' is absent, you must assume the non-formal definition.
*
* ----------------------------------------------------------------------------------
* NOTES
* =====
*
* A hierarchical layout is a different thing from a hierarchical network.
* The layout is a way to arrange the nodes in the view; this can be done
* on non-hierarchical networks as well. The converse is also possible.
*/ /**
* Container for derived data on current network, relating to hierarchy.
*
* @private
*/class HierarchicalStatus{/**
* @ignore
*/constructor(){this.childrenReference={};// child id's per node id
this.parentReference={};// parent id's per node id
this.trees={};// tree id per node id; i.e. to which tree does given node id belong
this.distributionOrdering={};// The nodes per level, in the display order
this.levels={};// hierarchy level per node id
this.distributionIndex={};// The position of the node in the level sorting order, per node id.
this.isTree=false;// True if current network is a formal tree
this.treeIndex=-1;// Highest tree id in current network.
}/**
* Add the relation between given nodes to the current state.
*
* @param {Node.id} parentNodeId
* @param {Node.id} childNodeId
*/addRelation(parentNodeId,childNodeId){if(this.childrenReference[parentNodeId]===undefined){this.childrenReference[parentNodeId]=[];}this.childrenReference[parentNodeId].push(childNodeId);if(this.parentReference[childNodeId]===undefined){this.parentReference[childNodeId]=[];}this.parentReference[childNodeId].push(parentNodeId);}/**
* Check if the current state is for a formal tree or formal forest.
*
* This is the case if every node has at most one parent.
*
* Pre: parentReference init'ed properly for current network
*/checkIfTree(){for(const i in this.parentReference){if(this.parentReference[i].length>1){this.isTree=false;return;}}this.isTree=true;}/**
* Return the number of separate trees in the current network.
*
* @returns {number}
*/numTrees(){return this.treeIndex+1;// This assumes the indexes are assigned consecitively
}/**
* Assign a tree id to a node
*
* @param {Node} node
* @param {string|number} treeId
*/setTreeIndex(node,treeId){if(treeId===undefined)return;// Don't bother
if(this.trees[node.id]===undefined){this.trees[node.id]=treeId;this.treeIndex=Math.max(treeId,this.treeIndex);}}/**
* Ensure level for given id is defined.
*
* Sets level to zero for given node id if not already present
*
* @param {Node.id} nodeId
*/ensureLevel(nodeId){if(this.levels[nodeId]===undefined){this.levels[nodeId]=0;}}/**
* get the maximum level of a branch.
*
* TODO: Never entered; find a test case to test this!
*
* @param {Node.id} nodeId
* @returns {number}
*/getMaxLevel(nodeId){const accumulator={};const _getMaxLevel=nodeId=>{if(accumulator[nodeId]!==undefined){return accumulator[nodeId];}let level=this.levels[nodeId];if(this.childrenReference[nodeId]){const children=this.childrenReference[nodeId];if(children.length>0){for(let i=0;i<children.length;i++){level=Math.max(level,_getMaxLevel(children[i]));}}}accumulator[nodeId]=level;return level;};return _getMaxLevel(nodeId);}/**
*
* @param {Node} nodeA
* @param {Node} nodeB
*/levelDownstream(nodeA,nodeB){if(this.levels[nodeB.id]===undefined){// set initial level
if(this.levels[nodeA.id]===undefined){this.levels[nodeA.id]=0;}// set level
this.levels[nodeB.id]=this.levels[nodeA.id]+1;}}/**
* Small util method to set the minimum levels of the nodes to zero.
*
* @param {Array.<Node>} nodes
*/setMinLevelToZero(nodes){let minLevel=1e9;// get the minimum level
for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){if(this.levels[nodeId]!==undefined){minLevel=Math.min(this.levels[nodeId],minLevel);}}}// subtract the minimum from the set so we have a range starting from 0
for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){if(this.levels[nodeId]!==undefined){this.levels[nodeId]-=minLevel;}}}}/**
* Get the min and max xy-coordinates of a given tree
*
* @param {Array.<Node>} nodes
* @param {number} index
* @returns {{min_x: number, max_x: number, min_y: number, max_y: number}}
*/getTreeSize(nodes,index){let min_x=1e9;let max_x=-1e9;let min_y=1e9;let max_y=-1e9;for(const nodeId in this.trees){if(Object.prototype.hasOwnProperty.call(this.trees,nodeId)){if(this.trees[nodeId]===index){const node=nodes[nodeId];min_x=Math.min(node.x,min_x);max_x=Math.max(node.x,max_x);min_y=Math.min(node.y,min_y);max_y=Math.max(node.y,max_y);}}}return {min_x:min_x,max_x:max_x,min_y:min_y,max_y:max_y};}/**
* Check if two nodes have the same parent(s)
*
* @param {Node} node1
* @param {Node} node2
* @returns {boolean} true if the two nodes have a same ancestor node, false otherwise
*/hasSameParent(node1,node2){const parents1=this.parentReference[node1.id];const parents2=this.parentReference[node2.id];if(parents1===undefined||parents2===undefined){return false;}for(let i=0;i<parents1.length;i++){for(let j=0;j<parents2.length;j++){if(parents1[i]==parents2[j]){return true;}}}return false;}/**
* Check if two nodes are in the same tree.
*
* @param {Node} node1
* @param {Node} node2
* @returns {boolean} true if this is so, false otherwise
*/inSameSubNetwork(node1,node2){return this.trees[node1.id]===this.trees[node2.id];}/**
* Get a list of the distinct levels in the current network
*
* @returns {Array}
*/getLevels(){return Object.keys(this.distributionOrdering);}/**
* Add a node to the ordering per level
*
* @param {Node} node
* @param {number} level
*/addToOrdering(node,level){if(this.distributionOrdering[level]===undefined){this.distributionOrdering[level]=[];}let isPresent=false;const curLevel=this.distributionOrdering[level];for(const n in curLevel){//if (curLevel[n].id === node.id) {
if(curLevel[n]===node){isPresent=true;break;}}if(!isPresent){this.distributionOrdering[level].push(node);this.distributionIndex[node.id]=this.distributionOrdering[level].length-1;}}}/**
* The Layout Engine
*/class LayoutEngine{/**
* @param {object} body
*/constructor(body){this.body=body;// Make sure there always is some RNG because the setOptions method won't
// set it unless there's a seed for it.
this._resetRNG(Math.random()+":"+Date.now());this.setPhysics=false;this.options={};this.optionsBackup={physics:{}};this.defaultOptions={randomSeed:undefined,improvedLayout:true,clusterThreshold:150,hierarchical:{enabled:false,levelSeparation:150,nodeSpacing:100,treeSpacing:200,blockShifting:true,edgeMinimization:true,parentCentralization:true,direction:"UD",// UD, DU, LR, RL
sortMethod:"hubsize"// hubsize, directed
}};Object.assign(this.options,this.defaultOptions);this.bindEventListeners();}/**
* Binds event listeners
*/bindEventListeners(){this.body.emitter.on("_dataChanged",()=>{this.setupHierarchicalLayout();});this.body.emitter.on("_dataLoaded",()=>{this.layoutNetwork();});this.body.emitter.on("_resetHierarchicalLayout",()=>{this.setupHierarchicalLayout();});this.body.emitter.on("_adjustEdgesForHierarchicalLayout",()=>{if(this.options.hierarchical.enabled!==true){return;}// get the type of static smooth curve in case it is required
const type=this.direction.curveType();// force all edges into static smooth curves.
this.body.emitter.emit("_forceDisableDynamicCurves",type,false);});}/**
*
* @param {object} options
* @param {object} allOptions
* @returns {object}
*/setOptions(options,allOptions){if(options!==undefined){const hierarchical=this.options.hierarchical;const prevHierarchicalState=hierarchical.enabled;selectiveDeepExtend(["randomSeed","improvedLayout","clusterThreshold"],this.options,options);mergeOptions(this.options,options,"hierarchical");if(options.randomSeed!==undefined){this._resetRNG(options.randomSeed);}if(hierarchical.enabled===true){if(prevHierarchicalState===true){// refresh the overridden options for nodes and edges.
this.body.emitter.emit("refresh",true);}// make sure the level separation is the right way up
if(hierarchical.direction==="RL"||hierarchical.direction==="DU"){if(hierarchical.levelSeparation>0){hierarchical.levelSeparation*=-1;}}else {if(hierarchical.levelSeparation<0){hierarchical.levelSeparation*=-1;}}this.setDirectionStrategy();this.body.emitter.emit("_resetHierarchicalLayout");// because the hierarchical system needs it's own physics and smooth curve settings,
// we adapt the other options if needed.
return this.adaptAllOptionsForHierarchicalLayout(allOptions);}else {if(prevHierarchicalState===true){// refresh the overridden options for nodes and edges.
this.body.emitter.emit("refresh");return deepExtend(allOptions,this.optionsBackup);}}}return allOptions;}/**
* Reset the random number generator with given seed.
*
* @param {any} seed - The seed that will be forwarded the the RNG.
*/_resetRNG(seed){this.initialRandomSeed=seed;this._rng=Alea(this.initialRandomSeed);}/**
*
* @param {object} allOptions
* @returns {object}
*/adaptAllOptionsForHierarchicalLayout(allOptions){if(this.options.hierarchical.enabled===true){const backupPhysics=this.optionsBackup.physics;// set the physics
if(allOptions.physics===undefined||allOptions.physics===true){allOptions.physics={enabled:backupPhysics.enabled===undefined?true:backupPhysics.enabled,solver:"hierarchicalRepulsion"};backupPhysics.enabled=backupPhysics.enabled===undefined?true:backupPhysics.enabled;backupPhysics.solver=backupPhysics.solver||"barnesHut";}else if(typeof allOptions.physics==="object"){backupPhysics.enabled=allOptions.physics.enabled===undefined?true:allOptions.physics.enabled;backupPhysics.solver=allOptions.physics.solver||"barnesHut";allOptions.physics.solver="hierarchicalRepulsion";}else if(allOptions.physics!==false){backupPhysics.solver="barnesHut";allOptions.physics={solver:"hierarchicalRepulsion"};}// get the type of static smooth curve in case it is required
let type=this.direction.curveType();// disable smooth curves if nothing is defined. If smooth curves have been turned on,
// turn them into static smooth curves.
if(allOptions.edges===undefined){this.optionsBackup.edges={smooth:{enabled:true,type:"dynamic"}};allOptions.edges={smooth:false};}else if(allOptions.edges.smooth===undefined){this.optionsBackup.edges={smooth:{enabled:true,type:"dynamic"}};allOptions.edges.smooth=false;}else {if(typeof allOptions.edges.smooth==="boolean"){this.optionsBackup.edges={smooth:allOptions.edges.smooth};allOptions.edges.smooth={enabled:allOptions.edges.smooth,type:type};}else {const smooth=allOptions.edges.smooth;// allow custom types except for dynamic
if(smooth.type!==undefined&&smooth.type!=="dynamic"){type=smooth.type;}// TODO: this is options merging; see if the standard routines can be used here.
this.optionsBackup.edges={smooth:{enabled:smooth.enabled===undefined?true:smooth.enabled,type:smooth.type===undefined?"dynamic":smooth.type,roundness:smooth.roundness===undefined?0.5:smooth.roundness,forceDirection:smooth.forceDirection===undefined?false:smooth.forceDirection}};// NOTE: Copying an object to self; this is basically setting defaults for undefined variables
allOptions.edges.smooth={enabled:smooth.enabled===undefined?true:smooth.enabled,type:type,roundness:smooth.roundness===undefined?0.5:smooth.roundness,forceDirection:smooth.forceDirection===undefined?false:smooth.forceDirection};}}// Force all edges into static smooth curves.
// Only applies to edges that do not use the global options for smooth.
this.body.emitter.emit("_forceDisableDynamicCurves",type);}return allOptions;}/**
*
* @param {Array.<Node>} nodesArray
*/positionInitially(nodesArray){if(this.options.hierarchical.enabled!==true){this._resetRNG(this.initialRandomSeed);const radius=nodesArray.length+50;for(let i=0;i<nodesArray.length;i++){const node=nodesArray[i];const angle=2*Math.PI*this._rng();if(node.x===undefined){node.x=radius*Math.cos(angle);}if(node.y===undefined){node.y=radius*Math.sin(angle);}}}}/**
* Use Kamada Kawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
* cluster them first to reduce the amount.
*/layoutNetwork(){if(this.options.hierarchical.enabled!==true&&this.options.improvedLayout===true){const indices=this.body.nodeIndices;// first check if we should Kamada Kawai to layout. The threshold is if less than half of the visible
// nodes have predefined positions we use this.
let positionDefined=0;for(let i=0;i<indices.length;i++){const node=this.body.nodes[indices[i]];if(node.predefinedPosition===true){positionDefined+=1;}}// if less than half of the nodes have a predefined position we continue
if(positionDefined<0.5*indices.length){const MAX_LEVELS=10;let level=0;const clusterThreshold=this.options.clusterThreshold;//
// Define the options for the hidden cluster nodes
// These options don't propagate outside the clustering phase.
//
// Some options are explicitly disabled, because they may be set in group or default node options.
// The clusters are never displayed, so most explicit settings here serve as performance optimizations.
//
// The explicit setting of 'shape' is to avoid `shape: 'image'`; images are not passed to the hidden
// cluster nodes, leading to an exception on creation.
//
// All settings here are performance related, except when noted otherwise.
//
const clusterOptions={clusterNodeProperties:{shape:"ellipse",// Bugfix: avoid type 'image', no images supplied
label:"",// avoid label handling
group:"",// avoid group handling
font:{multi:false}// avoid font propagation
},clusterEdgeProperties:{label:"",// avoid label handling
font:{multi:false},// avoid font propagation
smooth:{enabled:false// avoid drawing penalty for complex edges
}}};// if there are a lot of nodes, we cluster before we run the algorithm.
// NOTE: this part fails to find clusters for large scale-free networks, which should
// be easily clusterable.
// TODO: examine why this is so
if(indices.length>clusterThreshold){const startLength=indices.length;while(indices.length>clusterThreshold&&level<=MAX_LEVELS){//console.time("clustering")
level+=1;const before=indices.length;// if there are many nodes we do a hubsize cluster
if(level%3===0){this.body.modules.clustering.clusterBridges(clusterOptions);}else {this.body.modules.clustering.clusterOutliers(clusterOptions);}const after=indices.length;if(before==after&&level%3!==0){this._declusterAll();this.body.emitter.emit("_layoutFailed");console.info("This network could not be positioned by this version of the improved layout algorithm."+" Please disable improvedLayout for better performance.");return;}//console.timeEnd("clustering")
//console.log(before,level,after);
}// increase the size of the edges
this.body.modules.kamadaKawai.setOptions({springLength:Math.max(150,2*startLength)});}if(level>MAX_LEVELS){console.info("The clustering didn't succeed within the amount of interations allowed,"+" progressing with partial result.");}// position the system for these nodes and edges
this.body.modules.kamadaKawai.solve(indices,this.body.edgeIndices,true);// shift to center point
this._shiftToCenter();// perturb the nodes a little bit to force the physics to kick in
const offset=70;for(let i=0;i<indices.length;i++){// Only perturb the nodes that aren't fixed
const node=this.body.nodes[indices[i]];if(node.predefinedPosition===false){node.x+=(0.5-this._rng())*offset;node.y+=(0.5-this._rng())*offset;}}// uncluster all clusters
this._declusterAll();// reposition all bezier nodes.
this.body.emitter.emit("_repositionBezierNodes");}}}/**
* Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
*
* @private
*/_shiftToCenter(){const range=NetworkUtil.getRangeCore(this.body.nodes,this.body.nodeIndices);const center=NetworkUtil.findCenter(range);for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];node.x-=center.x;node.y-=center.y;}}/**
* Expands all clusters
*
* @private
*/_declusterAll(){let clustersPresent=true;while(clustersPresent===true){clustersPresent=false;for(let i=0;i<this.body.nodeIndices.length;i++){if(this.body.nodes[this.body.nodeIndices[i]].isCluster===true){clustersPresent=true;this.body.modules.clustering.openCluster(this.body.nodeIndices[i],{},false);}}if(clustersPresent===true){this.body.emitter.emit("_dataChanged");}}}/**
*
* @returns {number|*}
*/getSeed(){return this.initialRandomSeed;}/**
* This is the main function to layout the nodes in a hierarchical way.
* It checks if the node details are supplied correctly
*
* @private
*/setupHierarchicalLayout(){if(this.options.hierarchical.enabled===true&&this.body.nodeIndices.length>0){// get the size of the largest hubs and check if the user has defined a level for a node.
let node,nodeId;let definedLevel=false;let undefinedLevel=false;this.lastNodeOnLevel={};this.hierarchical=new HierarchicalStatus();for(nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){node=this.body.nodes[nodeId];if(node.options.level!==undefined){definedLevel=true;this.hierarchical.levels[nodeId]=node.options.level;}else {undefinedLevel=true;}}}// if the user defined some levels but not all, alert and run without hierarchical layout
if(undefinedLevel===true&&definedLevel===true){throw new Error("To use the hierarchical layout, nodes require either no predefined levels"+" or levels have to be defined for all nodes.");}else {// define levels if undefined by the users. Based on hubsize.
if(undefinedLevel===true){const sortMethod=this.options.hierarchical.sortMethod;if(sortMethod==="hubsize"){this._determineLevelsByHubsize();}else if(sortMethod==="directed"){this._determineLevelsDirected();}else if(sortMethod==="custom"){this._determineLevelsCustomCallback();}}// fallback for cases where there are nodes but no edges
for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){this.hierarchical.ensureLevel(nodeId);}}// check the distribution of the nodes per level.
const distribution=this._getDistribution();// get the parent children relations.
this._generateMap();// place the nodes on the canvas.
this._placeNodesByHierarchy(distribution);// condense the whitespace.
this._condenseHierarchy();// shift to center so gravity does not have to do much
this._shiftToCenter();}}}/**
* @private
*/_condenseHierarchy(){// Global var in this scope to define when the movement has stopped.
let stillShifting=false;const branches={};// first we have some methods to help shifting trees around.
// the main method to shift the trees
const shiftTrees=()=>{const treeSizes=getTreeSizes();let shiftBy=0;for(let i=0;i<treeSizes.length-1;i++){const diff=treeSizes[i].max-treeSizes[i+1].min;shiftBy+=diff+this.options.hierarchical.treeSpacing;shiftTree(i+1,shiftBy);}};// shift a single tree by an offset
const shiftTree=(index,offset)=>{const trees=this.hierarchical.trees;for(const nodeId in trees){if(Object.prototype.hasOwnProperty.call(trees,nodeId)){if(trees[nodeId]===index){this.direction.shift(nodeId,offset);}}}};// get the width of all trees
const getTreeSizes=()=>{const treeWidths=[];for(let i=0;i<this.hierarchical.numTrees();i++){treeWidths.push(this.direction.getTreeSize(i));}return treeWidths;};// get a map of all nodes in this branch
const getBranchNodes=(source,map)=>{if(map[source.id]){return;}map[source.id]=true;if(this.hierarchical.childrenReference[source.id]){const children=this.hierarchical.childrenReference[source.id];if(children.length>0){for(let i=0;i<children.length;i++){getBranchNodes(this.body.nodes[children[i]],map);}}}};// get a min max width as well as the maximum movement space it has on either sides
// we use min max terminology because width and height can interchange depending on the direction of the layout
const getBranchBoundary=(branchMap,maxLevel=1e9)=>{let minSpace=1e9;let maxSpace=1e9;let min=1e9;let max=-1e9;for(const branchNode in branchMap){if(Object.prototype.hasOwnProperty.call(branchMap,branchNode)){const node=this.body.nodes[branchNode];const level=this.hierarchical.levels[node.id];const position=this.direction.getPosition(node);// get the space around the node.
const[minSpaceNode,maxSpaceNode]=this._getSpaceAroundNode(node,branchMap);minSpace=Math.min(minSpaceNode,minSpace);maxSpace=Math.min(maxSpaceNode,maxSpace);// the width is only relevant for the levels two nodes have in common. This is why we filter on this.
if(level<=maxLevel){min=Math.min(position,min);max=Math.max(position,max);}}}return [min,max,minSpace,maxSpace];};// check what the maximum level is these nodes have in common.
const getCollisionLevel=(node1,node2)=>{const maxLevel1=this.hierarchical.getMaxLevel(node1.id);const maxLevel2=this.hierarchical.getMaxLevel(node2.id);return Math.min(maxLevel1,maxLevel2);};/**
* Condense elements. These can be nodes or branches depending on the callback.
*
* @param {Function} callback
* @param {Array.<number>} levels
* @param {*} centerParents
*/const shiftElementsCloser=(callback,levels,centerParents)=>{const hier=this.hierarchical;for(let i=0;i<levels.length;i++){const level=levels[i];const levelNodes=hier.distributionOrdering[level];if(levelNodes.length>1){for(let j=0;j<levelNodes.length-1;j++){const node1=levelNodes[j];const node2=levelNodes[j+1];// NOTE: logic maintained as it was; if nodes have same ancestor,
// then of course they are in the same sub-network.
if(hier.hasSameParent(node1,node2)&&hier.inSameSubNetwork(node1,node2)){callback(node1,node2,centerParents);}}}}};// callback for shifting branches
const branchShiftCallback=(node1,node2,centerParent=false)=>{//window.CALLBACKS.push(() => {
const pos1=this.direction.getPosition(node1);const pos2=this.direction.getPosition(node2);const diffAbs=Math.abs(pos2-pos1);const nodeSpacing=this.options.hierarchical.nodeSpacing;//console.log("NOW CHECKING:", node1.id, node2.id, diffAbs);
if(diffAbs>nodeSpacing){const branchNodes1={};const branchNodes2={};getBranchNodes(node1,branchNodes1);getBranchNodes(node2,branchNodes2);// check the largest distance between the branches
const maxLevel=getCollisionLevel(node1,node2);const branchNodeBoundary1=getBranchBoundary(branchNodes1,maxLevel);const branchNodeBoundary2=getBranchBoundary(branchNodes2,maxLevel);const max1=branchNodeBoundary1[1];const min2=branchNodeBoundary2[0];const minSpace2=branchNodeBoundary2[2];//console.log(node1.id, getBranchBoundary(branchNodes1, maxLevel), node2.id,
// getBranchBoundary(branchNodes2, maxLevel), maxLevel);
const diffBranch=Math.abs(max1-min2);if(diffBranch>nodeSpacing){let offset=max1-min2+nodeSpacing;if(offset<-minSpace2+nodeSpacing){offset=-minSpace2+nodeSpacing;//console.log("RESETTING OFFSET", max1 - min2 + this.options.hierarchical.nodeSpacing, -minSpace2, offset);
}if(offset<0){//console.log("SHIFTING", node2.id, offset);
this._shiftBlock(node2.id,offset);stillShifting=true;if(centerParent===true)this._centerParent(node2);}}}//this.body.emitter.emit("_redraw");})
};const minimizeEdgeLength=(iterations,node)=>{//window.CALLBACKS.push(() => {
// console.log("ts",node.id);
const nodeId=node.id;const allEdges=node.edges;const nodeLevel=this.hierarchical.levels[node.id];// gather constants
const C2=this.options.hierarchical.levelSeparation*this.options.hierarchical.levelSeparation;const referenceNodes={};const aboveEdges=[];for(let i=0;i<allEdges.length;i++){const edge=allEdges[i];if(edge.toId!=edge.fromId){const otherNode=edge.toId==nodeId?edge.from:edge.to;referenceNodes[allEdges[i].id]=otherNode;if(this.hierarchical.levels[otherNode.id]<nodeLevel){aboveEdges.push(edge);}}}// differentiated sum of lengths based on only moving one node over one axis
const getFx=(point,edges)=>{let sum=0;for(let i=0;i<edges.length;i++){if(referenceNodes[edges[i].id]!==undefined){const a=this.direction.getPosition(referenceNodes[edges[i].id])-point;sum+=a/Math.sqrt(a*a+C2);}}return sum;};// doubly differentiated sum of lengths based on only moving one node over one axis
const getDFx=(point,edges)=>{let sum=0;for(let i=0;i<edges.length;i++){if(referenceNodes[edges[i].id]!==undefined){const a=this.direction.getPosition(referenceNodes[edges[i].id])-point;sum-=C2*Math.pow(a*a+C2,-1.5);}}return sum;};const getGuess=(iterations,edges)=>{let guess=this.direction.getPosition(node);// Newton's method for optimization
const guessMap={};for(let i=0;i<iterations;i++){const fx=getFx(guess,edges);const dfx=getDFx(guess,edges);// we limit the movement to avoid instability.
const limit=40;const ratio=Math.max(-limit,Math.min(limit,Math.round(fx/dfx)));guess=guess-ratio;// reduce duplicates
if(guessMap[guess]!==undefined){break;}guessMap[guess]=i;}return guess;};const moveBranch=guess=>{// position node if there is space
const nodePosition=this.direction.getPosition(node);// check movable area of the branch
if(branches[node.id]===undefined){const branchNodes={};getBranchNodes(node,branchNodes);branches[node.id]=branchNodes;}const branchBoundary=getBranchBoundary(branches[node.id]);const minSpaceBranch=branchBoundary[2];const maxSpaceBranch=branchBoundary[3];const diff=guess-nodePosition;// check if we are allowed to move the node:
let branchOffset=0;if(diff>0){branchOffset=Math.min(diff,maxSpaceBranch-this.options.hierarchical.nodeSpacing);}else if(diff<0){branchOffset=-Math.min(-diff,minSpaceBranch-this.options.hierarchical.nodeSpacing);}if(branchOffset!=0){//console.log("moving branch:",branchOffset, maxSpaceBranch, minSpaceBranch)
this._shiftBlock(node.id,branchOffset);//this.body.emitter.emit("_redraw");
stillShifting=true;}};const moveNode=guess=>{const nodePosition=this.direction.getPosition(node);// position node if there is space
const[minSpace,maxSpace]=this._getSpaceAroundNode(node);const diff=guess-nodePosition;// check if we are allowed to move the node:
let newPosition=nodePosition;if(diff>0){newPosition=Math.min(nodePosition+(maxSpace-this.options.hierarchical.nodeSpacing),guess);}else if(diff<0){newPosition=Math.max(nodePosition-(minSpace-this.options.hierarchical.nodeSpacing),guess);}if(newPosition!==nodePosition){//console.log("moving Node:",diff, minSpace, maxSpace);
this.direction.setPosition(node,newPosition);//this.body.emitter.emit("_redraw");
stillShifting=true;}};let guess=getGuess(iterations,aboveEdges);moveBranch(guess);guess=getGuess(iterations,allEdges);moveNode(guess);//})
};// method to remove whitespace between branches. Because we do bottom up, we can center the parents.
const minimizeEdgeLengthBottomUp=iterations=>{let levels=this.hierarchical.getLevels();levels=levels.reverse();for(let i=0;i<iterations;i++){stillShifting=false;for(let j=0;j<levels.length;j++){const level=levels[j];const levelNodes=this.hierarchical.distributionOrdering[level];for(let k=0;k<levelNodes.length;k++){minimizeEdgeLength(1000,levelNodes[k]);}}if(stillShifting!==true){//console.log("FINISHED minimizeEdgeLengthBottomUp IN " + i);
break;}}};// method to remove whitespace between branches. Because we do bottom up, we can center the parents.
const shiftBranchesCloserBottomUp=iterations=>{let levels=this.hierarchical.getLevels();levels=levels.reverse();for(let i=0;i<iterations;i++){stillShifting=false;shiftElementsCloser(branchShiftCallback,levels,true);if(stillShifting!==true){//console.log("FINISHED shiftBranchesCloserBottomUp IN " + (i+1));
break;}}};// center all parents
const centerAllParents=()=>{for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId))this._centerParent(this.body.nodes[nodeId]);}};// center all parents
const centerAllParentsBottomUp=()=>{let levels=this.hierarchical.getLevels();levels=levels.reverse();for(let i=0;i<levels.length;i++){const level=levels[i];const levelNodes=this.hierarchical.distributionOrdering[level];for(let j=0;j<levelNodes.length;j++){this._centerParent(levelNodes[j]);}}};// the actual work is done here.
if(this.options.hierarchical.blockShifting===true){shiftBranchesCloserBottomUp(5);centerAllParents();}// minimize edge length
if(this.options.hierarchical.edgeMinimization===true){minimizeEdgeLengthBottomUp(20);}if(this.options.hierarchical.parentCentralization===true){centerAllParentsBottomUp();}shiftTrees();}/**
* This gives the space around the node. IF a map is supplied, it will only check against nodes NOT in the map.
* This is used to only get the distances to nodes outside of a branch.
*
* @param {Node} node
* @param {{Node.id: vis.Node}} map
* @returns {number[]}
* @private
*/_getSpaceAroundNode(node,map){let useMap=true;if(map===undefined){useMap=false;}const level=this.hierarchical.levels[node.id];if(level!==undefined){const index=this.hierarchical.distributionIndex[node.id];const position=this.direction.getPosition(node);const ordering=this.hierarchical.distributionOrdering[level];let minSpace=1e9;let maxSpace=1e9;if(index!==0){const prevNode=ordering[index-1];if(useMap===true&&map[prevNode.id]===undefined||useMap===false){const prevPos=this.direction.getPosition(prevNode);minSpace=position-prevPos;}}if(index!=ordering.length-1){const nextNode=ordering[index+1];if(useMap===true&&map[nextNode.id]===undefined||useMap===false){const nextPos=this.direction.getPosition(nextNode);maxSpace=Math.min(maxSpace,nextPos-position);}}return [minSpace,maxSpace];}else {return [0,0];}}/**
* We use this method to center a parent node and check if it does not cross other nodes when it does.
*
* @param {Node} node
* @private
*/_centerParent(node){if(this.hierarchical.parentReference[node.id]){const parents=this.hierarchical.parentReference[node.id];for(let i=0;i<parents.length;i++){const parentId=parents[i];const parentNode=this.body.nodes[parentId];const children=this.hierarchical.childrenReference[parentId];if(children!==undefined){// get the range of the children
const newPosition=this._getCenterPosition(children);const position=this.direction.getPosition(parentNode);const[minSpace,maxSpace]=this._getSpaceAroundNode(parentNode);const diff=position-newPosition;if(diff<0&&Math.abs(diff)<maxSpace-this.options.hierarchical.nodeSpacing||diff>0&&Math.abs(diff)<minSpace-this.options.hierarchical.nodeSpacing){this.direction.setPosition(parentNode,newPosition);}}}}}/**
* This function places the nodes on the canvas based on the hierarchial distribution.
*
* @param {object} distribution | obtained by the function this._getDistribution()
* @private
*/_placeNodesByHierarchy(distribution){this.positionedNodes={};// start placing all the level 0 nodes first. Then recursively position their branches.
for(const level in distribution){if(Object.prototype.hasOwnProperty.call(distribution,level)){// sort nodes in level by position:
let nodeArray=Object.keys(distribution[level]);nodeArray=this._indexArrayToNodes(nodeArray);this.direction.sort(nodeArray);let handledNodeCount=0;for(let i=0;i<nodeArray.length;i++){const node=nodeArray[i];if(this.positionedNodes[node.id]===undefined){const spacing=this.options.hierarchical.nodeSpacing;let pos=spacing*handledNodeCount;// We get the X or Y values we need and store them in pos and previousPos.
// The get and set make sure we get X or Y
if(handledNodeCount>0){pos=this.direction.getPosition(nodeArray[i-1])+spacing;}this.direction.setPosition(node,pos,level);this._validatePositionAndContinue(node,level,pos);handledNodeCount++;}}}}}/**
* This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
* on a X position that ensures there will be no overlap.
*
* @param {Node.id} parentId
* @param {number} parentLevel
* @private
*/_placeBranchNodes(parentId,parentLevel){const childRef=this.hierarchical.childrenReference[parentId];// if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
if(childRef===undefined){return;}// get a list of childNodes
const childNodes=[];for(let i=0;i<childRef.length;i++){childNodes.push(this.body.nodes[childRef[i]]);}// use the positions to order the nodes.
this.direction.sort(childNodes);// position the childNodes
for(let i=0;i<childNodes.length;i++){const childNode=childNodes[i];const childNodeLevel=this.hierarchical.levels[childNode.id];// check if the child node is below the parent node and if it has already been positioned.
if(childNodeLevel>parentLevel&&this.positionedNodes[childNode.id]===undefined){// get the amount of space required for this node. If parent the width is based on the amount of children.
const spacing=this.options.hierarchical.nodeSpacing;let pos;// we get the X or Y values we need and store them in pos and previousPos.
// The get and set make sure we get X or Y
if(i===0){pos=this.direction.getPosition(this.body.nodes[parentId]);}else {pos=this.direction.getPosition(childNodes[i-1])+spacing;}this.direction.setPosition(childNode,pos,childNodeLevel);this._validatePositionAndContinue(childNode,childNodeLevel,pos);}else {return;}}// center the parent nodes.
const center=this._getCenterPosition(childNodes);this.direction.setPosition(this.body.nodes[parentId],center,parentLevel);}/**
* This method checks for overlap and if required shifts the branch. It also keeps records of positioned nodes.
* Finally it will call _placeBranchNodes to place the branch nodes.
*
* @param {Node} node
* @param {number} level
* @param {number} pos
* @private
*/_validatePositionAndContinue(node,level,pos){// This method only works for formal trees and formal forests
// Early exit if this is not the case
if(!this.hierarchical.isTree)return;// if overlap has been detected, we shift the branch
if(this.lastNodeOnLevel[level]!==undefined){const previousPos=this.direction.getPosition(this.body.nodes[this.lastNodeOnLevel[level]]);if(pos-previousPos<this.options.hierarchical.nodeSpacing){const diff=previousPos+this.options.hierarchical.nodeSpacing-pos;const sharedParent=this._findCommonParent(this.lastNodeOnLevel[level],node.id);this._shiftBlock(sharedParent.withChild,diff);}}this.lastNodeOnLevel[level]=node.id;// store change in position.
this.positionedNodes[node.id]=true;this._placeBranchNodes(node.id,level);}/**
* Receives an array with node indices and returns an array with the actual node references.
* Used for sorting based on node properties.
*
* @param {Array.<Node.id>} idArray
* @returns {Array.<Node>}
*/_indexArrayToNodes(idArray){const array=[];for(let i=0;i<idArray.length;i++){array.push(this.body.nodes[idArray[i]]);}return array;}/**
* This function get the distribution of levels based on hubsize
*
* @returns {object}
* @private
*/_getDistribution(){const distribution={};let nodeId,node;// we fix Y because the hierarchy is vertical,
// we fix X so we do not give a node an x position for a second time.
// the fix of X is removed after the x value has been set.
for(nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){node=this.body.nodes[nodeId];const level=this.hierarchical.levels[nodeId]===undefined?0:this.hierarchical.levels[nodeId];this.direction.fix(node,level);if(distribution[level]===undefined){distribution[level]={};}distribution[level][nodeId]=node;}}return distribution;}/**
* Return the active (i.e. visible) edges for this node
*
* @param {Node} node
* @returns {Array.<vis.Edge>} Array of edge instances
* @private
*/_getActiveEdges(node){const result=[];forEach(node.edges,edge=>{if(this.body.edgeIndices.indexOf(edge.id)!==-1){result.push(edge);}});return result;}/**
* Get the hubsizes for all active nodes.
*
* @returns {number}
* @private
*/_getHubSizes(){const hubSizes={};const nodeIds=this.body.nodeIndices;forEach(nodeIds,nodeId=>{const node=this.body.nodes[nodeId];const hubSize=this._getActiveEdges(node).length;hubSizes[hubSize]=true;});// Make an array of the size sorted descending
const result=[];forEach(hubSizes,size=>{result.push(Number(size));});result.sort(function(a,b){return b-a;});return result;}/**
* this function allocates nodes in levels based on the recursive branching from the largest hubs.
*
* @private
*/_determineLevelsByHubsize(){const levelDownstream=(nodeA,nodeB)=>{this.hierarchical.levelDownstream(nodeA,nodeB);};const hubSizes=this._getHubSizes();for(let i=0;i<hubSizes.length;++i){const hubSize=hubSizes[i];if(hubSize===0)break;forEach(this.body.nodeIndices,nodeId=>{const node=this.body.nodes[nodeId];if(hubSize===this._getActiveEdges(node).length){this._crawlNetwork(levelDownstream,nodeId);}});}}/**
* TODO: release feature
* TODO: Determine if this feature is needed at all
*
* @private
*/_determineLevelsCustomCallback(){const minLevel=100000;// TODO: this should come from options.
// eslint-disable-next-line no-unused-vars -- This should eventually be implemented with these parameters used.
const customCallback=function(nodeA,nodeB,edge){};// TODO: perhaps move to HierarchicalStatus.
// But I currently don't see the point, this method is not used.
const levelByDirection=(nodeA,nodeB,edge)=>{let levelA=this.hierarchical.levels[nodeA.id];// set initial level
if(levelA===undefined){levelA=this.hierarchical.levels[nodeA.id]=minLevel;}const diff=customCallback(NetworkUtil.cloneOptions(nodeA,"node"),NetworkUtil.cloneOptions(nodeB,"node"),NetworkUtil.cloneOptions(edge,"edge"));this.hierarchical.levels[nodeB.id]=levelA+diff;};this._crawlNetwork(levelByDirection);this.hierarchical.setMinLevelToZero(this.body.nodes);}/**
* Allocate nodes in levels based on the direction of the edges.
*
* @private
*/_determineLevelsDirected(){const nodes=this.body.nodeIndices.reduce((acc,id)=>{acc.set(id,this.body.nodes[id]);return acc;},new Map());if(this.options.hierarchical.shakeTowards==="roots"){this.hierarchical.levels=fillLevelsByDirectionRoots(nodes);}else {this.hierarchical.levels=fillLevelsByDirectionLeaves(nodes);}this.hierarchical.setMinLevelToZero(this.body.nodes);}/**
* Update the bookkeeping of parent and child.
*
* @private
*/_generateMap(){const fillInRelations=(parentNode,childNode)=>{if(this.hierarchical.levels[childNode.id]>this.hierarchical.levels[parentNode.id]){this.hierarchical.addRelation(parentNode.id,childNode.id);}};this._crawlNetwork(fillInRelations);this.hierarchical.checkIfTree();}/**
* Crawl over the entire network and use a callback on each node couple that is connected to each other.
*
* @param {Function} [callback=function(){}] | will receive nodeA, nodeB and the connecting edge. A and B are distinct.
* @param {Node.id} startingNodeId
* @private
*/_crawlNetwork(callback=function(){},startingNodeId){const progress={};const crawler=(node,tree)=>{if(progress[node.id]===undefined){this.hierarchical.setTreeIndex(node,tree);progress[node.id]=true;let childNode;const edges=this._getActiveEdges(node);for(let i=0;i<edges.length;i++){const edge=edges[i];if(edge.connected===true){if(edge.toId==node.id){// Not '===' because id's can be string and numeric
childNode=edge.from;}else {childNode=edge.to;}if(node.id!=childNode.id){// Not '!==' because id's can be string and numeric
callback(node,childNode,edge);crawler(childNode,tree);}}}}};if(startingNodeId===undefined){// Crawl over all nodes
let treeIndex=0;// Serves to pass a unique id for the current distinct tree
for(let i=0;i<this.body.nodeIndices.length;i++){const nodeId=this.body.nodeIndices[i];if(progress[nodeId]===undefined){const node=this.body.nodes[nodeId];crawler(node,treeIndex);treeIndex+=1;}}}else {// Crawl from the given starting node
const node=this.body.nodes[startingNodeId];if(node===undefined){console.error("Node not found:",startingNodeId);return;}crawler(node);}}/**
* Shift a branch a certain distance
*
* @param {Node.id} parentId
* @param {number} diff
* @private
*/_shiftBlock(parentId,diff){const progress={};const shifter=parentId=>{if(progress[parentId]){return;}progress[parentId]=true;this.direction.shift(parentId,diff);const childRef=this.hierarchical.childrenReference[parentId];if(childRef!==undefined){for(let i=0;i<childRef.length;i++){shifter(childRef[i]);}}};shifter(parentId);}/**
* Find a common parent between branches.
*
* @param {Node.id} childA
* @param {Node.id} childB
* @returns {{foundParent, withChild}}
* @private
*/_findCommonParent(childA,childB){const parents={};const iterateParents=(parents,child)=>{const parentRef=this.hierarchical.parentReference[child];if(parentRef!==undefined){for(let i=0;i<parentRef.length;i++){const parent=parentRef[i];parents[parent]=true;iterateParents(parents,parent);}}};const findParent=(parents,child)=>{const parentRef=this.hierarchical.parentReference[child];if(parentRef!==undefined){for(let i=0;i<parentRef.length;i++){const parent=parentRef[i];if(parents[parent]!==undefined){return {foundParent:parent,withChild:child};}const branch=findParent(parents,parent);if(branch.foundParent!==null){return branch;}}}return {foundParent:null,withChild:child};};iterateParents(parents,childA);return findParent(parents,childB);}/**
* Set the strategy pattern for handling the coordinates given the current direction.
*
* The individual instances contain all the operations and data specific to a layout direction.
*
* @param {Node} node
* @param {{x: number, y: number}} position
* @param {number} level
* @param {boolean} [doNotUpdate=false]
* @private
*/setDirectionStrategy(){const isVertical=this.options.hierarchical.direction==="UD"||this.options.hierarchical.direction==="DU";if(isVertical){this.direction=new VerticalStrategy(this);}else {this.direction=new HorizontalStrategy(this);}}/**
* Determine the center position of a branch from the passed list of child nodes
*
* This takes into account the positions of all the child nodes.
*
* @param {Array.<Node|vis.Node.id>} childNodes Array of either child nodes or node id's
* @returns {number}
* @private
*/_getCenterPosition(childNodes){let minPos=1e9;let maxPos=-1e9;for(let i=0;i<childNodes.length;i++){let childNode;if(childNodes[i].id!==undefined){childNode=childNodes[i];}else {const childNodeId=childNodes[i];childNode=this.body.nodes[childNodeId];}const position=this.direction.getPosition(childNode);minPos=Math.min(minPos,position);maxPos=Math.max(maxPos,position);}return 0.5*(minPos+maxPos);}}/**
* Clears the toolbar div element of children
*
* @private
*/class ManipulationSystem{/**
* @param {object} body
* @param {Canvas} canvas
* @param {SelectionHandler} selectionHandler
* @param {InteractionHandler} interactionHandler
*/constructor(body,canvas,selectionHandler,interactionHandler){this.body=body;this.canvas=canvas;this.selectionHandler=selectionHandler;this.interactionHandler=interactionHandler;this.editMode=false;this.manipulationDiv=undefined;this.editModeDiv=undefined;this.closeDiv=undefined;this._domEventListenerCleanupQueue=[];this.temporaryUIFunctions={};this.temporaryEventFunctions=[];this.touchTime=0;this.temporaryIds={nodes:[],edges:[]};this.guiEnabled=false;this.inMode=false;this.selectedControlNode=undefined;this.options={};this.defaultOptions={enabled:false,initiallyActive:false,addNode:true,addEdge:true,editNode:undefined,editEdge:true,deleteNode:true,deleteEdge:true,controlNodeStyle:{shape:"dot",size:6,color:{background:"#ff0000",border:"#3c3c3c",highlight:{background:"#07f968",border:"#3c3c3c"}},borderWidth:2,borderWidthSelected:2}};Object.assign(this.options,this.defaultOptions);this.body.emitter.on("destroy",()=>{this._clean();});this.body.emitter.on("_dataChanged",this._restore.bind(this));this.body.emitter.on("_resetData",this._restore.bind(this));}/**
* If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes.
*
* @private
*/_restore(){if(this.inMode!==false){if(this.options.initiallyActive===true){this.enableEditMode();}else {this.disableEditMode();}}}/**
* Set the Options
*
* @param {object} options
* @param {object} allOptions
* @param {object} globalOptions
*/setOptions(options,allOptions,globalOptions){if(allOptions!==undefined){if(allOptions.locale!==undefined){this.options.locale=allOptions.locale;}else {this.options.locale=globalOptions.locale;}if(allOptions.locales!==undefined){this.options.locales=allOptions.locales;}else {this.options.locales=globalOptions.locales;}}if(options!==undefined){if(typeof options==="boolean"){this.options.enabled=options;}else {this.options.enabled=true;deepExtend(this.options,options);}if(this.options.initiallyActive===true){this.editMode=true;}this._setup();}}/**
* Enable or disable edit-mode. Draws the DOM required and cleans up after itself.
*
* @private
*/toggleEditMode(){if(this.editMode===true){this.disableEditMode();}else {this.enableEditMode();}}/**
* Enables Edit Mode
*/enableEditMode(){this.editMode=true;this._clean();if(this.guiEnabled===true){this.manipulationDiv.style.display="block";this.closeDiv.style.display="block";this.editModeDiv.style.display="none";this.showManipulatorToolbar();}}/**
* Disables Edit Mode
*/disableEditMode(){this.editMode=false;this._clean();if(this.guiEnabled===true){this.manipulationDiv.style.display="none";this.closeDiv.style.display="none";this.editModeDiv.style.display="block";this._createEditButton();}}/**
* Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
*
* @private
*/showManipulatorToolbar(){// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();// reset global variables
this.manipulationDOM={};// if the gui is enabled, draw all elements.
if(this.guiEnabled===true){// a _restore will hide these menus
this.editMode=true;this.manipulationDiv.style.display="block";this.closeDiv.style.display="block";const selectedNodeCount=this.selectionHandler.getSelectedNodeCount();const selectedEdgeCount=this.selectionHandler.getSelectedEdgeCount();const selectedTotalCount=selectedNodeCount+selectedEdgeCount;const locale=this.options.locales[this.options.locale];let needSeperator=false;if(this.options.addNode!==false){this._createAddNodeButton(locale);needSeperator=true;}if(this.options.addEdge!==false){if(needSeperator===true){this._createSeperator(1);}else {needSeperator=true;}this._createAddEdgeButton(locale);}if(selectedNodeCount===1&&typeof this.options.editNode==="function"){if(needSeperator===true){this._createSeperator(2);}else {needSeperator=true;}this._createEditNodeButton(locale);}else if(selectedEdgeCount===1&&selectedNodeCount===0&&this.options.editEdge!==false){if(needSeperator===true){this._createSeperator(3);}else {needSeperator=true;}this._createEditEdgeButton(locale);}// remove buttons
if(selectedTotalCount!==0){if(selectedNodeCount>0&&this.options.deleteNode!==false){if(needSeperator===true){this._createSeperator(4);}this._createDeleteButton(locale);}else if(selectedNodeCount===0&&this.options.deleteEdge!==false){if(needSeperator===true){this._createSeperator(4);}this._createDeleteButton(locale);}}// bind the close button
this._bindElementEvents(this.closeDiv,this.toggleEditMode.bind(this));// refresh this bar based on what has been selected
this._temporaryBindEvent("select",this.showManipulatorToolbar.bind(this));}// redraw to show any possible changes
this.body.emitter.emit("_redraw");}/**
* Create the toolbar for adding Nodes
*/addNodeMode(){// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="addNode";if(this.guiEnabled===true){const locale=this.options.locales[this.options.locale];this.manipulationDOM={};this._createBackButton(locale);this._createSeperator();this._createDescription(locale["addDescription"]||this.options.locales["en"]["addDescription"]);// bind the close button
this._bindElementEvents(this.closeDiv,this.toggleEditMode.bind(this));}this._temporaryBindEvent("click",this._performAddNode.bind(this));}/**
* call the bound function to handle the editing of the node. The node has to be selected.
*/editNode(){// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();const node=this.selectionHandler.getSelectedNodes()[0];if(node!==undefined){this.inMode="editNode";if(typeof this.options.editNode==="function"){if(node.isCluster!==true){const data=deepExtend({},node.options,false);data.x=node.x;data.y=node.y;if(this.options.editNode.length===2){this.options.editNode(data,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="editNode"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.data.nodes.getDataSet().update(finalizedData);}this.showManipulatorToolbar();});}else {throw new Error("The function for edit does not support two arguments (data, callback)");}}else {alert(this.options.locales[this.options.locale]["editClusterError"]||this.options.locales["en"]["editClusterError"]);}}else {throw new Error("No function has been configured to handle the editing of nodes.");}}else {this.showManipulatorToolbar();}}/**
* create the toolbar to connect nodes
*/addEdgeMode(){// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="addEdge";if(this.guiEnabled===true){const locale=this.options.locales[this.options.locale];this.manipulationDOM={};this._createBackButton(locale);this._createSeperator();this._createDescription(locale["edgeDescription"]||this.options.locales["en"]["edgeDescription"]);// bind the close button
this._bindElementEvents(this.closeDiv,this.toggleEditMode.bind(this));}// temporarily overload functions
this._temporaryBindUI("onTouch",this._handleConnect.bind(this));this._temporaryBindUI("onDragEnd",this._finishConnect.bind(this));this._temporaryBindUI("onDrag",this._dragControlNode.bind(this));this._temporaryBindUI("onRelease",this._finishConnect.bind(this));this._temporaryBindUI("onDragStart",this._dragStartEdge.bind(this));this._temporaryBindUI("onHold",()=>{});}/**
* create the toolbar to edit edges
*/editEdgeMode(){// when using the gui, enable edit mode if it wasn't already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="editEdge";if(typeof this.options.editEdge==="object"&&typeof this.options.editEdge.editWithoutDrag==="function"){this.edgeBeingEditedId=this.selectionHandler.getSelectedEdgeIds()[0];if(this.edgeBeingEditedId!==undefined){const edge=this.body.edges[this.edgeBeingEditedId];this._performEditEdge(edge.from.id,edge.to.id);return;}}if(this.guiEnabled===true){const locale=this.options.locales[this.options.locale];this.manipulationDOM={};this._createBackButton(locale);this._createSeperator();this._createDescription(locale["editEdgeDescription"]||this.options.locales["en"]["editEdgeDescription"]);// bind the close button
this._bindElementEvents(this.closeDiv,this.toggleEditMode.bind(this));}this.edgeBeingEditedId=this.selectionHandler.getSelectedEdgeIds()[0];if(this.edgeBeingEditedId!==undefined){const edge=this.body.edges[this.edgeBeingEditedId];// create control nodes
const controlNodeFrom=this._getNewTargetNode(edge.from.x,edge.from.y);const controlNodeTo=this._getNewTargetNode(edge.to.x,edge.to.y);this.temporaryIds.nodes.push(controlNodeFrom.id);this.temporaryIds.nodes.push(controlNodeTo.id);this.body.nodes[controlNodeFrom.id]=controlNodeFrom;this.body.nodeIndices.push(controlNodeFrom.id);this.body.nodes[controlNodeTo.id]=controlNodeTo;this.body.nodeIndices.push(controlNodeTo.id);// temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI
this._temporaryBindUI("onTouch",this._controlNodeTouch.bind(this));// used to get the position
this._temporaryBindUI("onTap",()=>{});// disabled
this._temporaryBindUI("onHold",()=>{});// disabled
this._temporaryBindUI("onDragStart",this._controlNodeDragStart.bind(this));// used to select control node
this._temporaryBindUI("onDrag",this._controlNodeDrag.bind(this));// used to drag control node
this._temporaryBindUI("onDragEnd",this._controlNodeDragEnd.bind(this));// used to connect or revert control nodes
this._temporaryBindUI("onMouseMove",()=>{});// disabled
// create function to position control nodes correctly on movement
// automatically cleaned up because we use the temporary bind
this._temporaryBindEvent("beforeDrawing",ctx=>{const positions=edge.edgeType.findBorderPositions(ctx);if(controlNodeFrom.selected===false){controlNodeFrom.x=positions.from.x;controlNodeFrom.y=positions.from.y;}if(controlNodeTo.selected===false){controlNodeTo.x=positions.to.x;controlNodeTo.y=positions.to.y;}});this.body.emitter.emit("_redraw");}else {this.showManipulatorToolbar();}}/**
* delete everything in the selection
*/deleteSelected(){// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="delete";const selectedNodes=this.selectionHandler.getSelectedNodeIds();const selectedEdges=this.selectionHandler.getSelectedEdgeIds();let deleteFunction=undefined;if(selectedNodes.length>0){for(let i=0;i<selectedNodes.length;i++){if(this.body.nodes[selectedNodes[i]].isCluster===true){alert(this.options.locales[this.options.locale]["deleteClusterError"]||this.options.locales["en"]["deleteClusterError"]);return;}}if(typeof this.options.deleteNode==="function"){deleteFunction=this.options.deleteNode;}}else if(selectedEdges.length>0){if(typeof this.options.deleteEdge==="function"){deleteFunction=this.options.deleteEdge;}}if(typeof deleteFunction==="function"){const data={nodes:selectedNodes,edges:selectedEdges};if(deleteFunction.length===2){deleteFunction(data,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="delete"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.data.edges.getDataSet().remove(finalizedData.edges);this.body.data.nodes.getDataSet().remove(finalizedData.nodes);this.body.emitter.emit("startSimulation");this.showManipulatorToolbar();}else {this.body.emitter.emit("startSimulation");this.showManipulatorToolbar();}});}else {throw new Error("The function for delete does not support two arguments (data, callback)");}}else {this.body.data.edges.getDataSet().remove(selectedEdges);this.body.data.nodes.getDataSet().remove(selectedNodes);this.body.emitter.emit("startSimulation");this.showManipulatorToolbar();}}//********************************************** PRIVATE ***************************************//
/**
* draw or remove the DOM
*
* @private
*/_setup(){if(this.options.enabled===true){// Enable the GUI
this.guiEnabled=true;this._createWrappers();if(this.editMode===false){this._createEditButton();}else {this.showManipulatorToolbar();}}else {this._removeManipulationDOM();// disable the gui
this.guiEnabled=false;}}/**
* create the div overlays that contain the DOM
*
* @private
*/_createWrappers(){// load the manipulator HTML elements. All styling done in css.
if(this.manipulationDiv===undefined){this.manipulationDiv=document.createElement("div");this.manipulationDiv.className="vis-manipulation";if(this.editMode===true){this.manipulationDiv.style.display="block";}else {this.manipulationDiv.style.display="none";}this.canvas.frame.appendChild(this.manipulationDiv);}// container for the edit button.
if(this.editModeDiv===undefined){this.editModeDiv=document.createElement("div");this.editModeDiv.className="vis-edit-mode";if(this.editMode===true){this.editModeDiv.style.display="none";}else {this.editModeDiv.style.display="block";}this.canvas.frame.appendChild(this.editModeDiv);}// container for the close div button
if(this.closeDiv===undefined){var _this$options$locales,_this$options$locales2;this.closeDiv=document.createElement("button");this.closeDiv.className="vis-close";this.closeDiv.setAttribute("aria-label",(_this$options$locales=(_this$options$locales2=this.options.locales[this.options.locale])===null||_this$options$locales2===void 0?void 0:_this$options$locales2["close"])!==null&&_this$options$locales!==void 0?_this$options$locales:this.options.locales["en"]["close"]);this.closeDiv.style.display=this.manipulationDiv.style.display;this.canvas.frame.appendChild(this.closeDiv);}}/**
* generate a new target node. Used for creating new edges and editing edges
*
* @param {number} x
* @param {number} y
* @returns {Node}
* @private
*/_getNewTargetNode(x,y){const controlNodeStyle=deepExtend({},this.options.controlNodeStyle);controlNodeStyle.id="targetNode"+v4();controlNodeStyle.hidden=false;controlNodeStyle.physics=false;controlNodeStyle.x=x;controlNodeStyle.y=y;// we have to define the bounding box in order for the nodes to be drawn immediately
const node=this.body.functions.createNode(controlNodeStyle);node.shape.boundingBox={left:x,right:x,top:y,bottom:y};return node;}/**
* Create the edit button
*/_createEditButton(){// restore everything to it's original state (if applicable)
this._clean();// reset the manipulationDOM
this.manipulationDOM={};// empty the editModeDiv
recursiveDOMDelete(this.editModeDiv);// create the contents for the editMode button
const locale=this.options.locales[this.options.locale];const button=this._createButton("editMode","vis-edit vis-edit-mode",locale["edit"]||this.options.locales["en"]["edit"]);this.editModeDiv.appendChild(button);// bind a hammer listener to the button, calling the function toggleEditMode.
this._bindElementEvents(button,this.toggleEditMode.bind(this));}/**
* this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed.
*
* @private
*/_clean(){// not in mode
this.inMode=false;// _clean the divs
if(this.guiEnabled===true){recursiveDOMDelete(this.editModeDiv);recursiveDOMDelete(this.manipulationDiv);// removes all the bindings and overloads
this._cleanupDOMEventListeners();}// remove temporary nodes and edges
this._cleanupTemporaryNodesAndEdges();// restore overloaded UI functions
this._unbindTemporaryUIs();// remove the temporaryEventFunctions
this._unbindTemporaryEvents();// restore the physics if required
this.body.emitter.emit("restorePhysics");}/**
* Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up.
*
* @private
*/_cleanupDOMEventListeners(){// _clean DOM event listener bindings
for(const callback of this._domEventListenerCleanupQueue.splice(0)){callback();}}/**
* Remove all DOM elements created by this module.
*
* @private
*/_removeManipulationDOM(){// removes all the bindings and overloads
this._clean();// empty the manipulation divs
recursiveDOMDelete(this.manipulationDiv);recursiveDOMDelete(this.editModeDiv);recursiveDOMDelete(this.closeDiv);// remove the manipulation divs
if(this.manipulationDiv){this.canvas.frame.removeChild(this.manipulationDiv);}if(this.editModeDiv){this.canvas.frame.removeChild(this.editModeDiv);}if(this.closeDiv){this.canvas.frame.removeChild(this.closeDiv);}// set the references to undefined
this.manipulationDiv=undefined;this.editModeDiv=undefined;this.closeDiv=undefined;}/**
* create a seperator line. the index is to differentiate in the manipulation dom
*
* @param {number} [index=1]
* @private
*/_createSeperator(index=1){this.manipulationDOM["seperatorLineDiv"+index]=document.createElement("div");this.manipulationDOM["seperatorLineDiv"+index].className="vis-separator-line";this.manipulationDiv.appendChild(this.manipulationDOM["seperatorLineDiv"+index]);}// ---------------------- DOM functions for buttons --------------------------//
/**
*
* @param {Locale} locale
* @private
*/_createAddNodeButton(locale){const button=this._createButton("addNode","vis-add",locale["addNode"]||this.options.locales["en"]["addNode"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,this.addNodeMode.bind(this));}/**
*
* @param {Locale} locale
* @private
*/_createAddEdgeButton(locale){const button=this._createButton("addEdge","vis-connect",locale["addEdge"]||this.options.locales["en"]["addEdge"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,this.addEdgeMode.bind(this));}/**
*
* @param {Locale} locale
* @private
*/_createEditNodeButton(locale){const button=this._createButton("editNode","vis-edit",locale["editNode"]||this.options.locales["en"]["editNode"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,this.editNode.bind(this));}/**
*
* @param {Locale} locale
* @private
*/_createEditEdgeButton(locale){const button=this._createButton("editEdge","vis-edit",locale["editEdge"]||this.options.locales["en"]["editEdge"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,this.editEdgeMode.bind(this));}/**
*
* @param {Locale} locale
* @private
*/_createDeleteButton(locale){let deleteBtnClass;if(this.options.rtl){deleteBtnClass="vis-delete-rtl";}else {deleteBtnClass="vis-delete";}const button=this._createButton("delete",deleteBtnClass,locale["del"]||this.options.locales["en"]["del"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,this.deleteSelected.bind(this));}/**
*
* @param {Locale} locale
* @private
*/_createBackButton(locale){const button=this._createButton("back","vis-back",locale["back"]||this.options.locales["en"]["back"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,this.showManipulatorToolbar.bind(this));}/**
*
* @param {number|string} id
* @param {string} className
* @param {label} label
* @param {string} labelClassName
* @returns {HTMLElement}
* @private
*/_createButton(id,className,label,labelClassName="vis-label"){this.manipulationDOM[id+"Div"]=document.createElement("button");this.manipulationDOM[id+"Div"].className="vis-button "+className;this.manipulationDOM[id+"Label"]=document.createElement("div");this.manipulationDOM[id+"Label"].className=labelClassName;this.manipulationDOM[id+"Label"].innerText=label;this.manipulationDOM[id+"Div"].appendChild(this.manipulationDOM[id+"Label"]);return this.manipulationDOM[id+"Div"];}/**
*
* @param {Label} label
* @private
*/_createDescription(label){this.manipulationDOM["descriptionLabel"]=document.createElement("div");this.manipulationDOM["descriptionLabel"].className="vis-none";this.manipulationDOM["descriptionLabel"].innerText=label;this.manipulationDiv.appendChild(this.manipulationDOM["descriptionLabel"]);}// -------------------------- End of DOM functions for buttons ------------------------------//
/**
* this binds an event until cleanup by the clean functions.
*
* @param {Event} event The event
* @param {Function} newFunction
* @private
*/_temporaryBindEvent(event,newFunction){this.temporaryEventFunctions.push({event:event,boundFunction:newFunction});this.body.emitter.on(event,newFunction);}/**
* this overrides an UI function until cleanup by the clean function
*
* @param {string} UIfunctionName
* @param {Function} newFunction
* @private
*/_temporaryBindUI(UIfunctionName,newFunction){if(this.body.eventListeners[UIfunctionName]!==undefined){this.temporaryUIFunctions[UIfunctionName]=this.body.eventListeners[UIfunctionName];this.body.eventListeners[UIfunctionName]=newFunction;}else {throw new Error("This UI function does not exist. Typo? You tried: "+UIfunctionName+" possible are: "+JSON.stringify(Object.keys(this.body.eventListeners)));}}/**
* Restore the overridden UI functions to their original state.
*
* @private
*/_unbindTemporaryUIs(){for(const functionName in this.temporaryUIFunctions){if(Object.prototype.hasOwnProperty.call(this.temporaryUIFunctions,functionName)){this.body.eventListeners[functionName]=this.temporaryUIFunctions[functionName];delete this.temporaryUIFunctions[functionName];}}this.temporaryUIFunctions={};}/**
* Unbind the events created by _temporaryBindEvent
*
* @private
*/_unbindTemporaryEvents(){for(let i=0;i<this.temporaryEventFunctions.length;i++){const eventName=this.temporaryEventFunctions[i].event;const boundFunction=this.temporaryEventFunctions[i].boundFunction;this.body.emitter.off(eventName,boundFunction);}this.temporaryEventFunctions=[];}/**
* Bind an hammer instance to a DOM element.
*
* @param {Element} domElement
* @param {Function} boundFunction
*/_bindElementEvents(domElement,boundFunction){// Bind touch events.
const hammer=new Hammer$2(domElement,{});onTouch(hammer,boundFunction);this._domEventListenerCleanupQueue.push(()=>{hammer.destroy();});// Bind keyboard events.
const keyupListener=({keyCode,key})=>{if(key==="Enter"||key===" "||keyCode===13||keyCode===32){boundFunction();}};domElement.addEventListener("keyup",keyupListener,false);this._domEventListenerCleanupQueue.push(()=>{domElement.removeEventListener("keyup",keyupListener,false);});}/**
* Neatly clean up temporary edges and nodes
*
* @private
*/_cleanupTemporaryNodesAndEdges(){// _clean temporary edges
for(let i=0;i<this.temporaryIds.edges.length;i++){this.body.edges[this.temporaryIds.edges[i]].disconnect();delete this.body.edges[this.temporaryIds.edges[i]];const indexTempEdge=this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]);if(indexTempEdge!==-1){this.body.edgeIndices.splice(indexTempEdge,1);}}// _clean temporary nodes
for(let i=0;i<this.temporaryIds.nodes.length;i++){delete this.body.nodes[this.temporaryIds.nodes[i]];const indexTempNode=this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]);if(indexTempNode!==-1){this.body.nodeIndices.splice(indexTempNode,1);}}this.temporaryIds={nodes:[],edges:[]};}// ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------//
/**
* the touch is used to get the position of the initial click
*
* @param {Event} event The event
* @private
*/_controlNodeTouch(event){this.selectionHandler.unselectAll();this.lastTouch=this.body.functions.getPointer(event.center);this.lastTouch.translation=Object.assign({},this.body.view.translation);// copy the object
}/**
* the drag start is used to mark one of the control nodes as selected.
*
* @private
*/_controlNodeDragStart(){const pointer=this.lastTouch;const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);const from=this.body.nodes[this.temporaryIds.nodes[0]];const to=this.body.nodes[this.temporaryIds.nodes[1]];const edge=this.body.edges[this.edgeBeingEditedId];this.selectedControlNode=undefined;const fromSelect=from.isOverlappingWith(pointerObj);const toSelect=to.isOverlappingWith(pointerObj);if(fromSelect===true){this.selectedControlNode=from;edge.edgeType.from=from;}else if(toSelect===true){this.selectedControlNode=to;edge.edgeType.to=to;}// we use the selection to find the node that is being dragged. We explicitly select it here.
if(this.selectedControlNode!==undefined){this.selectionHandler.selectObject(this.selectedControlNode);}this.body.emitter.emit("_redraw");}/**
* dragging the control nodes or the canvas
*
* @param {Event} event The event
* @private
*/_controlNodeDrag(event){this.body.emitter.emit("disablePhysics");const pointer=this.body.functions.getPointer(event.center);const pos=this.canvas.DOMtoCanvas(pointer);if(this.selectedControlNode!==undefined){this.selectedControlNode.x=pos.x;this.selectedControlNode.y=pos.y;}else {this.interactionHandler.onDrag(event);}this.body.emitter.emit("_redraw");}/**
* connecting or restoring the control nodes.
*
* @param {Event} event The event
* @private
*/_controlNodeDragEnd(event){const pointer=this.body.functions.getPointer(event.center);const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);const edge=this.body.edges[this.edgeBeingEditedId];// if the node that was dragged is not a control node, return
if(this.selectedControlNode===undefined){return;}// we use the selection to find the node that is being dragged. We explicitly DEselect the control node here.
this.selectionHandler.unselectAll();const overlappingNodeIds=this.selectionHandler._getAllNodesOverlappingWith(pointerObj);let node=undefined;for(let i=overlappingNodeIds.length-1;i>=0;i--){if(overlappingNodeIds[i]!==this.selectedControlNode.id){node=this.body.nodes[overlappingNodeIds[i]];break;}}// perform the connection
if(node!==undefined&&this.selectedControlNode!==undefined){if(node.isCluster===true){alert(this.options.locales[this.options.locale]["createEdgeError"]||this.options.locales["en"]["createEdgeError"]);}else {const from=this.body.nodes[this.temporaryIds.nodes[0]];if(this.selectedControlNode.id===from.id){this._performEditEdge(node.id,edge.to.id);}else {this._performEditEdge(edge.from.id,node.id);}}}else {edge.updateEdgeType();this.body.emitter.emit("restorePhysics");}this.body.emitter.emit("_redraw");}// ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------//
// ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------//
/**
* the function bound to the selection event. It checks if you want to connect a cluster and changes the description
* to walk the user through the process.
*
* @param {Event} event
* @private
*/_handleConnect(event){// check to avoid double fireing of this function.
if(new Date().valueOf()-this.touchTime>100){this.lastTouch=this.body.functions.getPointer(event.center);this.lastTouch.translation=Object.assign({},this.body.view.translation);// copy the object
this.interactionHandler.drag.pointer=this.lastTouch;// Drag pointer is not updated when adding edges
this.interactionHandler.drag.translation=this.lastTouch.translation;const pointer=this.lastTouch;const node=this.selectionHandler.getNodeAt(pointer);if(node!==undefined){if(node.isCluster===true){alert(this.options.locales[this.options.locale]["createEdgeError"]||this.options.locales["en"]["createEdgeError"]);}else {// create a node the temporary line can look at
const targetNode=this._getNewTargetNode(node.x,node.y);this.body.nodes[targetNode.id]=targetNode;this.body.nodeIndices.push(targetNode.id);// create a temporary edge
const connectionEdge=this.body.functions.createEdge({id:"connectionEdge"+v4(),from:node.id,to:targetNode.id,physics:false,smooth:{enabled:true,type:"continuous",roundness:0.5}});this.body.edges[connectionEdge.id]=connectionEdge;this.body.edgeIndices.push(connectionEdge.id);this.temporaryIds.nodes.push(targetNode.id);this.temporaryIds.edges.push(connectionEdge.id);}}this.touchTime=new Date().valueOf();}}/**
*
* @param {Event} event
* @private
*/_dragControlNode(event){const pointer=this.body.functions.getPointer(event.center);const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);// remember the edge id
let connectFromId=undefined;if(this.temporaryIds.edges[0]!==undefined){connectFromId=this.body.edges[this.temporaryIds.edges[0]].fromId;}// get the overlapping node but NOT the temporary node;
const overlappingNodeIds=this.selectionHandler._getAllNodesOverlappingWith(pointerObj);let node=undefined;for(let i=overlappingNodeIds.length-1;i>=0;i--){// if the node id is NOT a temporary node, accept the node.
if(this.temporaryIds.nodes.indexOf(overlappingNodeIds[i])===-1){node=this.body.nodes[overlappingNodeIds[i]];break;}}event.controlEdge={from:connectFromId,to:node?node.id:undefined};this.selectionHandler.generateClickEvent("controlNodeDragging",event,pointer);if(this.temporaryIds.nodes[0]!==undefined){const targetNode=this.body.nodes[this.temporaryIds.nodes[0]];// there is only one temp node in the add edge mode.
targetNode.x=this.canvas._XconvertDOMtoCanvas(pointer.x);targetNode.y=this.canvas._YconvertDOMtoCanvas(pointer.y);this.body.emitter.emit("_redraw");}else {this.interactionHandler.onDrag(event);}}/**
* Connect the new edge to the target if one exists, otherwise remove temp line
*
* @param {Event} event The event
* @private
*/_finishConnect(event){const pointer=this.body.functions.getPointer(event.center);const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);// remember the edge id
let connectFromId=undefined;if(this.temporaryIds.edges[0]!==undefined){connectFromId=this.body.edges[this.temporaryIds.edges[0]].fromId;}// get the overlapping node but NOT the temporary node;
const overlappingNodeIds=this.selectionHandler._getAllNodesOverlappingWith(pointerObj);let node=undefined;for(let i=overlappingNodeIds.length-1;i>=0;i--){// if the node id is NOT a temporary node, accept the node.
if(this.temporaryIds.nodes.indexOf(overlappingNodeIds[i])===-1){node=this.body.nodes[overlappingNodeIds[i]];break;}}// clean temporary nodes and edges.
this._cleanupTemporaryNodesAndEdges();// perform the connection
if(node!==undefined){if(node.isCluster===true){alert(this.options.locales[this.options.locale]["createEdgeError"]||this.options.locales["en"]["createEdgeError"]);}else {if(this.body.nodes[connectFromId]!==undefined&&this.body.nodes[node.id]!==undefined){this._performAddEdge(connectFromId,node.id);}}}event.controlEdge={from:connectFromId,to:node?node.id:undefined};this.selectionHandler.generateClickEvent("controlNodeDragEnd",event,pointer);// No need to do _generateclickevent('dragEnd') here, the regular dragEnd event fires.
this.body.emitter.emit("_redraw");}/**
*
* @param {Event} event
* @private
*/_dragStartEdge(event){const pointer=this.lastTouch;this.selectionHandler.generateClickEvent("dragStart",event,pointer,undefined,true);}// --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------//
// ------------------------------ Performing all the actual data manipulation ------------------------//
/**
* Adds a node on the specified location
*
* @param {object} clickData
* @private
*/_performAddNode(clickData){const defaultData={id:v4(),x:clickData.pointer.canvas.x,y:clickData.pointer.canvas.y,label:"new"};if(typeof this.options.addNode==="function"){if(this.options.addNode.length===2){this.options.addNode(defaultData,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="addNode"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback
this.body.data.nodes.getDataSet().add(finalizedData);}this.showManipulatorToolbar();});}else {this.showManipulatorToolbar();throw new Error("The function for add does not support two arguments (data,callback)");}}else {this.body.data.nodes.getDataSet().add(defaultData);this.showManipulatorToolbar();}}/**
* connect two nodes with a new edge.
*
* @param {Node.id} sourceNodeId
* @param {Node.id} targetNodeId
* @private
*/_performAddEdge(sourceNodeId,targetNodeId){const defaultData={from:sourceNodeId,to:targetNodeId};if(typeof this.options.addEdge==="function"){if(this.options.addEdge.length===2){this.options.addEdge(defaultData,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="addEdge"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback
this.body.data.edges.getDataSet().add(finalizedData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}});}else {throw new Error("The function for connect does not support two arguments (data,callback)");}}else {this.body.data.edges.getDataSet().add(defaultData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}}/**
* connect two nodes with a new edge.
*
* @param {Node.id} sourceNodeId
* @param {Node.id} targetNodeId
* @private
*/_performEditEdge(sourceNodeId,targetNodeId){const defaultData={id:this.edgeBeingEditedId,from:sourceNodeId,to:targetNodeId,label:this.body.data.edges.get(this.edgeBeingEditedId).label};let eeFunct=this.options.editEdge;if(typeof eeFunct==="object"){eeFunct=eeFunct.editWithoutDrag;}if(typeof eeFunct==="function"){if(eeFunct.length===2){eeFunct(defaultData,finalizedData=>{if(finalizedData===null||finalizedData===undefined||this.inMode!=="editEdge"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.edges[defaultData.id].updateEdgeType();this.body.emitter.emit("_redraw");this.showManipulatorToolbar();}else {this.body.data.edges.getDataSet().update(finalizedData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}});}else {throw new Error("The function for edit does not support two arguments (data, callback)");}}else {this.body.data.edges.getDataSet().update(defaultData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}}}/**
* This object contains all possible options. It will check if the types are correct, if required if the option is one
* of the allowed values.
*
* __any__ means that the name of the property does not matter.
* __type__ is a required field for all objects and contains the allowed types of all objects
*/const string="string";const bool="boolean";const number="number";const array="array";const object="object";// should only be in a __type__ property
const dom="dom";const any="any";// List of endpoints
const endPoints=["arrow","bar","box","circle","crow","curve","diamond","image","inv_curve","inv_triangle","triangle","vee"];/* eslint-disable @typescript-eslint/naming-convention -- The __*__ format is used to prevent collisions with actual option names. */const nodeOptions={borderWidth:{number},borderWidthSelected:{number,undefined:"undefined"},brokenImage:{string,undefined:"undefined"},chosen:{label:{boolean:bool,function:"function"},node:{boolean:bool,function:"function"},__type__:{object,boolean:bool}},color:{border:{string},background:{string},highlight:{border:{string},background:{string},__type__:{object,string}},hover:{border:{string},background:{string},__type__:{object,string}},__type__:{object,string}},opacity:{number,undefined:"undefined"},fixed:{x:{boolean:bool},y:{boolean:bool},__type__:{object,boolean:bool}},font:{align:{string},color:{string},size:{number},face:{string},background:{string},strokeWidth:{number},strokeColor:{string},vadjust:{number},multi:{boolean:bool,string},bold:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},boldital:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},ital:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},mono:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},__type__:{object,string}},group:{string,number,undefined:"undefined"},heightConstraint:{minimum:{number},valign:{string},__type__:{object,boolean:bool,number}},hidden:{boolean:bool},icon:{face:{string},code:{string},size:{number},color:{string},weight:{string,number},__type__:{object}},id:{string,number},image:{selected:{string,undefined:"undefined"},unselected:{string,undefined:"undefined"},__type__:{object,string}},imagePadding:{top:{number},right:{number},bottom:{number},left:{number},__type__:{object,number}},label:{string,undefined:"undefined"},labelHighlightBold:{boolean:bool},level:{number,undefined:"undefined"},margin:{top:{number},right:{number},bottom:{number},left:{number},__type__:{object,number}},mass:{number},physics:{boolean:bool},scaling:{min:{number},max:{number},label:{enabled:{boolean:bool},min:{number},max:{number},maxVisible:{number},drawThreshold:{number},__type__:{object,boolean:bool}},customScalingFunction:{function:"function"},__type__:{object}},shadow:{enabled:{boolean:bool},color:{string},size:{number},x:{number},y:{number},__type__:{object,boolean:bool}},shape:{string:["custom","ellipse","circle","database","box","text","image","circularImage","diamond","dot","star","triangle","triangleDown","square","icon","hexagon"]},ctxRenderer:{function:"function"},shapeProperties:{borderDashes:{boolean:bool,array},borderRadius:{number},interpolation:{boolean:bool},useImageSize:{boolean:bool},useBorderWithImage:{boolean:bool},coordinateOrigin:{string:["center","top-left"]},__type__:{object}},size:{number},title:{string,dom,undefined:"undefined"},value:{number,undefined:"undefined"},widthConstraint:{minimum:{number},maximum:{number},__type__:{object,boolean:bool,number}},x:{number},y:{number},__type__:{object}};const allOptions={configure:{enabled:{boolean:bool},filter:{boolean:bool,string,array,function:"function"},container:{dom},showButton:{boolean:bool},__type__:{object,boolean:bool,string,array,function:"function"}},edges:{arrows:{to:{enabled:{boolean:bool},scaleFactor:{number},type:{string:endPoints},imageHeight:{number},imageWidth:{number},src:{string},__type__:{object,boolean:bool}},middle:{enabled:{boolean:bool},scaleFactor:{number},type:{string:endPoints},imageWidth:{number},imageHeight:{number},src:{string},__type__:{object,boolean:bool}},from:{enabled:{boolean:bool},scaleFactor:{number},type:{string:endPoints},imageWidth:{number},imageHeight:{number},src:{string},__type__:{object,boolean:bool}},__type__:{string:["from","to","middle"],object}},endPointOffset:{from:{number:number},to:{number:number},__type__:{object:object,number:number}},arrowStrikethrough:{boolean:bool},background:{enabled:{boolean:bool},color:{string},size:{number},dashes:{boolean:bool,array},__type__:{object,boolean:bool}},chosen:{label:{boolean:bool,function:"function"},edge:{boolean:bool,function:"function"},__type__:{object,boolean:bool}},color:{color:{string},highlight:{string},hover:{string},inherit:{string:["from","to","both"],boolean:bool},opacity:{number},__type__:{object,string}},dashes:{boolean:bool,array},font:{color:{string},size:{number},face:{string},background:{string},strokeWidth:{number},strokeColor:{string},align:{string:["horizontal","top","middle","bottom"]},vadjust:{number},multi:{boolean:bool,string},bold:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},boldital:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},ital:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},mono:{color:{string},size:{number},face:{string},mod:{string},vadjust:{number},__type__:{object,string}},__type__:{object,string}},hidden:{boolean:bool},hoverWidth:{function:"function",number},label:{string,undefined:"undefined"},labelHighlightBold:{boolean:bool},length:{number,undefined:"undefined"},physics:{boolean:bool},scaling:{min:{number},max:{number},label:{enabled:{boolean:bool},min:{number},max:{number},maxVisible:{number},drawThreshold:{number},__type__:{object,boolean:bool}},customScalingFunction:{function:"function"},__type__:{object}},selectionWidth:{function:"function",number},selfReferenceSize:{number},selfReference:{size:{number},angle:{number},renderBehindTheNode:{boolean:bool},__type__:{object}},shadow:{enabled:{boolean:bool},color:{string},size:{number},x:{number},y:{number},__type__:{object,boolean:bool}},smooth:{enabled:{boolean:bool},type:{string:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW","cubicBezier"]},roundness:{number},forceDirection:{string:["horizontal","vertical","none"],boolean:bool},__type__:{object,boolean:bool}},title:{string,undefined:"undefined"},width:{number},widthConstraint:{maximum:{number},__type__:{object,boolean:bool,number}},value:{number,undefined:"undefined"},__type__:{object}},groups:{useDefaultGroups:{boolean:bool},__any__:nodeOptions,__type__:{object}},interaction:{dragNodes:{boolean:bool},dragView:{boolean:bool},hideEdgesOnDrag:{boolean:bool},hideEdgesOnZoom:{boolean:bool},hideNodesOnDrag:{boolean:bool},hover:{boolean:bool},keyboard:{enabled:{boolean:bool},speed:{x:{number},y:{number},zoom:{number},__type__:{object}},bindToWindow:{boolean:bool},autoFocus:{boolean:bool},__type__:{object,boolean:bool}},multiselect:{boolean:bool},navigationButtons:{boolean:bool},selectable:{boolean:bool},selectConnectedEdges:{boolean:bool},hoverConnectedEdges:{boolean:bool},tooltipDelay:{number},zoomView:{boolean:bool},zoomSpeed:{number},__type__:{object}},layout:{randomSeed:{undefined:"undefined",number,string},improvedLayout:{boolean:bool},clusterThreshold:{number},hierarchical:{enabled:{boolean:bool},levelSeparation:{number},nodeSpacing:{number},treeSpacing:{number},blockShifting:{boolean:bool},edgeMinimization:{boolean:bool},parentCentralization:{boolean:bool},direction:{string:["UD","DU","LR","RL"]},sortMethod:{string:["hubsize","directed"]},shakeTowards:{string:["leaves","roots"]},__type__:{object,boolean:bool}},__type__:{object}},manipulation:{enabled:{boolean:bool},initiallyActive:{boolean:bool},addNode:{boolean:bool,function:"function"},addEdge:{boolean:bool,function:"function"},editNode:{function:"function"},editEdge:{editWithoutDrag:{function:"function"},__type__:{object,boolean:bool,function:"function"}},deleteNode:{boolean:bool,function:"function"},deleteEdge:{boolean:bool,function:"function"},controlNodeStyle:nodeOptions,__type__:{object,boolean:bool}},nodes:nodeOptions,physics:{enabled:{boolean:bool},barnesHut:{theta:{number},gravitationalConstant:{number},centralGravity:{number},springLength:{number},springConstant:{number},damping:{number},avoidOverlap:{number},__type__:{object}},forceAtlas2Based:{theta:{number},gravitationalConstant:{number},centralGravity:{number},springLength:{number},springConstant:{number},damping:{number},avoidOverlap:{number},__type__:{object}},repulsion:{centralGravity:{number},springLength:{number},springConstant:{number},nodeDistance:{number},damping:{number},__type__:{object}},hierarchicalRepulsion:{centralGravity:{number},springLength:{number},springConstant:{number},nodeDistance:{number},damping:{number},avoidOverlap:{number},__type__:{object}},maxVelocity:{number},minVelocity:{number},solver:{string:["barnesHut","repulsion","hierarchicalRepulsion","forceAtlas2Based"]},stabilization:{enabled:{boolean:bool},iterations:{number},updateInterval:{number},onlyDynamicEdges:{boolean:bool},fit:{boolean:bool},__type__:{object,boolean:bool}},timestep:{number},adaptiveTimestep:{boolean:bool},wind:{x:{number},y:{number},__type__:{object}},__type__:{object,boolean:bool}},//globals :
autoResize:{boolean:bool},clickToUse:{boolean:bool},locale:{string},locales:{__any__:{any},__type__:{object}},height:{string},width:{string},__type__:{object}};/* eslint-enable @typescript-eslint/naming-convention */ /**
* This provides ranges, initial values, steps and dropdown menu choices for the
* configuration.
*
* @remarks
* Checkbox: `boolean`
* The value supllied will be used as the initial value.
*
* Text field: `string`
* The passed text will be used as the initial value. Any text will be
* accepted afterwards.
*
* Number range: `[number, number, number, number]`
* The meanings are `[initial value, min, max, step]`.
*
* Dropdown: `[Exclude<string, "color">, ...(string | number | boolean)[]]`
* Translations for people with poor understanding of TypeScript: the first
* value always has to be a string but never `"color"`, the rest can be any
* combination of strings, numbers and booleans.
*
* Color picker: `["color", string]`
* The first value says this will be a color picker not a dropdown menu. The
* next value is the initial color.
*/const configureOptions={nodes:{borderWidth:[1,0,10,1],borderWidthSelected:[2,0,10,1],color:{border:["color","#2B7CE9"],background:["color","#97C2FC"],highlight:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]},hover:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]}},opacity:[0,0,1,0.1],fixed:{x:false,y:false},font:{color:["color","#343434"],size:[14,0,100,1],face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[0,0,50,1],strokeColor:["color","#ffffff"]},//group: 'string',
hidden:false,labelHighlightBold:true,//icon: {
// face: 'string', //'FontAwesome',
// code: 'string', //'\uf007',
// size: [50, 0, 200, 1], //50,
// color: ['color','#2B7CE9'] //'#aa00ff'
//},
//image: 'string', // --> URL
physics:true,scaling:{min:[10,0,200,1],max:[30,0,200,1],label:{enabled:false,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},shape:["ellipse","box","circle","database","diamond","dot","square","star","text","triangle","triangleDown","hexagon"],shapeProperties:{borderDashes:false,borderRadius:[6,0,20,1],interpolation:true,useImageSize:false},size:[25,0,200,1]},edges:{arrows:{to:{enabled:false,scaleFactor:[1,0,3,0.05],type:"arrow"},middle:{enabled:false,scaleFactor:[1,0,3,0.05],type:"arrow"},from:{enabled:false,scaleFactor:[1,0,3,0.05],type:"arrow"}},endPointOffset:{from:[0,-10,10,1],to:[0,-10,10,1]},arrowStrikethrough:true,color:{color:["color","#848484"],highlight:["color","#848484"],hover:["color","#848484"],inherit:["from","to","both",true,false],opacity:[1,0,1,0.05]},dashes:false,font:{color:["color","#343434"],size:[14,0,100,1],face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[2,0,50,1],strokeColor:["color","#ffffff"],align:["horizontal","top","middle","bottom"]},hidden:false,hoverWidth:[1.5,0,5,0.1],labelHighlightBold:true,physics:true,scaling:{min:[1,0,100,1],max:[15,0,100,1],label:{enabled:true,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},selectionWidth:[1.5,0,5,0.1],selfReferenceSize:[20,0,200,1],selfReference:{size:[20,0,200,1],angle:[Math.PI/2,-6*Math.PI,6*Math.PI,Math.PI/8],renderBehindTheNode:true},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},smooth:{enabled:true,type:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW","cubicBezier"],forceDirection:["horizontal","vertical","none"],roundness:[0.5,0,1,0.05]},width:[1,0,30,1]},layout:{//randomSeed: [0, 0, 500, 1],
//improvedLayout: true,
hierarchical:{enabled:false,levelSeparation:[150,20,500,5],nodeSpacing:[100,20,500,5],treeSpacing:[200,20,500,5],blockShifting:true,edgeMinimization:true,parentCentralization:true,direction:["UD","DU","LR","RL"],sortMethod:["hubsize","directed"],shakeTowards:["leaves","roots"]// leaves, roots
}},interaction:{dragNodes:true,dragView:true,hideEdgesOnDrag:false,hideEdgesOnZoom:false,hideNodesOnDrag:false,hover:false,keyboard:{enabled:false,speed:{x:[10,0,40,1],y:[10,0,40,1],zoom:[0.02,0,0.1,0.005]},bindToWindow:true,autoFocus:true},multiselect:false,navigationButtons:false,selectable:true,selectConnectedEdges:true,hoverConnectedEdges:true,tooltipDelay:[300,0,1000,25],zoomView:true,zoomSpeed:[1,0.1,2,0.1]},manipulation:{enabled:false,initiallyActive:false},physics:{enabled:true,barnesHut:{theta:[0.5,0.1,1,0.05],gravitationalConstant:[-2000,-30000,0,50],centralGravity:[0.3,0,10,0.05],springLength:[95,0,500,5],springConstant:[0.04,0,1.2,0.005],damping:[0.09,0,1,0.01],avoidOverlap:[0,0,1,0.01]},forceAtlas2Based:{theta:[0.5,0.1,1,0.05],gravitationalConstant:[-50,-500,0,1],centralGravity:[0.01,0,1,0.005],springLength:[95,0,500,5],springConstant:[0.08,0,1.2,0.005],damping:[0.4,0,1,0.01],avoidOverlap:[0,0,1,0.01]},repulsion:{centralGravity:[0.2,0,10,0.05],springLength:[200,0,500,5],springConstant:[0.05,0,1.2,0.005],nodeDistance:[100,0,500,5],damping:[0.09,0,1,0.01]},hierarchicalRepulsion:{centralGravity:[0.2,0,10,0.05],springLength:[100,0,500,5],springConstant:[0.01,0,1.2,0.005],nodeDistance:[120,0,500,5],damping:[0.09,0,1,0.01],avoidOverlap:[0,0,1,0.01]},maxVelocity:[50,0,150,1],minVelocity:[0.1,0.01,0.5,0.01],solver:["barnesHut","forceAtlas2Based","repulsion","hierarchicalRepulsion"],timestep:[0.5,0.01,1,0.01],wind:{x:[0,-10,10,0.1],y:[0,-10,10,0.1]}//adaptiveTimestep: true
}};const configuratorHideOption=(parentPath,optionName,options)=>{if(parentPath.includes("physics")&&configureOptions.physics.solver.includes(optionName)&&options.physics.solver!==optionName&&optionName!=="wind"){return true;}return false;};/**
* The Floyd–Warshall algorithm is an algorithm for finding shortest paths in
* a weighted graph with positive or negative edge weights (but with no negative
* cycles). - https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm
*/class FloydWarshall{/**
* @ignore
*/constructor(){}/**
*
* @param {object} body
* @param {Array.<Node>} nodesArray
* @param {Array.<Edge>} edgesArray
* @returns {{}}
*/getDistances(body,nodesArray,edgesArray){const D_matrix={};const edges=body.edges;// prepare matrix with large numbers
for(let i=0;i<nodesArray.length;i++){const node=nodesArray[i];const cell={};D_matrix[node]=cell;for(let j=0;j<nodesArray.length;j++){cell[nodesArray[j]]=i==j?0:1e9;}}// put the weights for the edges in. This assumes unidirectionality.
for(let i=0;i<edgesArray.length;i++){const edge=edges[edgesArray[i]];// edge has to be connected if it counts to the distances. If it is connected to inner clusters it will crash so we also check if it is in the D_matrix
if(edge.connected===true&&D_matrix[edge.fromId]!==undefined&&D_matrix[edge.toId]!==undefined){D_matrix[edge.fromId][edge.toId]=1;D_matrix[edge.toId][edge.fromId]=1;}}const nodeCount=nodesArray.length;// Adapted FloydWarshall based on unidirectionality to greatly reduce complexity.
for(let k=0;k<nodeCount;k++){const knode=nodesArray[k];const kcolm=D_matrix[knode];for(let i=0;i<nodeCount-1;i++){const inode=nodesArray[i];const icolm=D_matrix[inode];for(let j=i+1;j<nodeCount;j++){const jnode=nodesArray[j];const jcolm=D_matrix[jnode];const val=Math.min(icolm[jnode],icolm[knode]+kcolm[jnode]);icolm[jnode]=val;jcolm[inode]=val;}}}return D_matrix;}}// distance finding algorithm
/**
* KamadaKawai positions the nodes initially based on
*
* "AN ALGORITHM FOR DRAWING GENERAL UNDIRECTED GRAPHS"
* -- Tomihisa KAMADA and Satoru KAWAI in 1989
*
* Possible optimizations in the distance calculation can be implemented.
*/class KamadaKawai{/**
* @param {object} body
* @param {number} edgeLength
* @param {number} edgeStrength
*/constructor(body,edgeLength,edgeStrength){this.body=body;this.springLength=edgeLength;this.springConstant=edgeStrength;this.distanceSolver=new FloydWarshall();}/**
* Not sure if needed but can be used to update the spring length and spring constant
*
* @param {object} options
*/setOptions(options){if(options){if(options.springLength){this.springLength=options.springLength;}if(options.springConstant){this.springConstant=options.springConstant;}}}/**
* Position the system
*
* @param {Array.<Node>} nodesArray
* @param {Array.<vis.Edge>} edgesArray
* @param {boolean} [ignoreClusters=false]
*/solve(nodesArray,edgesArray,ignoreClusters=false){// get distance matrix
const D_matrix=this.distanceSolver.getDistances(this.body,nodesArray,edgesArray);// distance matrix
// get the L Matrix
this._createL_matrix(D_matrix);// get the K Matrix
this._createK_matrix(D_matrix);// initial E Matrix
this._createE_matrix();// calculate positions
const threshold=0.01;const innerThreshold=1;let iterations=0;const maxIterations=Math.max(1000,Math.min(10*this.body.nodeIndices.length,6000));const maxInnerIterations=5;let maxEnergy=1e9;let highE_nodeId=0,dE_dx=0,dE_dy=0,delta_m=0,subIterations=0;while(maxEnergy>threshold&&iterations<maxIterations){iterations+=1;[highE_nodeId,maxEnergy,dE_dx,dE_dy]=this._getHighestEnergyNode(ignoreClusters);delta_m=maxEnergy;subIterations=0;while(delta_m>innerThreshold&&subIterations<maxInnerIterations){subIterations+=1;this._moveNode(highE_nodeId,dE_dx,dE_dy);[delta_m,dE_dx,dE_dy]=this._getEnergy(highE_nodeId);}}}/**
* get the node with the highest energy
*
* @param {boolean} ignoreClusters
* @returns {number[]}
* @private
*/_getHighestEnergyNode(ignoreClusters){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;let maxEnergy=0;let maxEnergyNodeId=nodesArray[0];let dE_dx_max=0,dE_dy_max=0;for(let nodeIdx=0;nodeIdx<nodesArray.length;nodeIdx++){const m=nodesArray[nodeIdx];// by not evaluating nodes with predefined positions we should only move nodes that have no positions.
if(nodes[m].predefinedPosition!==true||nodes[m].isCluster===true&&ignoreClusters===true||nodes[m].options.fixed.x!==true||nodes[m].options.fixed.y!==true){const[delta_m,dE_dx,dE_dy]=this._getEnergy(m);if(maxEnergy<delta_m){maxEnergy=delta_m;maxEnergyNodeId=m;dE_dx_max=dE_dx;dE_dy_max=dE_dy;}}}return [maxEnergyNodeId,maxEnergy,dE_dx_max,dE_dy_max];}/**
* calculate the energy of a single node
*
* @param {Node.id} m
* @returns {number[]}
* @private
*/_getEnergy(m){const[dE_dx,dE_dy]=this.E_sums[m];const delta_m=Math.sqrt(dE_dx**2+dE_dy**2);return [delta_m,dE_dx,dE_dy];}/**
* move the node based on it's energy
* the dx and dy are calculated from the linear system proposed by Kamada and Kawai
*
* @param {number} m
* @param {number} dE_dx
* @param {number} dE_dy
* @private
*/_moveNode(m,dE_dx,dE_dy){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;let d2E_dx2=0;let d2E_dxdy=0;let d2E_dy2=0;const x_m=nodes[m].x;const y_m=nodes[m].y;const km=this.K_matrix[m];const lm=this.L_matrix[m];for(let iIdx=0;iIdx<nodesArray.length;iIdx++){const i=nodesArray[iIdx];if(i!==m){const x_i=nodes[i].x;const y_i=nodes[i].y;const kmat=km[i];const lmat=lm[i];const denominator=1.0/((x_m-x_i)**2+(y_m-y_i)**2)**1.5;d2E_dx2+=kmat*(1-lmat*(y_m-y_i)**2*denominator);d2E_dxdy+=kmat*(lmat*(x_m-x_i)*(y_m-y_i)*denominator);d2E_dy2+=kmat*(1-lmat*(x_m-x_i)**2*denominator);}}// make the variable names easier to make the solving of the linear system easier to read
const A=d2E_dx2,B=d2E_dxdy,C=dE_dx,D=d2E_dy2,E=dE_dy;// solve the linear system for dx and dy
const dy=(C/A+E/B)/(B/A-D/B);const dx=-(B*dy+C)/A;// move the node
nodes[m].x+=dx;nodes[m].y+=dy;// Recalculate E_matrix (should be incremental)
this._updateE_matrix(m);}/**
* Create the L matrix: edge length times shortest path
*
* @param {object} D_matrix
* @private
*/_createL_matrix(D_matrix){const nodesArray=this.body.nodeIndices;const edgeLength=this.springLength;this.L_matrix=[];for(let i=0;i<nodesArray.length;i++){this.L_matrix[nodesArray[i]]={};for(let j=0;j<nodesArray.length;j++){this.L_matrix[nodesArray[i]][nodesArray[j]]=edgeLength*D_matrix[nodesArray[i]][nodesArray[j]];}}}/**
* Create the K matrix: spring constants times shortest path
*
* @param {object} D_matrix
* @private
*/_createK_matrix(D_matrix){const nodesArray=this.body.nodeIndices;const edgeStrength=this.springConstant;this.K_matrix=[];for(let i=0;i<nodesArray.length;i++){this.K_matrix[nodesArray[i]]={};for(let j=0;j<nodesArray.length;j++){this.K_matrix[nodesArray[i]][nodesArray[j]]=edgeStrength*D_matrix[nodesArray[i]][nodesArray[j]]**-2;}}}/**
* Create matrix with all energies between nodes
*
* @private
*/_createE_matrix(){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;this.E_matrix={};this.E_sums={};for(let mIdx=0;mIdx<nodesArray.length;mIdx++){this.E_matrix[nodesArray[mIdx]]=[];}for(let mIdx=0;mIdx<nodesArray.length;mIdx++){const m=nodesArray[mIdx];const x_m=nodes[m].x;const y_m=nodes[m].y;let dE_dx=0;let dE_dy=0;for(let iIdx=mIdx;iIdx<nodesArray.length;iIdx++){const i=nodesArray[iIdx];if(i!==m){const x_i=nodes[i].x;const y_i=nodes[i].y;const denominator=1.0/Math.sqrt((x_m-x_i)**2+(y_m-y_i)**2);this.E_matrix[m][iIdx]=[this.K_matrix[m][i]*(x_m-x_i-this.L_matrix[m][i]*(x_m-x_i)*denominator),this.K_matrix[m][i]*(y_m-y_i-this.L_matrix[m][i]*(y_m-y_i)*denominator)];this.E_matrix[i][mIdx]=this.E_matrix[m][iIdx];dE_dx+=this.E_matrix[m][iIdx][0];dE_dy+=this.E_matrix[m][iIdx][1];}}//Store sum
this.E_sums[m]=[dE_dx,dE_dy];}}/**
* Update method, just doing single column (rows are auto-updated) (update all sums)
*
* @param {number} m
* @private
*/_updateE_matrix(m){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;const colm=this.E_matrix[m];const kcolm=this.K_matrix[m];const lcolm=this.L_matrix[m];const x_m=nodes[m].x;const y_m=nodes[m].y;let dE_dx=0;let dE_dy=0;for(let iIdx=0;iIdx<nodesArray.length;iIdx++){const i=nodesArray[iIdx];if(i!==m){//Keep old energy value for sum modification below
const cell=colm[iIdx];const oldDx=cell[0];const oldDy=cell[1];//Calc new energy:
const x_i=nodes[i].x;const y_i=nodes[i].y;const denominator=1.0/Math.sqrt((x_m-x_i)**2+(y_m-y_i)**2);const dx=kcolm[i]*(x_m-x_i-lcolm[i]*(x_m-x_i)*denominator);const dy=kcolm[i]*(y_m-y_i-lcolm[i]*(y_m-y_i)*denominator);colm[iIdx]=[dx,dy];dE_dx+=dx;dE_dy+=dy;//add new energy to sum of each column
const sum=this.E_sums[i];sum[0]+=dx-oldDx;sum[1]+=dy-oldDy;}}//Store sum at -1 index
this.E_sums[m]=[dE_dx,dE_dy];}}// Load custom shapes into CanvasRenderingContext2D
/**
* Create a network visualization, displaying nodes and edges.
*
* @param {Element} container The DOM element in which the Network will
* be created. Normally a div element.
* @param {object} data An object containing parameters
* {Array} nodes
* {Array} edges
* @param {object} options Options
* @class Network
*/function Network(container,data,options){if(!(this instanceof Network)){throw new SyntaxError("Constructor must be called with the new operator");}// set constant values
this.options={};this.defaultOptions={locale:"en",locales:locales,clickToUse:false};Object.assign(this.options,this.defaultOptions);/**
* Containers for nodes and edges.
*
* 'edges' and 'nodes' contain the full definitions of all the network elements.
* 'nodeIndices' and 'edgeIndices' contain the id's of the active elements.
*
* The distinction is important, because a defined node need not be active, i.e.
* visible on the canvas. This happens in particular when clusters are defined, in
* that case there will be nodes and edges not displayed.
* The bottom line is that all code with actions related to visibility, *must* use
* 'nodeIndices' and 'edgeIndices', not 'nodes' and 'edges' directly.
*/this.body={container:container,// See comment above for following fields
nodes:{},nodeIndices:[],edges:{},edgeIndices:[],emitter:{on:this.on.bind(this),off:this.off.bind(this),emit:this.emit.bind(this),once:this.once.bind(this)},eventListeners:{onTap:function(){},onTouch:function(){},onDoubleTap:function(){},onHold:function(){},onDragStart:function(){},onDrag:function(){},onDragEnd:function(){},onMouseWheel:function(){},onPinch:function(){},onMouseMove:function(){},onRelease:function(){},onContext:function(){}},data:{nodes:null,// A DataSet or DataView
edges:null// A DataSet or DataView
},functions:{createNode:function(){},createEdge:function(){},getPointer:function(){}},modules:{},view:{scale:1,translation:{x:0,y:0}},selectionBox:{show:false,position:{start:{x:0,y:0},end:{x:0,y:0}}}};// bind the event listeners
this.bindEventListeners();// setting up all modules
this.images=new Images(()=>this.body.emitter.emit("_requestRedraw"));// object with images
this.groups=new Groups();// object with groups
this.canvas=new Canvas(this.body);// DOM handler
this.selectionHandler=new SelectionHandler(this.body,this.canvas);// Selection handler
this.interactionHandler=new InteractionHandler(this.body,this.canvas,this.selectionHandler);// Interaction handler handles all the hammer bindings (that are bound by canvas), key
this.view=new View(this.body,this.canvas);// camera handler, does animations and zooms
this.renderer=new CanvasRenderer(this.body,this.canvas);// renderer, starts renderloop, has events that modules can hook into
this.physics=new PhysicsEngine(this.body);// physics engine, does all the simulations
this.layoutEngine=new LayoutEngine(this.body);// layout engine for inital layout and hierarchical layout
this.clustering=new ClusterEngine(this.body);// clustering api
this.manipulation=new ManipulationSystem(this.body,this.canvas,this.selectionHandler,this.interactionHandler);// data manipulation system
this.nodesHandler=new NodesHandler(this.body,this.images,this.groups,this.layoutEngine);// Handle adding, deleting and updating of nodes as well as global options
this.edgesHandler=new EdgesHandler(this.body,this.images,this.groups);// Handle adding, deleting and updating of edges as well as global options
this.body.modules["kamadaKawai"]=new KamadaKawai(this.body,150,0.05);// Layouting algorithm.
this.body.modules["clustering"]=this.clustering;// create the DOM elements
this.canvas._create();// apply options
this.setOptions(options);// load data (the disable start variable will be the same as the enabled clustering)
this.setData(data);}// Extend Network with an Emitter mixin
componentEmitter(Network.prototype);/**
* Set options
*
* @param {object} options
*/Network.prototype.setOptions=function(options){if(options===null){options=undefined;// This ensures that options handling doesn't crash in the handling
}if(options!==undefined){const errorFound=Validator$2.validate(options,allOptions);if(errorFound===true){console.error("%cErrors have been found in the supplied options object.",VALIDATOR_PRINT_STYLE);}// copy the global fields over
const fields=["locale","locales","clickToUse"];selectiveDeepExtend(fields,this.options,options);// normalize the locale or use English
if(options.locale!==undefined){options.locale=normalizeLanguageCode(options.locales||this.options.locales,options.locale);}// the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
options=this.layoutEngine.setOptions(options.layout,options);this.canvas.setOptions(options);// options for canvas are in globals
// pass the options to the modules
this.groups.setOptions(options.groups);this.nodesHandler.setOptions(options.nodes);this.edgesHandler.setOptions(options.edges);this.physics.setOptions(options.physics);this.manipulation.setOptions(options.manipulation,options,this.options);// manipulation uses the locales in the globals
this.interactionHandler.setOptions(options.interaction);this.renderer.setOptions(options.interaction);// options for rendering are in interaction
this.selectionHandler.setOptions(options.interaction);// options for selection are in interaction
// reload the settings of the nodes to apply changes in groups that are not referenced by pointer.
if(options.groups!==undefined){this.body.emitter.emit("refreshNodes");}// these two do not have options at the moment, here for completeness
//this.view.setOptions(options.view);
//this.clustering.setOptions(options.clustering);
if("configure"in options){if(!this.configurator){this.configurator=new Configurator$2(this,this.body.container,configureOptions,this.canvas.pixelRatio,configuratorHideOption);}this.configurator.setOptions(options.configure);}// if the configuration system is enabled, copy all options and put them into the config system
if(this.configurator&&this.configurator.options.enabled===true){const networkOptions={nodes:{},edges:{},layout:{},interaction:{},manipulation:{},physics:{},global:{}};deepExtend(networkOptions.nodes,this.nodesHandler.options);deepExtend(networkOptions.edges,this.edgesHandler.options);deepExtend(networkOptions.layout,this.layoutEngine.options);// load the selectionHandler and render default options in to the interaction group
deepExtend(networkOptions.interaction,this.selectionHandler.options);deepExtend(networkOptions.interaction,this.renderer.options);deepExtend(networkOptions.interaction,this.interactionHandler.options);deepExtend(networkOptions.manipulation,this.manipulation.options);deepExtend(networkOptions.physics,this.physics.options);// load globals into the global object
deepExtend(networkOptions.global,this.canvas.options);deepExtend(networkOptions.global,this.options);this.configurator.setModuleOptions(networkOptions);}// handle network global options
if(options.clickToUse!==undefined){if(options.clickToUse===true){if(this.activator===undefined){this.activator=new Activator$2(this.canvas.frame);this.activator.on("change",()=>{this.body.emitter.emit("activate");});}}else {if(this.activator!==undefined){this.activator.destroy();delete this.activator;}this.body.emitter.emit("activate");}}else {this.body.emitter.emit("activate");}this.canvas.setSize();// start the physics simulation. Can be safely called multiple times.
this.body.emitter.emit("startSimulation");}};/**
* Update the visible nodes and edges list with the most recent node state.
*
* Visible nodes are stored in this.body.nodeIndices.
* Visible edges are stored in this.body.edgeIndices.
* A node or edges is visible if it is not hidden or clustered.
*
* @private
*/Network.prototype._updateVisibleIndices=function(){const nodes=this.body.nodes;const edges=this.body.edges;this.body.nodeIndices=[];this.body.edgeIndices=[];for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){if(!this.clustering._isClusteredNode(nodeId)&&nodes[nodeId].options.hidden===false){this.body.nodeIndices.push(nodes[nodeId].id);}}}for(const edgeId in edges){if(Object.prototype.hasOwnProperty.call(edges,edgeId)){const edge=edges[edgeId];// It can happen that this is executed *after* a node edge has been removed,
// but *before* the edge itself has been removed. Taking this into account.
const fromNode=nodes[edge.fromId];const toNode=nodes[edge.toId];const edgeNodesPresent=fromNode!==undefined&&toNode!==undefined;const isVisible=!this.clustering._isClusteredEdge(edgeId)&&edge.options.hidden===false&&edgeNodesPresent&&fromNode.options.hidden===false&&// Also hidden if any of its connecting nodes are hidden
toNode.options.hidden===false;// idem
if(isVisible){this.body.edgeIndices.push(edge.id);}}}};/**
* Bind all events
*/Network.prototype.bindEventListeners=function(){// This event will trigger a rebuilding of the cache everything.
// Used when nodes or edges have been added or removed.
this.body.emitter.on("_dataChanged",()=>{this.edgesHandler._updateState();this.body.emitter.emit("_dataUpdated");});// this is called when options of EXISTING nodes or edges have changed.
this.body.emitter.on("_dataUpdated",()=>{// Order important in following block
this.clustering._updateState();this._updateVisibleIndices();this._updateValueRange(this.body.nodes);this._updateValueRange(this.body.edges);// start simulation (can be called safely, even if already running)
this.body.emitter.emit("startSimulation");this.body.emitter.emit("_requestRedraw");});};/**
* Set nodes and edges, and optionally options as well.
*
* @param {object} data Object containing parameters:
* {Array | DataSet | DataView} [nodes] Array with nodes
* {Array | DataSet | DataView} [edges] Array with edges
* {String} [dot] String containing data in DOT format
* {String} [gephi] String containing data in gephi JSON format
* {Options} [options] Object with options
*/Network.prototype.setData=function(data){// reset the physics engine.
this.body.emitter.emit("resetPhysics");this.body.emitter.emit("_resetData");// unselect all to ensure no selections from old data are carried over.
this.selectionHandler.unselectAll();if(data&&data.dot&&(data.nodes||data.edges)){throw new SyntaxError('Data must contain either parameter "dot" or '+' parameter pair "nodes" and "edges", but not both.');}// set options
this.setOptions(data&&data.options);// set all data
if(data&&data.dot){console.warn("The dot property has been deprecated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);");// parse DOT file
const dotData=DOTToGraph(data.dot);this.setData(dotData);return;}else if(data&&data.gephi){// parse DOT file
console.warn("The gephi property has been deprecated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);");const gephiData=parseGephi(data.gephi);this.setData(gephiData);return;}else {this.nodesHandler.setData(data&&data.nodes,true);this.edgesHandler.setData(data&&data.edges,true);}// emit change in data
this.body.emitter.emit("_dataChanged");// emit data loaded
this.body.emitter.emit("_dataLoaded");// find a stable position or start animating to a stable position
this.body.emitter.emit("initPhysics");};/**
* Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
* var network = new vis.Network(..);
* network.destroy();
* network = null;
*/Network.prototype.destroy=function(){this.body.emitter.emit("destroy");// clear events
this.body.emitter.off();this.off();// delete modules
delete this.groups;delete this.canvas;delete this.selectionHandler;delete this.interactionHandler;delete this.view;delete this.renderer;delete this.physics;delete this.layoutEngine;delete this.clustering;delete this.manipulation;delete this.nodesHandler;delete this.edgesHandler;delete this.configurator;delete this.images;for(const nodeId in this.body.nodes){if(!Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId))continue;delete this.body.nodes[nodeId];}for(const edgeId in this.body.edges){if(!Object.prototype.hasOwnProperty.call(this.body.edges,edgeId))continue;delete this.body.edges[edgeId];}// remove the container and everything inside it recursively
recursiveDOMDelete(this.body.container);};/**
* Update the values of all object in the given array according to the current
* value range of the objects in the array.
*
* @param {object} obj An object containing a set of Edges or Nodes
* The objects must have a method getValue() and
* setValueRange(min, max).
* @private
*/Network.prototype._updateValueRange=function(obj){let id;// determine the range of the objects
let valueMin=undefined;let valueMax=undefined;let valueTotal=0;for(id in obj){if(Object.prototype.hasOwnProperty.call(obj,id)){const value=obj[id].getValue();if(value!==undefined){valueMin=valueMin===undefined?value:Math.min(value,valueMin);valueMax=valueMax===undefined?value:Math.max(value,valueMax);valueTotal+=value;}}}// adjust the range of all objects
if(valueMin!==undefined&&valueMax!==undefined){for(id in obj){if(Object.prototype.hasOwnProperty.call(obj,id)){obj[id].setValueRange(valueMin,valueMax,valueTotal);}}}};/**
* Returns true when the Network is active.
*
* @returns {boolean}
*/Network.prototype.isActive=function(){return !this.activator||this.activator.active;};Network.prototype.setSize=function(){return this.canvas.setSize.apply(this.canvas,arguments);};Network.prototype.canvasToDOM=function(){return this.canvas.canvasToDOM.apply(this.canvas,arguments);};Network.prototype.DOMtoCanvas=function(){return this.canvas.DOMtoCanvas.apply(this.canvas,arguments);};/**
* Nodes can be in clusters. Clusters can also be in clusters. This function returns and array of
* nodeIds showing where the node is.
*
* If any nodeId in the chain, especially the first passed in as a parameter, is not present in
* the current nodes list, an empty array is returned.
*
* Example:
* cluster 'A' contains cluster 'B',
* cluster 'B' contains cluster 'C',
* cluster 'C' contains node 'fred'.
* `jsnetwork.clustering.findNode('fred')` will return `['A','B','C','fred']`.
*
* @param {string|number} nodeId
* @returns {Array}
*/Network.prototype.findNode=function(){return this.clustering.findNode.apply(this.clustering,arguments);};Network.prototype.isCluster=function(){return this.clustering.isCluster.apply(this.clustering,arguments);};Network.prototype.openCluster=function(){return this.clustering.openCluster.apply(this.clustering,arguments);};Network.prototype.cluster=function(){return this.clustering.cluster.apply(this.clustering,arguments);};Network.prototype.getNodesInCluster=function(){return this.clustering.getNodesInCluster.apply(this.clustering,arguments);};Network.prototype.clusterByConnection=function(){return this.clustering.clusterByConnection.apply(this.clustering,arguments);};Network.prototype.clusterByHubsize=function(){return this.clustering.clusterByHubsize.apply(this.clustering,arguments);};Network.prototype.updateClusteredNode=function(){return this.clustering.updateClusteredNode.apply(this.clustering,arguments);};Network.prototype.getClusteredEdges=function(){return this.clustering.getClusteredEdges.apply(this.clustering,arguments);};Network.prototype.getBaseEdge=function(){return this.clustering.getBaseEdge.apply(this.clustering,arguments);};Network.prototype.getBaseEdges=function(){return this.clustering.getBaseEdges.apply(this.clustering,arguments);};Network.prototype.updateEdge=function(){return this.clustering.updateEdge.apply(this.clustering,arguments);};/**
* This method will cluster all nodes with 1 edge with their respective connected node.
* The options object is explained in full <a data-scroll="" data-options="{ "easing": "easeInCubic" }" href="#optionsObject">below</a>.
*
* @param {object} [options]
* @returns {undefined}
*/Network.prototype.clusterOutliers=function(){return this.clustering.clusterOutliers.apply(this.clustering,arguments);};Network.prototype.getSeed=function(){return this.layoutEngine.getSeed.apply(this.layoutEngine,arguments);};Network.prototype.enableEditMode=function(){return this.manipulation.enableEditMode.apply(this.manipulation,arguments);};Network.prototype.disableEditMode=function(){return this.manipulation.disableEditMode.apply(this.manipulation,arguments);};Network.prototype.addNodeMode=function(){return this.manipulation.addNodeMode.apply(this.manipulation,arguments);};Network.prototype.editNode=function(){return this.manipulation.editNode.apply(this.manipulation,arguments);};Network.prototype.editNodeMode=function(){console.warn("Deprecated: Please use editNode instead of editNodeMode.");return this.manipulation.editNode.apply(this.manipulation,arguments);};Network.prototype.addEdgeMode=function(){return this.manipulation.addEdgeMode.apply(this.manipulation,arguments);};Network.prototype.editEdgeMode=function(){return this.manipulation.editEdgeMode.apply(this.manipulation,arguments);};Network.prototype.deleteSelected=function(){return this.manipulation.deleteSelected.apply(this.manipulation,arguments);};Network.prototype.getPositions=function(){return this.nodesHandler.getPositions.apply(this.nodesHandler,arguments);};Network.prototype.getPosition=function(){return this.nodesHandler.getPosition.apply(this.nodesHandler,arguments);};Network.prototype.storePositions=function(){return this.nodesHandler.storePositions.apply(this.nodesHandler,arguments);};Network.prototype.moveNode=function(){return this.nodesHandler.moveNode.apply(this.nodesHandler,arguments);};Network.prototype.getBoundingBox=function(){return this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments);};Network.prototype.getConnectedNodes=function(objectId){if(this.body.nodes[objectId]!==undefined){return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments);}else {return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler,arguments);}};Network.prototype.getConnectedEdges=function(){return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler,arguments);};Network.prototype.startSimulation=function(){return this.physics.startSimulation.apply(this.physics,arguments);};Network.prototype.stopSimulation=function(){return this.physics.stopSimulation.apply(this.physics,arguments);};Network.prototype.stabilize=function(){return this.physics.stabilize.apply(this.physics,arguments);};Network.prototype.getSelection=function(){return this.selectionHandler.getSelection.apply(this.selectionHandler,arguments);};Network.prototype.setSelection=function(){return this.selectionHandler.setSelection.apply(this.selectionHandler,arguments);};Network.prototype.getSelectedNodes=function(){return this.selectionHandler.getSelectedNodeIds.apply(this.selectionHandler,arguments);};Network.prototype.getSelectedEdges=function(){return this.selectionHandler.getSelectedEdgeIds.apply(this.selectionHandler,arguments);};Network.prototype.getNodeAt=function(){const node=this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments);if(node!==undefined&&node.id!==undefined){return node.id;}return node;};Network.prototype.getEdgeAt=function(){const edge=this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments);if(edge!==undefined&&edge.id!==undefined){return edge.id;}return edge;};Network.prototype.selectNodes=function(){return this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments);};Network.prototype.selectEdges=function(){return this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments);};Network.prototype.unselectAll=function(){this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments);this.selectionHandler.commitWithoutEmitting.apply(this.selectionHandler);this.redraw();};Network.prototype.redraw=function(){return this.renderer.redraw.apply(this.renderer,arguments);};Network.prototype.getScale=function(){return this.view.getScale.apply(this.view,arguments);};Network.prototype.getViewPosition=function(){return this.view.getViewPosition.apply(this.view,arguments);};Network.prototype.fit=function(){return this.view.fit.apply(this.view,arguments);};Network.prototype.moveTo=function(){return this.view.moveTo.apply(this.view,arguments);};Network.prototype.focus=function(){return this.view.focus.apply(this.view,arguments);};Network.prototype.releaseNode=function(){return this.view.releaseNode.apply(this.view,arguments);};Network.prototype.getOptionsFromConfigurator=function(){let options={};if(this.configurator){options=this.configurator.getOptions.apply(this.configurator);}return options;};
var script = {
name: 'network',
props: {
edges: {
type: [Array, DataSet, DataView],
default: () => []
},
nodes: {
type: [Array, DataSet, DataView],
default: () => []
},
events: {
type: Array,
default: () => ['click', 'doubleClick', 'oncontext', 'hold', 'release', 'select', 'selectNode', 'selectEdge', 'deselectNode', 'deselectEdge', 'dragStart', 'dragging', 'dragEnd', 'hoverNode', 'blurNode', 'hoverEdge', 'blurEdge', 'zoom', 'showPopup', 'hidePopup', 'startStabilizing', 'stabilizationProgress', 'stabilizationIterationsDone', 'stabilized', 'resize', 'initRedraw', 'beforeDrawing', 'afterDrawing', 'animationFinished', 'configChange']
},
options: {
type: Object,
default: () => ({})
}
},
data: () => ({
visData: {
nodes: null,
edges: null
}
}),
computed: {
dsNodes() {
return new DataSet(this.nodes);
}
},
watchEffect: {
options: {
deep: true,
handler(o) {
this.network.setOptions(o);
}
}
},
methods: {
setData(n, e) {
this.visData.nodes = Array.isArray(n) ? new DataSet(n) : n;
this.visData.edges = Array.isArray(e) ? new DataSet(e) : e;
this.network.setData(this.visData);
},
destroy() {
this.network.destroy();
},
getNode(id) {
return this.visData.nodes.get(id);
},
getEdge(id) {
return this.visData.edges.get(id);
},
setOptions(options) {
this.network.setOptions(options);
},
on(event, callback) {
this.network.on(event, callback);
},
off(event, callback) {
this.network.off(event, callback);
},
once(event, callback) {
this.network.once(event, callback);
},
canvasToDom(p) {
return this.network.canvasToDOM(p);
},
domToCanvas(p) {
return this.network.DOMtoCanvas(p);
},
redraw() {
this.network.redraw();
},
setSize(w, h) {
this.network.setSize(w, h);
},
cluster(options) {
this.network.cluster(options);
},
clusterByConnection(nodeId, options) {
this.network.clusterByConnection(nodeId, options);
},
clusterByHubsize(hubsize, options) {
this.network.clusterByHubsize(hubsize, options);
},
clusterOutliers(options) {
this.network.clusterOutliers(options);
},
findNode(id) {
return this.network.findNode(id);
},
getClusteredEdges(baseEdgeId) {
return this.network.clustering.getClusteredEdges(baseEdgeId);
},
getBaseEdge(clusteredEdgeId) {
return this.network.clustering.getBaseEdge(clusteredEdgeId);
},
getBaseEdges(clusteredEdgeId) {
return this.network.clustering.getBaseEdges(clusteredEdgeId);
},
updateEdge(startEdgeId, options) {
this.network.clustering.updateEdge(startEdgeId, options);
},
updateClusteredNode(clusteredNodeId, options) {
this.network.clustering.updateClusteredNode(clusteredNodeId, options);
},
isCluster(nodeId) {
return this.network.isCluster(nodeId);
},
getNodesInCluster(clusterNodeId) {
return this.network.getNodesInCluster(clusterNodeId);
},
openCluster(nodeId, options) {
this.network.openCluster(nodeId, options);
},
getSeed() {
return this.network.getSeed();
},
enableEditMode() {
this.network.enableEditMode();
},
disableEditMode() {
this.network.disableEditMode();
},
addNodeMode() {
this.network.addNodeMode();
},
editNode() {
this.network.editNode();
},
addEdgeMode() {
this.network.addEdgeMode();
},
editEdgeMode() {
this.network.editEdgeMode();
},
deleteSelected() {
this.network.deleteSelected();
},
getPositions(nodeIds) {
return this.network.getPositions(nodeIds);
},
storePositions() {
this.network.storePositions();
},
moveNode(nodeId, x, y) {
this.network.moveNode(nodeId, x, y);
},
getBoundingBox(nodeId) {
return this.network.getBoundingBox(nodeId);
},
getConnectedNodes(nodeId, direction) {
return this.network.getConnectedNodes(nodeId, direction);
},
getConnectedEdges(nodeId) {
return this.network.getConnectedEdges(nodeId);
},
startSimulation() {
this.network.startSimulation();
},
stopSimulation() {
this.network.stopSimulation();
},
stabilize(iterations) {
this.network.stabilize(iterations);
},
getSelection() {
return this.network.getSelection();
},
getSelectedNodes() {
return this.network.getSelectedNodes();
},
getSelectedEdges() {
return this.network.getSelectedEdges();
},
getNodeAt(p) {
return this.network.getNodeAt(p);
},
getEdgeAt(p) {
return this.network.getEdgeAt(p);
},
selectNodes(nodeIds, highlightEdges) {
this.network.selectNodes(nodeIds, highlightEdges);
},
selectEdges(edgeIds) {
this.network.selectEdges(edgeIds);
},
setSelection(selection, options) {
this.network.setSelection(selection, options);
},
unselectAll() {
this.network.unselectAll();
},
getScale() {
return this.network.getScale();
},
getViewPosition() {
return this.network.getViewPosition();
},
fit(options) {
this.network.fit(options);
},
focus(nodeId, options) {
this.network.focus(nodeId, options);
},
moveTo(options) {
this.network.moveTo(options);
},
releaseNode() {
this.network.releaseNode();
},
getOptionsFromConfigurator() {
return this.network.getOptionsFromConfigurator();
}
},
created() {
// This should be a Vue data property, but Vue reactivity kinda bugs Vis.
// See here for more: https://github.com/almende/vis/issues/2524
this.network = null;
},
mounted() {
const container = this.$refs.visualization;
this.visData.nodes = mountVisData(this, 'nodes' /* DataSet, DataView */);
this.visData.edges = mountVisData(this, 'edges' /* , DataSet, DataView */);
this.network = new Network(container, this.visData, this.options);
this.events.forEach(eventName => this.network.on(eventName, props => this.$emit(translateEvent(eventName), props)));
},
beforeUnmount() {
this.network.destroy();
}
};
const _hoisted_1 = {
ref: "visualization"
};
function render(_ctx, _cache, $props, $setup, $data, $options) {
return openBlock(), createElementBlock("div", _hoisted_1, null, 512 /* NEED_PATCH */);
}
script.render = render;
function styleInject(css, ref) {
if (ref === void 0) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') {
return;
}
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var css_248z$1 = ".vis-time-axis{overflow:hidden;position:relative}.vis-time-axis.vis-foreground{left:0;top:0;width:100%}.vis-time-axis.vis-background{height:100%;left:0;position:absolute;top:0;width:100%}.vis-time-axis .vis-text{box-sizing:border-box;color:#4d4d4d;overflow:hidden;padding:3px;position:absolute;white-space:nowrap}.vis-time-axis .vis-text.vis-measure{margin-left:0;margin-right:0;padding-left:0;padding-right:0;position:absolute;visibility:hidden}.vis-time-axis .vis-grid.vis-vertical{border-left:1px solid;position:absolute}.vis-time-axis .vis-grid.vis-vertical-rtl{border-right:1px solid;position:absolute}.vis-time-axis .vis-grid.vis-minor{border-color:#e5e5e5}.vis-time-axis .vis-grid.vis-major{border-color:#bfbfbf}.vis .overlay{height:100%;left:0;position:absolute;top:0;width:100%;z-index:10}.vis-active{box-shadow:0 0 10px #86d5f8}.vis-custom-time{background-color:#6e94ff;cursor:move;width:2px;z-index:1}.vis-custom-time>.vis-custom-time-marker{background-color:inherit;color:#fff;cursor:auto;font-size:12px;padding:3px 5px;top:0;white-space:nowrap;z-index:inherit}.vis-current-time{background-color:#ff7f6e;pointer-events:none;width:2px;z-index:1}.vis-rolling-mode-btn{background:#3876c2;border-radius:50%;color:#fff;cursor:pointer;font-size:28px;font-weight:700;height:40px;opacity:.8;position:absolute;right:20px;text-align:center;top:7px;width:40px}.vis-rolling-mode-btn:before{content:\"\\26F6\"}.vis-rolling-mode-btn:hover{opacity:1}.vis-panel{box-sizing:border-box;margin:0;padding:0;position:absolute}.vis-panel.vis-bottom,.vis-panel.vis-center,.vis-panel.vis-left,.vis-panel.vis-right,.vis-panel.vis-top{border:1px #bfbfbf}.vis-panel.vis-center,.vis-panel.vis-left,.vis-panel.vis-right{border-bottom-style:solid;border-top-style:solid;overflow:hidden}.vis-left.vis-panel.vis-vertical-scroll,.vis-right.vis-panel.vis-vertical-scroll{height:100%;overflow-x:hidden;overflow-y:scroll}.vis-left.vis-panel.vis-vertical-scroll{direction:rtl}.vis-left.vis-panel.vis-vertical-scroll .vis-content,.vis-right.vis-panel.vis-vertical-scroll{direction:ltr}.vis-right.vis-panel.vis-vertical-scroll .vis-content{direction:rtl}.vis-panel.vis-bottom,.vis-panel.vis-center,.vis-panel.vis-top{border-left-style:solid;border-right-style:solid}.vis-background{overflow:hidden}.vis-panel>.vis-content{position:relative}.vis-panel .vis-shadow{box-shadow:0 0 10px rgba(0,0,0,.8);height:1px;position:absolute;width:100%}.vis-panel .vis-shadow.vis-top{left:0;top:-1px}.vis-panel .vis-shadow.vis-bottom{bottom:-1px;left:0}.vis-graph-group0{fill:#4f81bd;fill-opacity:0;stroke-width:2px;stroke:#4f81bd}.vis-graph-group1{fill:#f79646;fill-opacity:0;stroke-width:2px;stroke:#f79646}.vis-graph-group2{fill:#8c51cf;fill-opacity:0;stroke-width:2px;stroke:#8c51cf}.vis-graph-group3{fill:#75c841;fill-opacity:0;stroke-width:2px;stroke:#75c841}.vis-graph-group4{fill:#ff0100;fill-opacity:0;stroke-width:2px;stroke:#ff0100}.vis-graph-group5{fill:#37d8e6;fill-opacity:0;stroke-width:2px;stroke:#37d8e6}.vis-graph-group6{fill:#042662;fill-opacity:0;stroke-width:2px;stroke:#042662}.vis-graph-group7{fill:#00ff26;fill-opacity:0;stroke-width:2px;stroke:#00ff26}.vis-graph-group8{fill:#f0f;fill-opacity:0;stroke-width:2px;stroke:#f0f}.vis-graph-group9{fill:#8f3938;fill-opacity:0;stroke-width:2px;stroke:#8f3938}.vis-timeline .vis-fill{fill-opacity:.1;stroke:none}.vis-timeline .vis-bar{fill-opacity:.5;stroke-width:1px}.vis-timeline .vis-point{stroke-width:2px;fill-opacity:1}.vis-timeline .vis-legend-background{stroke-width:1px;fill-opacity:.9;fill:#fff;stroke:#c2c2c2}.vis-timeline .vis-outline{stroke-width:1px;fill-opacity:1;fill:#fff;stroke:#e5e5e5}.vis-timeline .vis-icon-fill{fill-opacity:.3;stroke:none}.vis-timeline{border:1px solid #bfbfbf;box-sizing:border-box;margin:0;overflow:hidden;padding:0;position:relative}.vis-loading-screen{height:100%;left:0;position:absolute;top:0;width:100%}.vis [class*=span]{min-height:0;width:auto}.vis-item{background-color:#d5ddf6;border-color:#97b0f8;border-width:1px;color:#1a1a1a;display:inline-block;position:absolute;z-index:1}.vis-item.vis-selected{background-color:#fff785;border-color:#ffc200;z-index:2}.vis-editable.vis-selected{cursor:move}.vis-item.vis-point.vis-selected{background-color:#fff785}.vis-item.vis-box{border-radius:2px;border-style:solid;text-align:center}.vis-item.vis-point{background:none}.vis-item.vis-dot{border-radius:4px;border-style:solid;border-width:4px;padding:0;position:absolute}.vis-item.vis-range{border-radius:2px;border-style:solid;box-sizing:border-box}.vis-item.vis-background{background-color:rgba(213,221,246,.4);border:none;box-sizing:border-box;margin:0;padding:0}.vis-item .vis-item-overflow{height:100%;margin:0;overflow:hidden;padding:0;position:relative;width:100%}.vis-item-visible-frame{white-space:nowrap}.vis-item.vis-range .vis-item-content{display:inline-block;position:relative}.vis-item.vis-background .vis-item-content{display:inline-block;position:absolute}.vis-item.vis-line{border-left-style:solid;border-left-width:1px;padding:0;position:absolute;width:0}.vis-item .vis-item-content{box-sizing:border-box;padding:5px;white-space:nowrap}.vis-item .vis-onUpdateTime-tooltip{background:#4f81bd;border-radius:1px;color:#fff;padding:5px;position:absolute;text-align:center;transition:.4s;-o-transition:.4s;-moz-transition:.4s;-webkit-transition:.4s;white-space:nowrap;width:200px}.vis-item .vis-delete,.vis-item .vis-delete-rtl{box-sizing:border-box;cursor:pointer;height:24px;padding:0 5px;position:absolute;top:0;transition:background .2s linear;width:24px}.vis-item .vis-delete{right:-24px}.vis-item .vis-delete-rtl{left:-24px}.vis-item .vis-delete-rtl:after,.vis-item .vis-delete:after{color:red;content:\"\\00D7\";font-family:arial,sans-serif;font-size:22px;font-weight:700;transition:color .2s linear}.vis-item .vis-delete-rtl:hover,.vis-item .vis-delete:hover{background:red}.vis-item .vis-delete-rtl:hover:after,.vis-item .vis-delete:hover:after{color:#fff}.vis-item .vis-drag-center{cursor:move;height:100%;left:0;position:absolute;top:0;width:100%}.vis-item.vis-range .vis-drag-left{cursor:w-resize;left:-4px}.vis-item.vis-range .vis-drag-left,.vis-item.vis-range .vis-drag-right{height:100%;max-width:20%;min-width:2px;position:absolute;top:0;width:24px}.vis-item.vis-range .vis-drag-right{cursor:e-resize;right:-4px}.vis-range.vis-item.vis-readonly .vis-drag-left,.vis-range.vis-item.vis-readonly .vis-drag-right{cursor:auto}.vis-item.vis-cluster{border-radius:2px;border-style:solid;text-align:center;vertical-align:center}.vis-item.vis-cluster-line{border-left-style:solid;border-left-width:1px;padding:0;position:absolute;width:0}.vis-item.vis-cluster-dot{border-radius:4px;border-style:solid;border-width:4px;padding:0;position:absolute}div.vis-tooltip{background-color:#f5f4ed;border:1px solid #808074;border-radius:3px;box-shadow:3px 3px 10px rgba(0,0,0,.2);color:#000;font-family:verdana;font-size:14px;padding:5px;pointer-events:none;position:absolute;visibility:hidden;white-space:nowrap;z-index:5}.vis-itemset{box-sizing:border-box;margin:0;padding:0;position:relative}.vis-itemset .vis-background,.vis-itemset .vis-foreground{height:100%;overflow:visible;position:absolute;width:100%}.vis-axis{height:0;left:0;position:absolute;width:100%;z-index:1}.vis-foreground .vis-group{border-bottom:1px solid #bfbfbf;box-sizing:border-box;position:relative}.vis-foreground .vis-group:last-child{border-bottom:none}.vis-nesting-group{cursor:pointer}.vis-label.vis-nested-group.vis-group-level-unknown-but-gte1{background:#f5f5f5}.vis-label.vis-nested-group.vis-group-level-0{background-color:#fff}.vis-ltr .vis-label.vis-nested-group.vis-group-level-0 .vis-inner{padding-left:0}.vis-rtl .vis-label.vis-nested-group.vis-group-level-0 .vis-inner{padding-right:0}.vis-label.vis-nested-group.vis-group-level-1{background-color:rgba(0,0,0,.05)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-1 .vis-inner{padding-left:15px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-1 .vis-inner{padding-right:15px}.vis-label.vis-nested-group.vis-group-level-2{background-color:rgba(0,0,0,.1)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-2 .vis-inner{padding-left:30px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-2 .vis-inner{padding-right:30px}.vis-label.vis-nested-group.vis-group-level-3{background-color:rgba(0,0,0,.15)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-3 .vis-inner{padding-left:45px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-3 .vis-inner{padding-right:45px}.vis-label.vis-nested-group.vis-group-level-4{background-color:rgba(0,0,0,.2)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-4 .vis-inner{padding-left:60px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-4 .vis-inner{padding-right:60px}.vis-label.vis-nested-group.vis-group-level-5{background-color:rgba(0,0,0,.25)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-5 .vis-inner{padding-left:75px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-5 .vis-inner{padding-right:75px}.vis-label.vis-nested-group.vis-group-level-6{background-color:rgba(0,0,0,.3)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-6 .vis-inner{padding-left:90px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-6 .vis-inner{padding-right:90px}.vis-label.vis-nested-group.vis-group-level-7{background-color:rgba(0,0,0,.35)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-7 .vis-inner{padding-left:105px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-7 .vis-inner{padding-right:105px}.vis-label.vis-nested-group.vis-group-level-8{background-color:rgba(0,0,0,.4)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-8 .vis-inner{padding-left:120px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-8 .vis-inner{padding-right:120px}.vis-label.vis-nested-group.vis-group-level-9{background-color:rgba(0,0,0,.45)}.vis-ltr .vis-label.vis-nested-group.vis-group-level-9 .vis-inner{padding-left:135px}.vis-rtl .vis-label.vis-nested-group.vis-group-level-9 .vis-inner{padding-right:135px}.vis-label.vis-nested-group{background-color:rgba(0,0,0,.5)}.vis-ltr .vis-label.vis-nested-group .vis-inner{padding-left:150px}.vis-rtl .vis-label.vis-nested-group .vis-inner{padding-right:150px}.vis-group-level-unknown-but-gte1{border:1px solid red}.vis-label.vis-nesting-group:before{display:inline-block;width:15px}.vis-label.vis-nesting-group.expanded:before{content:\"\\25BC\"}.vis-label.vis-nesting-group.collapsed:before{content:\"\\25B6\"}.vis-rtl .vis-label.vis-nesting-group.collapsed:before{content:\"\\25C0\"}.vis-ltr .vis-label:not(.vis-nesting-group):not(.vis-group-level-0){padding-left:15px}.vis-rtl .vis-label:not(.vis-nesting-group):not(.vis-group-level-0){padding-right:15px}.vis-overlay{height:100%;left:0;position:absolute;top:0;width:100%;z-index:10}.vis-labelset{overflow:hidden}.vis-labelset,.vis-labelset .vis-label{box-sizing:border-box;position:relative}.vis-labelset .vis-label{border-bottom:1px solid #bfbfbf;color:#4d4d4d;left:0;top:0;width:100%}.vis-labelset .vis-label.draggable{cursor:pointer}.vis-group-is-dragging{background:rgba(0,0,0,.1)}.vis-labelset .vis-label:last-child{border-bottom:none}.vis-labelset .vis-label .vis-inner{display:inline-block;padding:5px}.vis-labelset .vis-label .vis-inner.vis-hidden{padding:0}div.vis-configuration{display:block;float:left;font-size:12px;position:relative}div.vis-configuration-wrapper{display:block;width:700px}div.vis-configuration-wrapper:after{clear:both;content:\"\";display:block}div.vis-configuration.vis-config-option-container{background-color:#fff;border:2px solid #f7f8fa;border-radius:4px;display:block;left:10px;margin-top:20px;padding-left:5px;width:495px}div.vis-configuration.vis-config-button{background-color:#f7f8fa;border:2px solid #ceced0;border-radius:4px;cursor:pointer;display:block;height:25px;left:10px;line-height:25px;margin-bottom:30px;margin-top:20px;padding-left:5px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-button.hover{background-color:#4588e6;border:2px solid #214373;color:#fff}div.vis-configuration.vis-config-item{display:block;float:left;height:25px;line-height:25px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-item.vis-config-s2{background-color:#f7f8fa;border-radius:3px;left:10px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s3{background-color:#e4e9f0;border-radius:3px;left:20px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s4{background-color:#cfd8e6;border-radius:3px;left:30px;padding-left:5px}div.vis-configuration.vis-config-header{font-size:18px;font-weight:700}div.vis-configuration.vis-config-label{height:25px;line-height:25px;width:120px}div.vis-configuration.vis-config-label.vis-config-s3{width:110px}div.vis-configuration.vis-config-label.vis-config-s4{width:100px}div.vis-configuration.vis-config-colorBlock{border:1px solid #444;border-radius:2px;cursor:pointer;height:19px;margin:0;padding:0;top:1px;width:30px}input.vis-configuration.vis-config-checkbox{left:-5px}input.vis-configuration.vis-config-rangeinput{margin:0;padding:1px;pointer-events:none;position:relative;top:-5px;width:60px}input.vis-configuration.vis-config-range{-webkit-appearance:none;background-color:transparent;border:0 solid #fff;height:20px;width:300px}input.vis-configuration.vis-config-range::-webkit-slider-runnable-track{background:#dedede;background:linear-gradient(180deg,#dedede 0,#c8c8c8 99%);border:1px solid #999;border-radius:3px;box-shadow:0 0 3px 0 #aaa;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#dedede\",endColorstr=\"#c8c8c8\",GradientType=0);height:5px;width:300px}input.vis-configuration.vis-config-range::-webkit-slider-thumb{-webkit-appearance:none;background:#3876c2;background:linear-gradient(180deg,#3876c2 0,#385380);border:1px solid #14334b;border-radius:50%;box-shadow:0 0 1px 0 #111927;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#3876c2\",endColorstr=\"#385380\",GradientType=0);height:17px;margin-top:-7px;width:17px}input.vis-configuration.vis-config-range:focus{outline:none}input.vis-configuration.vis-config-range:focus::-webkit-slider-runnable-track{background:#9d9d9d;background:linear-gradient(180deg,#9d9d9d 0,#c8c8c8 99%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#9d9d9d\",endColorstr=\"#c8c8c8\",GradientType=0)}input.vis-configuration.vis-config-range::-moz-range-track{background:#dedede;background:linear-gradient(180deg,#dedede 0,#c8c8c8 99%);border:1px solid #999;border-radius:3px;box-shadow:0 0 3px 0 #aaa;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#dedede\",endColorstr=\"#c8c8c8\",GradientType=0);height:10px;width:300px}input.vis-configuration.vis-config-range::-moz-range-thumb{background:#385380;border:none;border-radius:50%;height:16px;width:16px}input.vis-configuration.vis-config-range:-moz-focusring{outline:1px solid #fff;outline-offset:-1px}input.vis-configuration.vis-config-range::-ms-track{background:transparent;border-color:transparent;border-width:6px 0;color:transparent;height:5px;width:300px}input.vis-configuration.vis-config-range::-ms-fill-lower{background:#777;border-radius:10px}input.vis-configuration.vis-config-range::-ms-fill-upper{background:#ddd;border-radius:10px}input.vis-configuration.vis-config-range::-ms-thumb{background:#385380;border:none;border-radius:50%;height:16px;width:16px}input.vis-configuration.vis-config-range:focus::-ms-fill-lower{background:#888}input.vis-configuration.vis-config-range:focus::-ms-fill-upper{background:#ccc}.vis-configuration-popup{background:rgba(57,76,89,.85);border:2px solid #f2faff;border-radius:4px;color:#fff;font-size:14px;height:30px;line-height:30px;position:absolute;text-align:center;transition:opacity .3s ease-in-out;width:150px}.vis-configuration-popup:after,.vis-configuration-popup:before{border:solid transparent;content:\" \";height:0;left:100%;pointer-events:none;position:absolute;top:50%;width:0}.vis-configuration-popup:after{border-color:rgba(136,183,213,0) rgba(136,183,213,0) rgba(136,183,213,0) rgba(57,76,89,.85);border-width:8px;margin-top:-8px}.vis-configuration-popup:before{border-color:rgba(194,225,245,0) rgba(194,225,245,0) rgba(194,225,245,0) #f2faff;border-width:12px;margin-top:-12px}.vis-panel.vis-background.vis-horizontal .vis-grid.vis-horizontal{border-bottom:1px solid;height:0;position:absolute;width:100%}.vis-panel.vis-background.vis-horizontal .vis-grid.vis-minor{border-color:#e5e5e5}.vis-panel.vis-background.vis-horizontal .vis-grid.vis-major{border-color:#bfbfbf}.vis-data-axis .vis-y-axis.vis-major{color:#4d4d4d;position:absolute;white-space:nowrap;width:100%}.vis-data-axis .vis-y-axis.vis-major.vis-measure{border:0;margin:0;padding:0;visibility:hidden;width:auto}.vis-data-axis .vis-y-axis.vis-minor{color:#bebebe;position:absolute;white-space:nowrap;width:100%}.vis-data-axis .vis-y-axis.vis-minor.vis-measure{border:0;margin:0;padding:0;visibility:hidden;width:auto}.vis-data-axis .vis-y-axis.vis-title{bottom:20px;color:#4d4d4d;position:absolute;text-align:center;white-space:nowrap}.vis-data-axis .vis-y-axis.vis-title.vis-measure{margin:0;padding:0;visibility:hidden;width:auto}.vis-data-axis .vis-y-axis.vis-title.vis-left{bottom:0;transform:rotate(-90deg);transform-origin:left bottom}.vis-data-axis .vis-y-axis.vis-title.vis-right{bottom:0;transform:rotate(90deg);transform-origin:right bottom}.vis-legend{background-color:rgba(247,252,255,.65);border:1px solid #b3b3b3;box-shadow:2px 2px 10px hsla(0,0%,60%,.55);padding:5px}.vis-legend-text{display:inline-block;white-space:nowrap}";
styleInject(css_248z$1);
var css_248z = ".vis-overlay{bottom:0;left:0;position:absolute;right:0;top:0;z-index:10}.vis-active{box-shadow:0 0 10px #86d5f8}.vis [class*=span]{min-height:0;width:auto}div.vis-color-picker{background-color:#fff;border-radius:15px;box-shadow:0 0 10px 0 rgba(0,0,0,.5);display:none;height:444px;left:30px;margin-left:30px;margin-top:-140px;padding:10px;position:absolute;top:0;width:310px;z-index:1}div.vis-color-picker div.vis-arrow{left:5px;position:absolute;top:147px}div.vis-color-picker div.vis-arrow:after,div.vis-color-picker div.vis-arrow:before{border:solid transparent;content:\" \";height:0;pointer-events:none;position:absolute;right:100%;top:50%;width:0}div.vis-color-picker div.vis-arrow:after{border-color:hsla(0,0%,100%,0) #fff hsla(0,0%,100%,0) hsla(0,0%,100%,0);border-width:30px;margin-top:-30px}div.vis-color-picker div.vis-color{cursor:pointer;height:289px;position:absolute;width:289px}div.vis-color-picker div.vis-brightness{position:absolute;top:313px}div.vis-color-picker div.vis-opacity{position:absolute;top:350px}div.vis-color-picker div.vis-selector{background:#4c4c4c;background:linear-gradient(180deg,#4c4c4c 0,#595959 12%,#666 25%,#474747 39%,#2c2c2c 50%,#000 51%,#111 60%,#2b2b2b 76%,#1c1c1c 91%,#131313);border:1px solid #fff;border-radius:15px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#4c4c4c\",endColorstr=\"#131313\",GradientType=0);height:15px;left:137px;position:absolute;top:137px;width:15px}div.vis-color-picker div.vis-new-color{left:159px;padding-right:2px;text-align:right}div.vis-color-picker div.vis-initial-color,div.vis-color-picker div.vis-new-color{border:1px solid rgba(0,0,0,.1);border-radius:5px;color:rgba(0,0,0,.4);font-size:10px;height:20px;line-height:20px;position:absolute;top:380px;vertical-align:middle;width:140px}div.vis-color-picker div.vis-initial-color{left:10px;padding-left:2px;text-align:left}div.vis-color-picker div.vis-label{left:10px;position:absolute;width:300px}div.vis-color-picker div.vis-label.vis-brightness{top:300px}div.vis-color-picker div.vis-label.vis-opacity{top:338px}div.vis-color-picker div.vis-button{background-color:#f7f7f7;border:2px solid #d9d9d9;border-radius:10px;cursor:pointer;height:25px;line-height:25px;position:absolute;text-align:center;top:410px;vertical-align:middle;width:68px}div.vis-color-picker div.vis-button.vis-cancel{left:5px}div.vis-color-picker div.vis-button.vis-load{left:82px}div.vis-color-picker div.vis-button.vis-apply{left:159px}div.vis-color-picker div.vis-button.vis-save{left:236px}div.vis-color-picker input.vis-range{height:20px;width:290px}div.vis-configuration{display:block;float:left;font-size:12px;position:relative}div.vis-configuration-wrapper{display:block;width:700px}div.vis-configuration-wrapper:after{clear:both;content:\"\";display:block}div.vis-configuration.vis-config-option-container{background-color:#fff;border:2px solid #f7f8fa;border-radius:4px;display:block;left:10px;margin-top:20px;padding-left:5px;width:495px}div.vis-configuration.vis-config-button{background-color:#f7f8fa;border:2px solid #ceced0;border-radius:4px;cursor:pointer;display:block;height:25px;left:10px;line-height:25px;margin-bottom:30px;margin-top:20px;padding-left:5px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-button.hover{background-color:#4588e6;border:2px solid #214373;color:#fff}div.vis-configuration.vis-config-item{display:block;float:left;height:25px;line-height:25px;vertical-align:middle;width:495px}div.vis-configuration.vis-config-item.vis-config-s2{background-color:#f7f8fa;border-radius:3px;left:10px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s3{background-color:#e4e9f0;border-radius:3px;left:20px;padding-left:5px}div.vis-configuration.vis-config-item.vis-config-s4{background-color:#cfd8e6;border-radius:3px;left:30px;padding-left:5px}div.vis-configuration.vis-config-header{font-size:18px;font-weight:700}div.vis-configuration.vis-config-label{height:25px;line-height:25px;width:120px}div.vis-configuration.vis-config-label.vis-config-s3{width:110px}div.vis-configuration.vis-config-label.vis-config-s4{width:100px}div.vis-configuration.vis-config-colorBlock{border:1px solid #444;border-radius:2px;cursor:pointer;height:19px;margin:0;padding:0;top:1px;width:30px}input.vis-configuration.vis-config-checkbox{left:-5px}input.vis-configuration.vis-config-rangeinput{margin:0;padding:1px;pointer-events:none;position:relative;top:-5px;width:60px}input.vis-configuration.vis-config-range{-webkit-appearance:none;background-color:transparent;border:0 solid #fff;height:20px;width:300px}input.vis-configuration.vis-config-range::-webkit-slider-runnable-track{background:#dedede;background:linear-gradient(180deg,#dedede 0,#c8c8c8 99%);border:1px solid #999;border-radius:3px;box-shadow:0 0 3px 0 #aaa;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#dedede\",endColorstr=\"#c8c8c8\",GradientType=0);height:5px;width:300px}input.vis-configuration.vis-config-range::-webkit-slider-thumb{-webkit-appearance:none;background:#3876c2;background:linear-gradient(180deg,#3876c2 0,#385380);border:1px solid #14334b;border-radius:50%;box-shadow:0 0 1px 0 #111927;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#3876c2\",endColorstr=\"#385380\",GradientType=0);height:17px;margin-top:-7px;width:17px}input.vis-configuration.vis-config-range:focus{outline:none}input.vis-configuration.vis-config-range:focus::-webkit-slider-runnable-track{background:#9d9d9d;background:linear-gradient(180deg,#9d9d9d 0,#c8c8c8 99%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#9d9d9d\",endColorstr=\"#c8c8c8\",GradientType=0)}input.vis-configuration.vis-config-range::-moz-range-track{background:#dedede;background:linear-gradient(180deg,#dedede 0,#c8c8c8 99%);border:1px solid #999;border-radius:3px;box-shadow:0 0 3px 0 #aaa;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#dedede\",endColorstr=\"#c8c8c8\",GradientType=0);height:10px;width:300px}input.vis-configuration.vis-config-range::-moz-range-thumb{background:#385380;border:none;border-radius:50%;height:16px;width:16px}input.vis-configuration.vis-config-range:-moz-focusring{outline:1px solid #fff;outline-offset:-1px}input.vis-configuration.vis-config-range::-ms-track{background:transparent;border-color:transparent;border-width:6px 0;color:transparent;height:5px;width:300px}input.vis-configuration.vis-config-range::-ms-fill-lower{background:#777;border-radius:10px}input.vis-configuration.vis-config-range::-ms-fill-upper{background:#ddd;border-radius:10px}input.vis-configuration.vis-config-range::-ms-thumb{background:#385380;border:none;border-radius:50%;height:16px;width:16px}input.vis-configuration.vis-config-range:focus::-ms-fill-lower{background:#888}input.vis-configuration.vis-config-range:focus::-ms-fill-upper{background:#ccc}.vis-configuration-popup{background:rgba(57,76,89,.85);border:2px solid #f2faff;border-radius:4px;color:#fff;font-size:14px;height:30px;line-height:30px;position:absolute;text-align:center;transition:opacity .3s ease-in-out;width:150px}.vis-configuration-popup:after,.vis-configuration-popup:before{border:solid transparent;content:\" \";height:0;left:100%;pointer-events:none;position:absolute;top:50%;width:0}.vis-configuration-popup:after{border-color:rgba(136,183,213,0) rgba(136,183,213,0) rgba(136,183,213,0) rgba(57,76,89,.85);border-width:8px;margin-top:-8px}.vis-configuration-popup:before{border-color:rgba(194,225,245,0) rgba(194,225,245,0) rgba(194,225,245,0) #f2faff;border-width:12px;margin-top:-12px}div.vis-tooltip{background-color:#f5f4ed;border:1px solid #808074;border-radius:3px;box-shadow:3px 3px 10px rgba(0,0,0,.2);color:#000;font-family:verdana;font-size:14px;padding:5px;pointer-events:none;position:absolute;visibility:hidden;white-space:nowrap;z-index:5}div.vis-network div.vis-navigation div.vis-button{-webkit-touch-callout:none;background-position:2px 2px;background-repeat:no-repeat;border-radius:17px;cursor:pointer;display:inline-block;height:34px;position:absolute;-ms-user-select:none;user-select:none;width:34px}div.vis-network div.vis-navigation div.vis-button:hover{box-shadow:0 0 3px 3px rgba(56,207,21,.3)}div.vis-network div.vis-navigation div.vis-button:active{box-shadow:0 0 1px 3px rgba(56,207,21,.95)}div.vis-network div.vis-navigation div.vis-button.vis-up{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGo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sKK0GAibEua9spANh4aY2VmcEg+DEkiBgR/L2hYFgGtcErkQQAMVJgBxyy9hboZzv32v+Kpr7qbEECTAIMAoaJa3qPTmNiiAAgJAjk6J5xhu6HDAIgQYGLmI29PocmMcI8MNYvT1ckfzD9H/ub5br4e4Me9WfOKqtyX6Ud2cwC449PRamifDm6Auc0rTXokci+Xo1EAgBckiDuYGLjpTvntcGIA+SFcp6uUAaAI879VhWrRteYAqn/edq758brXJ1327QMhgJcZjA3EBjNrgZjOG1PkAjyTGENMjZPq5ECQ0MDE9ERBqFZrk0OJ3i4x/7vyIjBxGERt3takgVJEAp9xq3f769WiPDNvSsJdT3HDOEASPelmoBRYT3Kzt5uMtwauJEgSOCpwrk1DIJCoNUMwj9v7MweP9XSQ8/hJPp496fZTAICvLqcyv2B7nRbrgCA03JN5h8ub7A8VqpB437xHvsOy3l3cyaB4L2uqxhti1WLMcSgZQCw7+bOooO3Pk4JBZIYYXISMV5sKH59UePM10GESRGpIf/bE92HU452HywSJIGIllctrhp6YAK5+fHds0lLtJFMXNwkV6fFqA29mROefqiMJj1h6um4a5vY/92dKGaBxIhU5zJTWW2cJmEgGOmeb3c8FxAfb9mdf2RzyGGv5MvU7QwuEySwKHFp/c/M71zA/2F7b1RajnYdLAqMukMVu2YcfmDYE2MD7H+7/Xlq6cRIJqm4zXM+qd3TGjVBir43KSLlXjiELe5TsX+3/yW/ST45PaAHbKmccWh12AP93JNZywj0kSABIobpiXRHjtZ6faout2tyZMadGLXBCxBcvl6NfaAz+tKdFmObpzWl2+tIIBACYy0t/yj34M7HvsKUK+CGassvicX7alYDwwq+vykIEqPVa+Q9gdYk5+V+UE7lj3+FGbuBM/X5JUT8QwIVSSSZiTgmoFR2MfiqYFFPfjpkyrfWPopwxP47AP1pK1g9/dqeAAAAAElFTkSuQmCC\");bottom:50px;left:55px}div.vis-network div.vis-navigation div.vis-button.vis-down{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA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bbvYHJhlTGp6O+JVHb0/2HJtX1PH+aqECqG/5YN1nlXcokGvvO6vCc4x+QskotxVHB/qa+xbOWuzw8NB3nuo+Ht0z2hHsuGU3GrWAoZfi3jrxgHpw3BPpobaCH7vbqOw6mHI836vYW3Eqcq9AtioqbJy7ufQ3lhfu8sR+s9+3vL8klACsQSu7AnxMY1MxH7YXJp7oPpLulrrj+9575Ni2aeVt1teWfEWfHQLCaspseHzOU7VWU+aM5G2NoyL4i+6j8XWDNQsmGsKu/cv+nTtjQb/mm7hfENyvqEAK5v8opjPJaL26KGBpd5TfguuBvuZRgBgY6zO0jlyZXXe9JqR+8MK8ntHOMHfHIkhu2b/0yIH7/oXJ0yFlxYnPUdRbvuILgO7+y+91l6Ka6M+cnCf4fMSypXvymHf/vzBTD3CuNGUFKT8lmK5Rs5ASqKiBlAGBXFaiSuni0fkp1pJ7Ed4e/xsAqLk46EWsG1EAAAAASUVORK5CYII=\");bottom:10px;left:55px}div.vis-network div.vis-navigation div.vis-button.vis-left{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5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XOaQc+uONfmCwZXJIf8xKx2KRgxYgOS+CROuyoyQKCxIhkOr4T6JWgxGnvZ1HWnf/CfHcBXxcnpRHxYwRKkUjSErFKkAQiNjP4kmBRTHbKm5KkKxwL+K39fwDX1XGF8ct++QAAAABJRU5ErkJggg==\");bottom:10px;left:15px}div.vis-network div.vis-navigation div.vis-button.vis-right{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQ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B5u2hf5z+6TMexYji+tVdrM5leMbWOtSwQx/F1C2rcuebIqwSO568a4WmuN3mEYSiUi+pRl2l1pLvYBsKArUKVwnZRYgdHpMWVG4+/WXhwoDBXE7OmkHzJ6JNemLfv51bniGqzVPoIkyLbpfK7ZMFIkE6FlrMn7Ql+BbiHg+zXGbgLjylDpyosD58KZmKM0cfWHI9//aD5o1VCZrnO83VuQQOja5PMCfwK8n3K2ChIbLVOD9KB36le3A+u/s2Q81C2yRavQmQNdVnamLnmq4nHD9jpB0rwm77jpjTW9E906Bu18fWlWCQHAox9CtGoXTwmS8IThZyXPB+29inuoE6bMsDM9ufEAMNHqJuU8ljMtAKA2B7IhzaWNiLfWjVQb3J10/SGuEZZ7Af1X7+lluZ3HkpgEQPL291M+qbzJgXQcG60ypKlVTGwsMxcFaJW6/hDXVZZvCz3RlrmRiQHwy9nRn2bM6bnas4cLfH6s1RIorsJcFDA2PToR7Z7QezfQD9qzwvI6TyTZC47ttXeiT+2c1+wBgOndoTPLt7mrmCRjvfULQ4O1xsVVchu7b9GysYUAqy3lnsdNb0aXmQuj7PYWL2etuRl6S0OfXLjiGQIdEY6K5esc2BWhjvkqXLO6x08VPKxV6iYAwuBkv5NpvNmtbrhaX2+tWdY70eVNINhtLW0/sjrv6B0/YdJlcGlR2AvE4hUlKwHQ7BU5cz8LRx0HaPY7gXb53L/67+mUfudPmP/twOWS6AQi/j6B4iWS/IlYK+yGYJDB1wWLErLRKd/omOJbAWf03wEAyO9m+/TtS3AAAAAASUVORK5CYII=\");bottom:10px;left:95px}div.vis-network div.vis-navigation div.vis-button.vis-zoomIn{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVE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E31SBjmWPznHPjy+8NjdhYfeMmJl3EiNSRgCi/25fpGu4M671zjlrm685s2fEnUoQ5lrLLW8uPLj3oX9hqgxIw8n8X1LU7yMkItCHzREZrGQV6ONmy5TggHk247sL/1jFqof/hRn/AWfqC0pI+QHBIk3tICXRrFTpF8hlJaqefh6yFxQ6HwQYlK8HAKyt3WsWxl7fAAAAAElFTkSuQmCC\");bottom:10px;right:15px}div.vis-network div.vis-navigation div.vis-button.vis-zoomOut{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+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CtLqADqS76ev6/ilgrk2q6esxHZgf5CySh3FMcG+5jbE0ZNdj4odHdDwWPGcZNNO1MPbrxtzdW4s+tI5HPBwQTTzziKY3v/7HGlhmS23g90T+OO5L1Nu7MMw3Fv/Tx1f97/FnsAYPui8/D4nBB/oZZR230uoq67auQoLaB37Iio3sEAK52nR39p+zS13HFiilHeYtOOabdC71jQzz2R+ALBbcrjWNF+cfaUwLSrk4KmtsT4T+gK9jG7AKKjv93X1lcfUNNVaantropqddnDCcIoa7lk29S92+/5CpOvQ04VJ79KUe/7iI/Hh40U6c3PyuPjhmWKN8G8Fvnw1A/zmX/vV5h/T+CXstRMUp4kOFOjZiUlWBkFQYdALitRZXRzf3RqWumdgF79NQDBOa2V/iYSHAAAAABJRU5ErkJggg==\");bottom:10px;right:55px}div.vis-network div.vis-navigation div.vis-button.vis-zoomExtends{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/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oqJFCyLTZmeq4MB5f3BVADnbpcQkzStUQMAk0YKBPfzxlhA95NQQe43QBotBECAFFyZHo6dz6CKCizAPFPivzUWqxm2AqIgnwkFvZNn4uczGK3Hah7wpet98UZ85R8aKScIcXYEWpMLkx8fvleHpNjlAWtTsakQa0pVKGcJQqMGUqCHBvfdjp/gTP6xwFzg85PdyaH2J4SUowKiw3889e4KBACnT582W5uKTV2uusAdUFlgzBcFQoFGDT35HwW+82mhqaenxwwA4WtYfRNnUkMZUqsJpEkn8cXU5yktYw2JjsTCMQDwer0ekt6GhgZPUVGRd3fu7qjqdU9Mj7mlpcVD0tvS0uKxWCyVANB5rS3x8s3BFEUFgTTLtuZndQHLBMSfB6pyZtfqMDQ3NzfqTcJisficTqc3BI+8bxh9L8corarM3fnDoIT+rACAU/7m7MOfHbCEwQDQ2Njo6erqinqTOHfuXNjjiI23+ystZ8c7smmkWgVJcN++fRARfLDhlacEUqVEQ1nm77xPrHjSh/+Djo3WmN/s/6OHEOgIPr2h63tVuq5Dud1ukETWoK3zorkzTiiONn/TKlNM4lj24m+Pf13o2wOVHqGA5MsAXjKPrDaqnMvlQnjTzhy0Nlw0d5oI5p3yN62amrk+ve5B5+hXgb47WGX52+V3NgoFOvQKAGUkkTqcbZy5XC7XHYf4zEFr3aXU7jih5uidPPOtvsmzixZr8VMrHjBHddLsHj+Z9Fb/n9a1+T/JDaXey0IpEzEKkHnU8Jj79++PeEwSSimQRGP+Gz8j5DVFBVKQtjBj6JGlNt/D8Y+OpMdlTphiEqcB4tqtsVjfjUtLLkx0J/dOnjWPTg+lEARIEHwaQJVQIYggACC/qxi6rn8ZHL4XETSsf0MU1HOk/CFGYgAwskUqY5eBitRxzn7/a0V1EEBwdqkN6jPI7y4xPmHmC5unbWdQRMqP2d86qANOksU6gvmArNQRNClqABnQgYuK0krI+wCOAyH3DK/vqOXhaf3PAO7mIRjDNV25AAAAAElFTkSuQmCC\");bottom:50px;right:15px}div.vis-network div.vis-manipulation{background:#fff;background:linear-gradient(180deg,#fff 0,#fcfcfc 48%,#fafafa 50%,#fcfcfc);border:0 solid #d6d9d8;border-bottom:1px;box-sizing:content-box;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#ffffff\",endColorstr=\"#fcfcfc\",GradientType=0);height:28px;left:0;padding-top:4px;position:absolute;top:0;width:100%}div.vis-network button.vis-edit-mode,div.vis-network div.vis-edit-mode{height:30px;left:0;position:absolute;top:5px}div.vis-network button.vis-close{-webkit-touch-callout:none;background-color:transparent;background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiU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lsZT5zUkdCIElFQzYxOTY2LTIuMTwvcGhvdG9zaG9wOklDQ1Byb2ZpbGU+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjcyMDAwMC8xMDAwMDwvdGlmZjpYUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+NzIwMDAwLzEwMDAwPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjc8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+NzwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgIAo8P3hwYWNrZXQgZW5kPSJ3Ij8+cZUZMwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAAA2ElEQVR42gDLADT/AS0tLUQFBQUVFxcXtPHx8fPl5eUNCAgITCkpKesEHx8fGgYGBjH+/v4a+Pj4qgQEBFU6OjodMTExzwQUFBSvEBAQEfX19SD19fVqNDQ0CElJSd/9/f2vAwEBAfrn5+fkBwcHLRYWFgsXFxfz29vbo9LS0uwDDQ0NDfPz81orKysXIyMj+ODg4Avh4eEa/f391gMkJCRYPz8/KUhISOMCAgKh8fHxHRsbGx4UFBQQBDk5OeY7Ozv7CAgItPb29vMEBASaJSUlTQ0NDesDAEwpT0Ko8Ri2AAAAAElFTkSuQmCC\");background-position:20px 3px;background-repeat:no-repeat;border:none;cursor:pointer;height:30px;position:absolute;right:0;top:0;-ms-user-select:none;user-select:none;width:30px}div.vis-network button.vis-close:hover{opacity:.6}div.vis-network div.vis-edit-mode button.vis-button,div.vis-network div.vis-manipulation button.vis-button{-webkit-touch-callout:none;background-color:transparent;background-position:0 0;background-repeat:no-repeat;border:none;border-radius:15px;box-sizing:content-box;cursor:pointer;float:left;font-family:verdana;font-size:12px;height:24px;margin-left:10px;padding:0 8px;-ms-user-select:none;user-select:none}div.vis-network div.vis-manipulation button.vis-button:hover{box-shadow:1px 1px 8px rgba(0,0,0,.2)}div.vis-network div.vis-manipulation button.vis-button:active{box-shadow:1px 1px 8px rgba(0,0,0,.5)}div.vis-network div.vis-manipulation button.vis-button.vis-back{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTK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C9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5zaW9uPjI0PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz4jq1U/AAAAIGN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hbUZTdra2tL2pra8OJRGLHnTt3zkqS9K+huHU4EhHMZnMoGo0W5OIh7nK5jjLGKq1W69vDhw8rRqMxMjc3t2t5eXnX5ORklc/nM+fl5SWnpqa+0uv1K/n5+Ws6nW5NluXNd15e3ppOp1uz2WyzZ86cGQ0Gg6ZAIFCZzWZ/lYjokRDiuN/vt7W0tMw3NTUpbrd78P79++5gMFgRiUTKHj58WMYYQ3V19etTp05tq6Lp6Wkb5xxCiEfc7XZPM8a6FxcXTfX19a/1en2Gcy5qamreNjY2/qGq6joRZe12+9Tp06e3JY/FYgWPHz8+mhvr3/CWlpbk+vp6PmOseWVlBS6XS9GSJUkSdrs93NDQ8Oe+ffvC/8fJIyMjddFo9Esi6pVleVjT2m0A8Hq9zqGhIefnjoknT544A4GAM/eDbxMReFNTE0pKSpKqqsaI6Pj8/LxVVdWM3W6PfCr5xMTE1zllXS0uLn6aSqXAGxsbodPpoNfrn6uqCs75EUVRrJFIZMfevXsXdTrdxseIE4mEPDIyUu/3++tynd8yGo29RIR0Og26fv06ioqKwBgD5xzv3r27zBjrIyJIkgSHwzFZWVmp7NmzJ1ZaWpoAgGg0WqgoSvHMzIw1GAw6tvjhitFo7NPW5fv370Hd3d0oKCgA53zTQMvLy+VCiKuSJH0rSdLmztZytIWv5RPRD0T0Y3Fx8dzWfby6ugopHo//w4mcc8iyPMc5v5FOp7/PZrOdQohWInIC2C2EgBBigYi8Qoifs9lsv06nWyIiaFxagXg8jr8GAGxuIe7LBeWhAAAAAElFTkSuQmCC\")}div.vis-network div.vis-manipulation div.vis-none:hover{box-shadow:1px 1px 8px transparent;cursor:default}div.vis-network div.vis-manipulation div.vis-none:active{box-shadow:1px 1px 8px transparent}div.vis-network div.vis-manipulation div.vis-none{line-height:23px;padding:0}div.vis-network div.vis-manipulation div.notification{font-weight:700;margin:2px}div.vis-network div.vis-manipulation button.vis-button.vis-add{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34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ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz5WKqp9AAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAYXSURBVHjafFZtUFTXGX7e9z27sveuMCwYV8ElrA7YSFYHtJUPkaaI0aRqG8wP00zUzljDINNSA/2ROtpO24SxnahlxjYd7SSjmUkymcxYlDhQPzHGisEVp8HwYWCVVVgEsrsuLnL74+5uqTF9Z+7cO/d8PO95zvO851BlZSV0XQcAMDOYGQBARDhX3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ks3sycYMSEwGHNtWf5bkX5NkYCJBxUBXiGV0XHvosOt54Zey33j/K+8P33++vjnbiGJbbLE+J9SANAb6nJ2B79wcUwETAwQQ7fMjPzMvfP8ja87HUIKMOiaAqMZhrGmLdAy78eZrwwsTS0eObTs+IdtgVanxBUExqGbb5VzrIISGIoUXsmqbgEhJldCQWqRf27SvPAn/o8XmgLhZsUkR4ll37mhk3n94Z4OlzY/7NLcYZfm7o1z2zT4vsvUNSXqprBCkmiTFbPX90/fh8GIT2sf+zTPdDMf4dVnNg4z+E0ixsGeBs9jd5ViSgLHjCb/peaR+MD3d4/ZJg2llyuG2Vwy7QWAs8PNnn1f7vkGSGxAzE6mk+kxkx/p/4unffSCR0hAoL1EBCYiPNdWNcwkNQTCR7feWX6g+7f/A7I8rcw/U6UEe0Ndrhc/W7mtL9ztmqlSgstSS/zTJ28dalpOpkRryrwbhwBACgsLMWPGDOT4ll3qyeqAkJTdCF7P/CrUY/GkLL1rE+2hTbSH8+0Lb/WEuhzhyaA905blf9Vd/895WnZwLHrPevir/cvOB1oLYpTtLrm6oYGIMDExAaqtrUVKSgqYGSKCk0WHq5ikkWEWtNL0imv5qUW+RclLRjJsrhBAuH1/QL8R7HR4xy5nescuP23E6hOA6mLv+sb4uTw6Ogqqq6uDpmkQkcStorX4XRcM1FjZ+kvFFjCJKU1WpkNJJUqIMtX1RyLeX3JtQ0JRhmGYZ/L27duRnJycuFGISOJ9pqh5lrB6iYgqGOxRrOaa54DcZmKvkJxk8JHC9rKh+KVhOsD4+Dj+MwADIf8n5m4xGwAAAABJRU5ErkJggg==\")}div.vis-network div.vis-edit-mode button.vis-button.vis-edit,div.vis-network div.vis-manipulation button.vis-button.vis-edit{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUh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ICAgICAgICAgICAgPHN0UmVmOm9yaWdpbmFsRG9jdW1lbnRJRD54bXAuZGlkOjczQjYyQUFEOTE4M0UzMTE5NDhCRDEzRTJCRTc5OUExPC9zdFJlZjpvcmlnaW5hbERvY3VtZW50SUQ+CiAgICAgICAgIDwveG1wTU06RGVyaXZlZEZyb20+CiAgICAgICAgIDxwaG90b3Nob3A6Q29sb3JNb2RlPjM8L3Bob3Rvc2hvcDpDb2xvck1vZGU+CiAgICAgICAgIDxwaG90b3Nob3A6SUNDUHJvZmlsZT5zUkdCIElFQzYxOTY2LTIuMTwvcGhvdG9zaG9wOklDQ1Byb2ZpbGU+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjcyMDA5MC8xMDAwMDwvdGlmZjpYUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+NzIwMDkwLzEwMDAwPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjI0PC9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5zaW9uPjI0PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz4ykninAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAYpSURBVHjafFZtTFvnFX7Oea+NudiY2Hwam4CBlgQwXdKREDKUoYg0jbRJ29RJ2VZ1mjRFUxSpA3VTfkzJfkQbS7spU6rtx5Z2UtppScjaHxvLuiatWi2jLEoMIUDCh23g2gbj7+tPuPvhOurawPl1dc99n+c55z33fV46ceIEZFkGADAziAgAQERoe/9ZK4GPM/AcgbsIXAcABCgMvkfAqAa89eDoJyF8LogIqqqChoaGYDAYHr8kItS8uc8iIH6iAa9IkAo5EAQX8pqmgUVBCBggYFgDhv0/GA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DsEoStLkR/768ummsaJG9Pb9oe+9J+xaeSVokiQDSJphAo5uaBuWjiKP4QTqS1cUWU7ayesN66wu22frD1vmVW6GW6T8u9eVjGyZzs+w78Nqu0a2mbvVu1KEJQAgeZRL0liQYyx+GOmKeQpu0rMYsAJPNEFGD2dLodLIy6c9Ys7G8yeSUl3tf2/X3rcBVJSOv34l3sCBogi7z1LH/rBHjl4IJ93/ncQFAnjeImJD0Z8zuCwu9q3djDXqTlAKID5xv+9t2R8n8VcUFBljQ8Gyfe40BYBM4DwDLt8Kue79ZcFkbzfEdbUbv+oN4c9KTtsfm1MbYQqqh+2zrVZYKs/7Ef+byimt1POYiJhDhPBFBIiIEXhxfs7/dfYoIF+auBfYTE/pebx/V8hqBP2ODvD34yvuh/WCAmU75Bx6sIgaI/v5+6PV6JLqUsYr7dpDAoehs0h73pHTWrvKgThYbRSt9UmSjef3MpaUvBz4O72UmADgTOPJguGiZor+/HyUlJWBmJFz+D8xTtlUiOpbwpmrmrweeSXrT+g11k4SBN3RGKUcAVCVdFhyP1nreDbY//NPyEXUlU/Pp4XYycGT6V0Ux2WwWdO7cOZSWlkII8diX7SPPNgDaKdbxoNAxwATBAEkEEgSWCEQAqPAMwqvMdCEwMO0tVqZpWsGTT58+DaPR+PhGIYQAAAgh0P7B3ioW/B0iGiCGiwXbCuOHFSJys6AbYFye2T+xWhT3WYJEIoH/DQBMw3kes8OJPgAAAABJRU5ErkJggg==\")}div.vis-network div.vis-edit-mode button.vis-button.vis-edit.vis-edit-mode{background-color:#fcfcfc;border:1px solid #ccc}div.vis-network div.vis-manipulation button.vis-button.vis-connect{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEs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nRJRD54bXAuZGlkOjczQjYyQUFEOTE4M0UzMTE5NDhCRDEzRTJCRTc5OUExPC9zdFJlZjpvcmlnaW5hbERvY3VtZW50SUQ+CiAgICAgICAgIDwveG1wTU06RGVyaXZlZEZyb20+CiAgICAgICAgIDxwaG90b3Nob3A6Q29sb3JNb2RlPjM8L3Bob3Rvc2hvcDpDb2xvck1vZGU+CiAgICAgICAgIDxwaG90b3Nob3A6SUNDUHJvZmlsZT5zUkdCIElFQzYxOTY2LTIuMTwvcGhvdG9zaG9wOklDQ1Byb2ZpbGU+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjcyMDA5MC8xMDAwMDwvdGlmZjpYUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+NzIwMDkwLzEwMDAwPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjI0PC9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5zaW9uPjI0PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz4ubxs+AAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAUtSURBVHjajJZ/bNT1Gcdfz/P53PV6B4W7VltLqdAaplIOiMOoyxxJCSs/Gv/yB4gzJroAosmmDklwkYWR0bQsdmkykoojTpcsWYLxD/lRZdMQkTHRtkLZRqG0tIVe7662vTu43n32x/VKZ/jh89cn38/zvN7P5/l88zwf2blzJz6fDwARQUSm1n8s31CM0/VAnbNmsUPuAsDpgEO+Bg4C7//iyv5hvmMiQiqVQpqamvB6vVNwEeG1JZtCBrYi/MrkAwDNgjhwAlbzICBLA0rDb0+/839C6XQaaWxspLCw8Dp86cbNmqVFJQddE6KzdjZ9D89g+B6fSyC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2NIoKpr69nxeiZxLHicFSFVWfGqBidIP3LSjrWltD94CyufF/4kQgPuVz2Lz93+dDRa9eu5QQ8Hg8/iXee+Dy4CKMs7xqn4nwKz9IirhQqmVuB42m8ey+x7LMoD6iAON782eChhqmRuXfvXgKBAKqKqtI0/8nNKrQI4BVYXkzHgzPpC88gWuHL/caXrhLoGiN0apSKr0ZZRBZM7q2w5ZnLR1oAnHOMjY0hra2tFBQUYIyZmstvVT1Z6eDlAuEVq7merxmwueNPDXy9PvybjKP5mctHLk4/XTKZRJqbm/H7/VNw1VyEMYbW4FN3WNWnnchKoy5sHeVGBRX6VWi3ymFx7r11Ix8MTX/y5C2RSPC/AQB61erowbpqSwAAAABJRU5ErkJggg==\")}div.vis-network div.vis-manipulation button.vis-button.vis-delete{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gR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gPHRpZmY6WVJlc29sdXRpb24+NzIwMDkwLzEwMDAwPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjI0PC9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5zaW9uPjI0PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz4aYJzYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAYGSURBVHjalJZ7UJTnFcZ/73m/72PdJY1RbhoQp6lkXRAvmIYxdCUadLVOozPNtGObap1JsKipjiShbdoRbeKEiQHpQK3xj0xa03aamTbaTGyAYV1QGeqFi+JyiZFLAlmESBkWRmS3fyzslGkmnZ5/v/M873Oe75zzvqqoqAibzQaAiKCUAkApRdHIK/NFsx2NR91nOSILADDoJyzNaM4xxbtvPHh0iC+JiYkJ1OHDh4mJiUEpFSXPv/ziPC28TIiXDCOSrAClQDSEpsCwJPIhrEBRQpiSytXlQwDhcBilFPfu3UMVFxdjt9ujFTzfcLBADCoEEAFr1ZbrrNjch2vtEImPBgHob7fTcWE+bVXJNJ/NiFQlEGLvieXHKmYqGB8fRx05cgSbzYaIsPvywV8pKFaA7fGtLTzz61YWpo/xVTHQbufsq5lcez9zWuWhk5mvFwMEg0H0+vXrMU2Tn1wp3CtCiQ5DjGd3A/m/v8IDCZP8r4iNmyRrWx/j/5qktykZpXKzAjVDVxPzGqemptDr1q1jX3NRnIJarcDKK2hgR2ULXRfncv7UYv7xpovhnhiW5Mz+kefeSKO6LJ1A1xzEuk/Ojm4mRibpuZaMZW3OCtRUND60NmiICCIUShisx7a2sLMiQn4s77uEQgIabnqdfHIlgT1/qQeg8vs5dHhdCNB1wYn3RIiC995j26stjAbsNH+YiZJCESnS1Y/XxIXu8r4YIPv/VkVs3CTnTy2ms34xro1+sp9po6sxlTu34ultmsPVvy6is86FCHgO+DDs49zpjuf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3ZeXIYASgL1/X5RfMXMvj46OosrLy7HZbGitUUohIuzoem0RofALaOsghgWGjky0MiJTL8b0lOvI8hN1DKXKP0jd3TNTWDgcJhgMoo4ePYrD4Yi+KmaeLlprnrtXFo9h/AAlG1AqE8yFmBrC+jO0bgH9EVpO/1F2Dc5g//OAsbEx/j0Af+USsQynL1UAAAAASUVORK5CYII=\")}div.vis-network div.vis-edit-mode div.vis-label,div.vis-network div.vis-manipulation div.vis-label{line-height:25px;margin:0 0 0 23px}div.vis-network div.vis-manipulation div.vis-separator-line{background-color:#bdbdbd;display:inline-block;float:left;height:21px;margin:0 7px 0 15px;width:1px}";
styleInject(css_248z);
// Declare install function executed by Vue.use()
function install(app) {
if (install.installed) return;
install.installed = true;
app.component(script$2.name, script$2);
app.component(script.name, script);
app.component(script$1.name, script$1);
}
const plugin = {
install
};
// To auto-install when Vue is found
let GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
export { DataSet, DataView, script$1 as Graph2d, script as Network, script$2 as Timeline, install };