function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = o[Symbol.iterator](); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, basedir, module) { return module = { path: basedir, exports: {}, require: function (path, base) { return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); } }, fn(module, module.exports), module.exports; } function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); } var check = function check(it) { return it && it.Math == Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global_1 = // eslint-disable-next-line no-undef check((typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis)) == 'object' && globalThis) || check((typeof window === "undefined" ? "undefined" : _typeof(window)) == 'object' && window) || check((typeof self === "undefined" ? "undefined" : _typeof(self)) == 'object' && self) || check(_typeof(commonjsGlobal) == 'object' && commonjsGlobal) || // eslint-disable-next-line no-new-func Function('return this')(); var fails = function fails(exec) { try { return !!exec(); } catch (error) { return true; } }; var descriptors = !fails(function () { return Object.defineProperty({}, 1, { get: function get() { return 7; } })[1] != 7; }); var nativePropertyIsEnumerable = {}.propertyIsEnumerable; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable var f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor(this, V); return !!descriptor && descriptor.enumerable; } : nativePropertyIsEnumerable; var objectPropertyIsEnumerable = { f: f }; var createPropertyDescriptor = function createPropertyDescriptor(bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var toString = {}.toString; var classofRaw = function classofRaw(it) { return toString.call(it).slice(8, -1); }; var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings var indexedObject = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classofRaw(it) == 'String' ? split.call(it, '') : Object(it); } : Object; // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible var requireObjectCoercible = function requireObjectCoercible(it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; var toIndexedObject = function toIndexedObject(it) { return indexedObject(requireObjectCoercible(it)); }; var isObject = function isObject(it) { return _typeof(it) === 'object' ? it !== null : typeof it === 'function'; }; // https://tc39.github.io/ecma262/#sec-toprimitive // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var toPrimitive = function toPrimitive(input, PREFERRED_STRING) { if (!isObject(input)) return input; var fn, val; if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; throw TypeError("Can't convert object to primitive value"); }; var hasOwnProperty = {}.hasOwnProperty; var has = function has(it, key) { return hasOwnProperty.call(it, key); }; var document$1 = global_1.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document$1) && isObject(document$1.createElement); var documentCreateElement = function documentCreateElement(it) { return EXISTS ? document$1.createElement(it) : {}; }; var ie8DomDefine = !descriptors && !fails(function () { return Object.defineProperty(documentCreateElement('div'), 'a', { get: function get() { return 7; } }).a != 7; }); var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (ie8DomDefine) try { return nativeGetOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]); }; var objectGetOwnPropertyDescriptor = { f: f$1 }; var anObject = function anObject(it) { if (!isObject(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method // https://tc39.github.io/ecma262/#sec-object.defineproperty var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (ie8DomDefine) try { return nativeDefineProperty(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var objectDefineProperty = { f: f$2 }; var createNonEnumerableProperty = descriptors ? function (object, key, value) { return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var setGlobal = function setGlobal(key, value) { try { createNonEnumerableProperty(global_1, key, value); } catch (error) { global_1[key] = value; } return value; }; var SHARED = '__core-js_shared__'; var store = global_1[SHARED] || setGlobal(SHARED, {}); var sharedStore = store; var functionToString = Function.toString; // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper if (typeof sharedStore.inspectSource != 'function') { sharedStore.inspectSource = function (it) { return functionToString.call(it); }; } var inspectSource = sharedStore.inspectSource; var WeakMap = global_1.WeakMap; var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap)); var isPure = false; var shared = createCommonjsModule(function (module) { (module.exports = function (key, value) { return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.6.5', mode: 'global', copyright: '© 2020 Denis Pushkarev (zloirock.ru)' }); }); var id = 0; var postfix = Math.random(); var uid = function uid(key) { return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); }; var keys = shared('keys'); var sharedKey = function sharedKey(key) { return keys[key] || (keys[key] = uid(key)); }; var hiddenKeys = {}; var WeakMap$1 = global_1.WeakMap; var set, get, has$1; var enforce = function enforce(it) { return has$1(it) ? get(it) : set(it, {}); }; var getterFor = function getterFor(TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (nativeWeakMap) { var store$1 = new WeakMap$1(); var wmget = store$1.get; var wmhas = store$1.has; var wmset = store$1.set; set = function set(it, metadata) { wmset.call(store$1, it, metadata); return metadata; }; get = function get(it) { return wmget.call(store$1, it) || {}; }; has$1 = function has(it) { return wmhas.call(store$1, it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function set(it, metadata) { createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function get(it) { return has(it, STATE) ? it[STATE] : {}; }; has$1 = function has$1(it) { return has(it, STATE); }; } var internalState = { set: set, get: get, has: has$1, enforce: enforce, getterFor: getterFor }; var redefine = createCommonjsModule(function (module) { var getInternalState = internalState.get; var enforceInternalState = internalState.enforce; var TEMPLATE = String(String).split('String'); (module.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; if (typeof value == 'function') { if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); } if (O === global_1) { if (simple) O[key] = value;else setGlobal(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value;else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || inspectSource(this); }); }); var path = global_1; var aFunction = function aFunction(variable) { return typeof variable == 'function' ? variable : undefined; }; var getBuiltIn = function getBuiltIn(namespace, method) { return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace]) : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method]; }; var ceil = Math.ceil; var floor = Math.floor; // `ToInteger` abstract operation // https://tc39.github.io/ecma262/#sec-tointeger var toInteger = function toInteger(argument) { return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); }; var min = Math.min; // `ToLength` abstract operation // https://tc39.github.io/ecma262/#sec-tolength var toLength = function toLength(argument) { return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; var max = Math.max; var min$1 = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). var toAbsoluteIndex = function toAbsoluteIndex(index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min$1(integer, length); }; var createMethod = function createMethod(IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (; length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; var arrayIncludes = { // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; var indexOf = arrayIncludes.indexOf; var objectKeysInternal = function objectKeysInternal(object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) { !has(hiddenKeys, key) && has(O, key) && result.push(key); } // Don't enum bug & hidden keys while (names.length > i) { if (has(O, key = names[i++])) { ~indexOf(result, key) || result.push(key); } } return result; }; // IE8- don't enum bug keys var enumBugKeys = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf']; var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return objectKeysInternal(O, hiddenKeys$1); }; var objectGetOwnPropertyNames = { f: f$3 }; var f$4 = Object.getOwnPropertySymbols; var objectGetOwnPropertySymbols = { f: f$4 }; var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = objectGetOwnPropertyNames.f(anObject(it)); var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; var copyConstructorProperties = function copyConstructorProperties(target, source) { var keys = ownKeys(source); var defineProperty = objectDefineProperty.f; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } }; var replacement = /#|\.prototype\./; var isForced = function isForced(feature, detection) { var value = data[normalize(feature)]; return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; var isForced_1 = isForced; var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ var _export = function _export(options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global_1; } else if (STATIC) { target = global_1[TARGET] || setGlobal(TARGET, {}); } else { target = (global_1[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor$1(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (_typeof(sourceProperty) === _typeof(targetProperty)) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || targetProperty && targetProperty.sham) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () { // Chrome 38 Symbol has incorrect toString conversion // eslint-disable-next-line no-undef return !String(Symbol()); }); var useSymbolAsUid = nativeSymbol // eslint-disable-next-line no-undef && !Symbol.sham // eslint-disable-next-line no-undef && _typeof(Symbol.iterator) == 'symbol'; // https://tc39.github.io/ecma262/#sec-isarray var isArray = Array.isArray || function isArray(arg) { return classofRaw(arg) == 'Array'; }; // https://tc39.github.io/ecma262/#sec-toobject var toObject = function toObject(argument) { return Object(requireObjectCoercible(argument)); }; // https://tc39.github.io/ecma262/#sec-object.keys var objectKeys = Object.keys || function keys(O) { return objectKeysInternal(O, enumBugKeys); }; // https://tc39.github.io/ecma262/#sec-object.defineproperties var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = objectKeys(Properties); var length = keys.length; var index = 0; var key; while (length > index) { objectDefineProperty.f(O, key = keys[index++], Properties[key]); } return O; }; var html = getBuiltIn('document', 'documentElement'); var GT = '>'; var LT = '<'; var PROTOTYPE = 'prototype'; var SCRIPT = 'script'; var IE_PROTO = sharedKey('IE_PROTO'); var EmptyConstructor = function EmptyConstructor() { /* empty */ }; var scriptTag = function scriptTag(content) { return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; }; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype var NullProtoObjectViaActiveX = function NullProtoObjectViaActiveX(activeXDocument) { activeXDocument.write(scriptTag('')); activeXDocument.close(); var temp = activeXDocument.parentWindow.Object; activeXDocument = null; // avoid memory leak return temp; }; // Create object with fake `null` prototype: use iframe Object with cleared prototype var NullProtoObjectViaIFrame = function NullProtoObjectViaIFrame() { // Thrash, waste and sodomy: IE GC bug var iframe = documentCreateElement('iframe'); var JS = 'java' + SCRIPT + ':'; var iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475 iframe.src = String(JS); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(scriptTag('document.F=Object')); iframeDocument.close(); return iframeDocument.F; }; // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 // avoid IE GC bug var activeXDocument; var _NullProtoObject = function NullProtoObject() { try { /* global ActiveXObject */ activeXDocument = document.domain && new ActiveXObject('htmlfile'); } catch (error) { /* ignore */ } _NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame(); var length = enumBugKeys.length; while (length--) { delete _NullProtoObject[PROTOTYPE][enumBugKeys[length]]; } return _NullProtoObject(); }; hiddenKeys[IE_PROTO] = true; // `Object.create` method // https://tc39.github.io/ecma262/#sec-object.create var objectCreate = Object.create || function create(O, Properties) { var result; if (O !== null) { EmptyConstructor[PROTOTYPE] = anObject(O); result = new EmptyConstructor(); EmptyConstructor[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = _NullProtoObject(); return Properties === undefined ? result : objectDefineProperties(result, Properties); }; var nativeGetOwnPropertyNames = objectGetOwnPropertyNames.f; var toString$1 = {}.toString; var windowNames = (typeof window === "undefined" ? "undefined" : _typeof(window)) == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function getWindowNames(it) { try { return nativeGetOwnPropertyNames(it); } catch (error) { return windowNames.slice(); } }; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var f$5 = function getOwnPropertyNames(it) { return windowNames && toString$1.call(it) == '[object Window]' ? getWindowNames(it) : nativeGetOwnPropertyNames(toIndexedObject(it)); }; var objectGetOwnPropertyNamesExternal = { f: f$5 }; var WellKnownSymbolsStore = shared('wks'); var _Symbol = global_1.Symbol; var createWellKnownSymbol = useSymbolAsUid ? _Symbol : _Symbol && _Symbol.withoutSetter || uid; var wellKnownSymbol = function wellKnownSymbol(name) { if (!has(WellKnownSymbolsStore, name)) { if (nativeSymbol && has(_Symbol, name)) WellKnownSymbolsStore[name] = _Symbol[name];else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); } return WellKnownSymbolsStore[name]; }; var f$6 = wellKnownSymbol; var wellKnownSymbolWrapped = { f: f$6 }; var defineProperty = objectDefineProperty.f; var defineWellKnownSymbol = function defineWellKnownSymbol(NAME) { var _Symbol = path.Symbol || (path.Symbol = {}); if (!has(_Symbol, NAME)) defineProperty(_Symbol, NAME, { value: wellKnownSymbolWrapped.f(NAME) }); }; var defineProperty$1 = objectDefineProperty.f; var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var setToStringTag = function setToStringTag(it, TAG, STATIC) { if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) { defineProperty$1(it, TO_STRING_TAG, { configurable: true, value: TAG }); } }; var aFunction$1 = function aFunction(it) { if (typeof it != 'function') { throw TypeError(String(it) + ' is not a function'); } return it; }; var functionBindContext = function functionBindContext(fn, that, length) { aFunction$1(fn); if (that === undefined) return fn; switch (length) { case 0: return function () { return fn.call(that); }; case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function () /* ...args */ { return fn.apply(that, arguments); }; }; var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation // https://tc39.github.io/ecma262/#sec-arrayspeciescreate var arraySpeciesCreate = function arraySpeciesCreate(originalArray, length) { var C; if (isArray(originalArray)) { C = originalArray.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;else if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); }; var push = [].push; // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation var createMethod$1 = function createMethod(TYPE) { var IS_MAP = TYPE == 1; var IS_FILTER = TYPE == 2; var IS_SOME = TYPE == 3; var IS_EVERY = TYPE == 4; var IS_FIND_INDEX = TYPE == 6; var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; return function ($this, callbackfn, that, specificCreate) { var O = toObject($this); var self = indexedObject(O); var boundFunction = functionBindContext(callbackfn, that, 3); var length = toLength(self.length); var index = 0; var create = specificCreate || arraySpeciesCreate; var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; var value, result; for (; length > index; index++) { if (NO_HOLES || index in self) { value = self[index]; result = boundFunction(value, index, O); if (TYPE) { if (IS_MAP) target[index] = result; // map else if (result) switch (TYPE) { case 3: return true; // some case 5: return value; // find case 6: return index; // findIndex case 2: push.call(target, value); // filter } else if (IS_EVERY) return false; // every } } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; }; }; var arrayIteration = { // `Array.prototype.forEach` method // https://tc39.github.io/ecma262/#sec-array.prototype.foreach forEach: createMethod$1(0), // `Array.prototype.map` method // https://tc39.github.io/ecma262/#sec-array.prototype.map map: createMethod$1(1), // `Array.prototype.filter` method // https://tc39.github.io/ecma262/#sec-array.prototype.filter filter: createMethod$1(2), // `Array.prototype.some` method // https://tc39.github.io/ecma262/#sec-array.prototype.some some: createMethod$1(3), // `Array.prototype.every` method // https://tc39.github.io/ecma262/#sec-array.prototype.every every: createMethod$1(4), // `Array.prototype.find` method // https://tc39.github.io/ecma262/#sec-array.prototype.find find: createMethod$1(5), // `Array.prototype.findIndex` method // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex findIndex: createMethod$1(6) }; var $forEach = arrayIteration.forEach; var HIDDEN = sharedKey('hidden'); var SYMBOL = 'Symbol'; var PROTOTYPE$1 = 'prototype'; var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); var setInternalState = internalState.set; var getInternalState = internalState.getterFor(SYMBOL); var ObjectPrototype = Object[PROTOTYPE$1]; var $Symbol = global_1.Symbol; var $stringify = getBuiltIn('JSON', 'stringify'); var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; var nativeDefineProperty$1 = objectDefineProperty.f; var nativeGetOwnPropertyNames$1 = objectGetOwnPropertyNamesExternal.f; var nativePropertyIsEnumerable$1 = objectPropertyIsEnumerable.f; var AllSymbols = shared('symbols'); var ObjectPrototypeSymbols = shared('op-symbols'); var StringToSymbolRegistry = shared('string-to-symbol-registry'); var SymbolToStringRegistry = shared('symbol-to-string-registry'); var WellKnownSymbolsStore$1 = shared('wks'); var QObject = global_1.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDescriptor = descriptors && fails(function () { return objectCreate(nativeDefineProperty$1({}, 'a', { get: function get() { return nativeDefineProperty$1(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (O, P, Attributes) { var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$1(ObjectPrototype, P); if (ObjectPrototypeDescriptor) delete ObjectPrototype[P]; nativeDefineProperty$1(O, P, Attributes); if (ObjectPrototypeDescriptor && O !== ObjectPrototype) { nativeDefineProperty$1(ObjectPrototype, P, ObjectPrototypeDescriptor); } } : nativeDefineProperty$1; var wrap = function wrap(tag, description) { var symbol = AllSymbols[tag] = objectCreate($Symbol[PROTOTYPE$1]); setInternalState(symbol, { type: SYMBOL, tag: tag, description: description }); if (!descriptors) symbol.description = description; return symbol; }; var isSymbol = useSymbolAsUid ? function (it) { return _typeof(it) == 'symbol'; } : function (it) { return Object(it) instanceof $Symbol; }; var $defineProperty = function defineProperty(O, P, Attributes) { if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes); anObject(O); var key = toPrimitive(P, true); anObject(Attributes); if (has(AllSymbols, key)) { if (!Attributes.enumerable) { if (!has(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor(1, {})); O[HIDDEN][key] = true; } else { if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false; Attributes = objectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) }); } return setSymbolDescriptor(O, key, Attributes); } return nativeDefineProperty$1(O, key, Attributes); }; var $defineProperties = function defineProperties(O, Properties) { anObject(O); var properties = toIndexedObject(Properties); var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties)); $forEach(keys, function (key) { if (!descriptors || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]); }); return O; }; var $create = function create(O, Properties) { return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties); }; var $propertyIsEnumerable = function propertyIsEnumerable(V) { var P = toPrimitive(V, true); var enumerable = nativePropertyIsEnumerable$1.call(this, P); if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false; return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) { var it = toIndexedObject(O); var key = toPrimitive(P, true); if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return; var descriptor = nativeGetOwnPropertyDescriptor$1(it, key); if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) { descriptor.enumerable = true; } return descriptor; }; var $getOwnPropertyNames = function getOwnPropertyNames(O) { var names = nativeGetOwnPropertyNames$1(toIndexedObject(O)); var result = []; $forEach(names, function (key) { if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key); }); return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(O) { var IS_OBJECT_PROTOTYPE = O === ObjectPrototype; var names = nativeGetOwnPropertyNames$1(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O)); var result = []; $forEach(names, function (key) { if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) { result.push(AllSymbols[key]); } }); return result; }; // `Symbol` constructor // https://tc39.github.io/ecma262/#sec-symbol-constructor if (!nativeSymbol) { $Symbol = function _Symbol() { if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor'); var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]); var tag = uid(description); var setter = function setter(value) { if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value); if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value)); }; if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter }); return wrap(tag, description); }; redefine($Symbol[PROTOTYPE$1], 'toString', function toString() { return getInternalState(this).tag; }); redefine($Symbol, 'withoutSetter', function (description) { return wrap(uid(description), description); }); objectPropertyIsEnumerable.f = $propertyIsEnumerable; objectDefineProperty.f = $defineProperty; objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor; objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames; objectGetOwnPropertySymbols.f = $getOwnPropertySymbols; wellKnownSymbolWrapped.f = function (name) { return wrap(wellKnownSymbol(name), name); }; if (descriptors) { // https://github.com/tc39/proposal-Symbol-description nativeDefineProperty$1($Symbol[PROTOTYPE$1], 'description', { configurable: true, get: function description() { return getInternalState(this).description; } }); { redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true }); } } } _export({ global: true, wrap: true, forced: !nativeSymbol, sham: !nativeSymbol }, { Symbol: $Symbol }); $forEach(objectKeys(WellKnownSymbolsStore$1), function (name) { defineWellKnownSymbol(name); }); _export({ target: SYMBOL, stat: true, forced: !nativeSymbol }, { // `Symbol.for` method // https://tc39.github.io/ecma262/#sec-symbol.for 'for': function _for(key) { var string = String(key); if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string]; var symbol = $Symbol(string); StringToSymbolRegistry[string] = symbol; SymbolToStringRegistry[symbol] = string; return symbol; }, // `Symbol.keyFor` method // https://tc39.github.io/ecma262/#sec-symbol.keyfor keyFor: function keyFor(sym) { if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol'); if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym]; }, useSetter: function useSetter() { USE_SETTER = true; }, useSimple: function useSimple() { USE_SETTER = false; } }); _export({ target: 'Object', stat: true, forced: !nativeSymbol, sham: !descriptors }, { // `Object.create` method // https://tc39.github.io/ecma262/#sec-object.create create: $create, // `Object.defineProperty` method // https://tc39.github.io/ecma262/#sec-object.defineproperty defineProperty: $defineProperty, // `Object.defineProperties` method // https://tc39.github.io/ecma262/#sec-object.defineproperties defineProperties: $defineProperties, // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors getOwnPropertyDescriptor: $getOwnPropertyDescriptor }); _export({ target: 'Object', stat: true, forced: !nativeSymbol }, { // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames getOwnPropertyNames: $getOwnPropertyNames, // `Object.getOwnPropertySymbols` method // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols getOwnPropertySymbols: $getOwnPropertySymbols }); // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives // https://bugs.chromium.org/p/v8/issues/detail?id=3443 _export({ target: 'Object', stat: true, forced: fails(function () { objectGetOwnPropertySymbols.f(1); }) }, { getOwnPropertySymbols: function getOwnPropertySymbols(it) { return objectGetOwnPropertySymbols.f(toObject(it)); } }); // `JSON.stringify` method behavior with symbols // https://tc39.github.io/ecma262/#sec-json.stringify if ($stringify) { var FORCED_JSON_STRINGIFY = !nativeSymbol || fails(function () { var symbol = $Symbol(); // MS Edge converts symbol values to JSON as {} return $stringify([symbol]) != '[null]' // WebKit converts symbol values to JSON as null || $stringify({ a: symbol }) != '{}' // V8 throws on boxed symbols || $stringify(Object(symbol)) != '{}'; }); _export({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, { // eslint-disable-next-line no-unused-vars stringify: function stringify(it, replacer, space) { var args = [it]; var index = 1; var $replacer; while (arguments.length > index) { args.push(arguments[index++]); } $replacer = replacer; if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined if (!isArray(replacer)) replacer = function replacer(key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol(value)) return value; }; args[1] = replacer; return $stringify.apply(null, args); } }); } // `Symbol.prototype[@@toPrimitive]` method // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive if (!$Symbol[PROTOTYPE$1][TO_PRIMITIVE]) { createNonEnumerableProperty($Symbol[PROTOTYPE$1], TO_PRIMITIVE, $Symbol[PROTOTYPE$1].valueOf); } // `Symbol.prototype[@@toStringTag]` property // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag setToStringTag($Symbol, SYMBOL); hiddenKeys[HIDDEN] = true; var defineProperty$2 = objectDefineProperty.f; var NativeSymbol = global_1.Symbol; if (descriptors && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || // Safari 12 bug NativeSymbol().description !== undefined)) { var EmptyStringDescriptionStore = {}; // wrap Symbol constructor for correct work with undefined description var SymbolWrapper = function _Symbol() { var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]); var result = this instanceof SymbolWrapper ? new NativeSymbol(description) // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)' : description === undefined ? NativeSymbol() : NativeSymbol(description); if (description === '') EmptyStringDescriptionStore[result] = true; return result; }; copyConstructorProperties(SymbolWrapper, NativeSymbol); var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype; symbolPrototype.constructor = SymbolWrapper; var symbolToString = symbolPrototype.toString; var _native = String(NativeSymbol('test')) == 'Symbol(test)'; var regexp = /^Symbol\((.*)\)[^)]+$/; defineProperty$2(symbolPrototype, 'description', { configurable: true, get: function description() { var symbol = isObject(this) ? this.valueOf() : this; var string = symbolToString.call(symbol); if (has(EmptyStringDescriptionStore, symbol)) return ''; var desc = _native ? string.slice(7, -1) : string.replace(regexp, '$1'); return desc === '' ? undefined : desc; } }); _export({ global: true, forced: true }, { Symbol: SymbolWrapper }); } // https://tc39.github.io/ecma262/#sec-symbol.asynciterator defineWellKnownSymbol('asyncIterator'); // https://tc39.github.io/ecma262/#sec-symbol.hasinstance defineWellKnownSymbol('hasInstance'); // https://tc39.github.io/ecma262/#sec-symbol.isconcatspreadable defineWellKnownSymbol('isConcatSpreadable'); // https://tc39.github.io/ecma262/#sec-symbol.iterator defineWellKnownSymbol('iterator'); // https://tc39.github.io/ecma262/#sec-symbol.match defineWellKnownSymbol('match'); defineWellKnownSymbol('matchAll'); // https://tc39.github.io/ecma262/#sec-symbol.replace defineWellKnownSymbol('replace'); // https://tc39.github.io/ecma262/#sec-symbol.search defineWellKnownSymbol('search'); // https://tc39.github.io/ecma262/#sec-symbol.species defineWellKnownSymbol('species'); // https://tc39.github.io/ecma262/#sec-symbol.split defineWellKnownSymbol('split'); // https://tc39.github.io/ecma262/#sec-symbol.toprimitive defineWellKnownSymbol('toPrimitive'); // https://tc39.github.io/ecma262/#sec-symbol.tostringtag defineWellKnownSymbol('toStringTag'); // https://tc39.github.io/ecma262/#sec-symbol.unscopables defineWellKnownSymbol('unscopables'); var createProperty = function createProperty(object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));else object[propertyKey] = value; }; var engineUserAgent = getBuiltIn('navigator', 'userAgent') || ''; var process = global_1.process; var versions = process && process.versions; var v8 = versions && versions.v8; var match, version; if (v8) { match = v8.split('.'); version = match[0] + match[1]; } else if (engineUserAgent) { match = engineUserAgent.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = engineUserAgent.match(/Chrome\/(\d+)/); if (match) version = match[1]; } } var engineV8Version = version && +version; var SPECIES$1 = wellKnownSymbol('species'); var arrayMethodHasSpeciesSupport = function arrayMethodHasSpeciesSupport(METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return engineV8Version >= 51 || !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES$1] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/679 var IS_CONCAT_SPREADABLE_SUPPORT = engineV8Version >= 51 || !fails(function () { var array = []; array[IS_CONCAT_SPREADABLE] = false; return array.concat()[0] !== array; }); var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); var isConcatSpreadable = function isConcatSpreadable(O) { if (!isObject(O)) return false; var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray(O); }; var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method // https://tc39.github.io/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species _export({ target: 'Array', proto: true, forced: FORCED }, { concat: function concat(arg) { // eslint-disable-line no-unused-vars var O = toObject(this); var A = arraySpeciesCreate(O, 0); var n = 0; var i, k, length, len, E; for (i = -1, length = arguments.length; i < length; i++) { E = i === -1 ? O : arguments[i]; if (isConcatSpreadable(E)) { len = toLength(E.length); if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); for (k = 0; k < len; k++, n++) { if (k in E) createProperty(A, n, E[k]); } } else { if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); createProperty(A, n++, E); } } A.length = n; return A; } }); var min$2 = Math.min; // `Array.prototype.copyWithin` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin var arrayCopyWithin = [].copyWithin || function copyWithin(target /* = 0 */ , start /* = 0, end = @length */ ) { var O = toObject(this); var len = toLength(O.length); var to = toAbsoluteIndex(target, len); var from = toAbsoluteIndex(start, len); var end = arguments.length > 2 ? arguments[2] : undefined; var count = min$2((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); var inc = 1; if (from < to && to < from + count) { inc = -1; from += count - 1; to += count - 1; } while (count-- > 0) { if (from in O) O[to] = O[from];else delete O[to]; to += inc; from += inc; } return O; }; var UNSCOPABLES = wellKnownSymbol('unscopables'); var ArrayPrototype = Array.prototype; // Array.prototype[@@unscopables] // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables if (ArrayPrototype[UNSCOPABLES] == undefined) { objectDefineProperty.f(ArrayPrototype, UNSCOPABLES, { configurable: true, value: objectCreate(null) }); } // add a key to Array.prototype[@@unscopables] var addToUnscopables = function addToUnscopables(key) { ArrayPrototype[UNSCOPABLES][key] = true; }; // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin _export({ target: 'Array', proto: true }, { copyWithin: arrayCopyWithin }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('copyWithin'); var arrayMethodIsStrict = function arrayMethodIsStrict(METHOD_NAME, argument) { var method = [][METHOD_NAME]; return !!method && fails(function () { // eslint-disable-next-line no-useless-call,no-throw-literal method.call(null, argument || function () { throw 1; }, 1); }); }; var defineProperty$3 = Object.defineProperty; var cache = {}; var thrower = function thrower(it) { throw it; }; var arrayMethodUsesToLength = function arrayMethodUsesToLength(METHOD_NAME, options) { if (has(cache, METHOD_NAME)) return cache[METHOD_NAME]; if (!options) options = {}; var method = [][METHOD_NAME]; var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false; var argument0 = has(options, 0) ? options[0] : thrower; var argument1 = has(options, 1) ? options[1] : undefined; return cache[METHOD_NAME] = !!method && !fails(function () { if (ACCESSORS && !descriptors) return true; var O = { length: -1 }; if (ACCESSORS) defineProperty$3(O, 1, { enumerable: true, get: thrower });else O[1] = 1; method.call(O, argument0, argument1); }); }; var $every = arrayIteration.every; var STRICT_METHOD = arrayMethodIsStrict('every'); var USES_TO_LENGTH = arrayMethodUsesToLength('every'); // `Array.prototype.every` method // https://tc39.github.io/ecma262/#sec-array.prototype.every _export({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, { every: function every(callbackfn /* , thisArg */ ) { return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.prototype.fill var arrayFill = function fill(value /* , start = 0, end = @length */ ) { var O = toObject(this); var length = toLength(O.length); var argumentsLength = arguments.length; var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length); var end = argumentsLength > 2 ? arguments[2] : undefined; var endPos = end === undefined ? length : toAbsoluteIndex(end, length); while (endPos > index) { O[index++] = value; } return O; }; // https://tc39.github.io/ecma262/#sec-array.prototype.fill _export({ target: 'Array', proto: true }, { fill: arrayFill }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('fill'); var $filter = arrayIteration.filter; var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); // Edge 14- issue var USES_TO_LENGTH$1 = arrayMethodUsesToLength('filter'); // `Array.prototype.filter` method // https://tc39.github.io/ecma262/#sec-array.prototype.filter // with adding support of @@species _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH$1 }, { filter: function filter(callbackfn /* , thisArg */ ) { return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); var $find = arrayIteration.find; var FIND = 'find'; var SKIPS_HOLES = true; var USES_TO_LENGTH$2 = arrayMethodUsesToLength(FIND); // Shouldn't skip holes if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; }); // `Array.prototype.find` method // https://tc39.github.io/ecma262/#sec-array.prototype.find _export({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH$2 }, { find: function find(callbackfn /* , that = undefined */ ) { return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables(FIND); var $findIndex = arrayIteration.findIndex; var FIND_INDEX = 'findIndex'; var SKIPS_HOLES$1 = true; var USES_TO_LENGTH$3 = arrayMethodUsesToLength(FIND_INDEX); // Shouldn't skip holes if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES$1 = false; }); // `Array.prototype.findIndex` method // https://tc39.github.io/ecma262/#sec-array.prototype.findindex _export({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 || !USES_TO_LENGTH$3 }, { findIndex: function findIndex(callbackfn /* , that = undefined */ ) { return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables(FIND_INDEX); // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray var flattenIntoArray = function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { var targetIndex = start; var sourceIndex = 0; var mapFn = mapper ? functionBindContext(mapper, thisArg, 3) : false; var element; while (sourceIndex < sourceLen) { if (sourceIndex in source) { element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; if (depth > 0 && isArray(element)) { targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; } else { if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError('Exceed the acceptable array length'); target[targetIndex] = element; } targetIndex++; } sourceIndex++; } return targetIndex; }; var flattenIntoArray_1 = flattenIntoArray; // https://github.com/tc39/proposal-flatMap _export({ target: 'Array', proto: true }, { flat: function flat() /* depthArg = 1 */ { var depthArg = arguments.length ? arguments[0] : undefined; var O = toObject(this); var sourceLen = toLength(O.length); var A = arraySpeciesCreate(O, 0); A.length = flattenIntoArray_1(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); return A; } }); // https://github.com/tc39/proposal-flatMap _export({ target: 'Array', proto: true }, { flatMap: function flatMap(callbackfn /* , thisArg */ ) { var O = toObject(this); var sourceLen = toLength(O.length); var A; aFunction$1(callbackfn); A = arraySpeciesCreate(O, 0); A.length = flattenIntoArray_1(A, O, O, sourceLen, 0, 1, callbackfn, arguments.length > 1 ? arguments[1] : undefined); return A; } }); var $forEach$1 = arrayIteration.forEach; var STRICT_METHOD$1 = arrayMethodIsStrict('forEach'); var USES_TO_LENGTH$4 = arrayMethodUsesToLength('forEach'); // `Array.prototype.forEach` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.foreach var arrayForEach = !STRICT_METHOD$1 || !USES_TO_LENGTH$4 ? function forEach(callbackfn /* , thisArg */ ) { return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } : [].forEach; // https://tc39.github.io/ecma262/#sec-array.prototype.foreach _export({ target: 'Array', proto: true, forced: [].forEach != arrayForEach }, { forEach: arrayForEach }); var callWithSafeIterationClosing = function callWithSafeIterationClosing(iterator, fn, value, ENTRIES) { try { return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (error) { var returnMethod = iterator['return']; if (returnMethod !== undefined) anObject(returnMethod.call(iterator)); throw error; } }; var iterators = {}; var ITERATOR = wellKnownSymbol('iterator'); var ArrayPrototype$1 = Array.prototype; // check on default Array iterator var isArrayIteratorMethod = function isArrayIteratorMethod(it) { return it !== undefined && (iterators.Array === it || ArrayPrototype$1[ITERATOR] === it); }; var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag'); var test = {}; test[TO_STRING_TAG$1] = 'z'; var toStringTagSupport = String(test) === '[object z]'; var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag'); // ES3 wrong here var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function tryGet(it, key) { try { return it[key]; } catch (error) { /* empty */ } }; // getting tag from ES6+ `Object.prototype.toString` var classof = toStringTagSupport ? classofRaw : function (it) { var O, tag, result; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$2)) == 'string' ? tag // builtinTag case : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; }; var ITERATOR$1 = wellKnownSymbol('iterator'); var getIteratorMethod = function getIteratorMethod(it) { if (it != undefined) return it[ITERATOR$1] || it['@@iterator'] || iterators[classof(it)]; }; // https://tc39.github.io/ecma262/#sec-array.from var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */ ) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var argumentsLength = arguments.length; var mapfn = argumentsLength > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var iteratorMethod = getIteratorMethod(O); var index = 0; var length, result, step, iterator, next, value; if (mapping) mapfn = functionBindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); // if the target is not iterable or it's an array with the default iterator - use a simple case if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { iterator = iteratorMethod.call(O); next = iterator.next; result = new C(); for (; !(step = next.call(iterator)).done; index++) { value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value; createProperty(result, index, value); } } else { length = toLength(O.length); result = new C(length); for (; length > index; index++) { value = mapping ? mapfn(O[index], index) : O[index]; createProperty(result, index, value); } } result.length = index; return result; }; var ITERATOR$2 = wellKnownSymbol('iterator'); var SAFE_CLOSING = false; try { var called = 0; var iteratorWithReturn = { next: function next() { return { done: !!called++ }; }, 'return': function _return() { SAFE_CLOSING = true; } }; iteratorWithReturn[ITERATOR$2] = function () { return this; }; // eslint-disable-next-line no-throw-literal Array.from(iteratorWithReturn, function () { throw 2; }); } catch (error) { /* empty */ } var checkCorrectnessOfIteration = function checkCorrectnessOfIteration(exec, SKIP_CLOSING) { if (!SKIP_CLOSING && !SAFE_CLOSING) return false; var ITERATION_SUPPORT = false; try { var object = {}; object[ITERATOR$2] = function () { return { next: function next() { return { done: ITERATION_SUPPORT = true }; } }; }; exec(object); } catch (error) { /* empty */ } return ITERATION_SUPPORT; }; var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) { Array.from(iterable); }); // `Array.from` method // https://tc39.github.io/ecma262/#sec-array.from _export({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, { from: arrayFrom }); var $includes = arrayIncludes.includes; var USES_TO_LENGTH$5 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes _export({ target: 'Array', proto: true, forced: !USES_TO_LENGTH$5 }, { includes: function includes(el /* , fromIndex = 0 */ ) { return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('includes'); var $indexOf = arrayIncludes.indexOf; var nativeIndexOf = [].indexOf; var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0; var STRICT_METHOD$2 = arrayMethodIsStrict('indexOf'); var USES_TO_LENGTH$6 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof _export({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD$2 || !USES_TO_LENGTH$6 }, { indexOf: function indexOf(searchElement /* , fromIndex = 0 */ ) { return NEGATIVE_ZERO // convert -0 to +0 ? nativeIndexOf.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.isarray _export({ target: 'Array', stat: true }, { isArray: isArray }); var correctPrototypeGetter = !fails(function () { function F() { /* empty */ } F.prototype.constructor = null; return Object.getPrototypeOf(new F()) !== F.prototype; }); var IE_PROTO$1 = sharedKey('IE_PROTO'); var ObjectPrototype$1 = Object.prototype; // `Object.getPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.getprototypeof var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) { O = toObject(O); if (has(O, IE_PROTO$1)) return O[IE_PROTO$1]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectPrototype$1 : null; }; var ITERATOR$3 = wellKnownSymbol('iterator'); var BUGGY_SAFARI_ITERATORS = false; var returnThis = function returnThis() { return this; }; // `%IteratorPrototype%` object // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; if ([].keys) { arrayIterator = [].keys(); // Safari 8 has buggy iterators w/o `next` if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;else { PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator)); if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; } } if (IteratorPrototype == undefined) IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() if ( !has(IteratorPrototype, ITERATOR$3)) { createNonEnumerableProperty(IteratorPrototype, ITERATOR$3, returnThis); } var iteratorsCore = { IteratorPrototype: IteratorPrototype, BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS }; var IteratorPrototype$1 = iteratorsCore.IteratorPrototype; var returnThis$1 = function returnThis() { return this; }; var createIteratorConstructor = function createIteratorConstructor(IteratorConstructor, NAME, next) { var TO_STRING_TAG = NAME + ' Iterator'; IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) }); setToStringTag(IteratorConstructor, TO_STRING_TAG, false); iterators[TO_STRING_TAG] = returnThis$1; return IteratorConstructor; }; var aPossiblePrototype = function aPossiblePrototype(it) { if (!isObject(it) && it !== null) { throw TypeError("Can't set " + String(it) + ' as a prototype'); } return it; }; // https://tc39.github.io/ecma262/#sec-object.setprototypeof // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () { var CORRECT_SETTER = false; var test = {}; var setter; try { setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; setter.call(test, []); CORRECT_SETTER = test instanceof Array; } catch (error) { /* empty */ } return function setPrototypeOf(O, proto) { anObject(O); aPossiblePrototype(proto); if (CORRECT_SETTER) setter.call(O, proto);else O.__proto__ = proto; return O; }; }() : undefined); var IteratorPrototype$2 = iteratorsCore.IteratorPrototype; var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS; var ITERATOR$4 = wellKnownSymbol('iterator'); var KEYS = 'keys'; var VALUES = 'values'; var ENTRIES = 'entries'; var returnThis$2 = function returnThis() { return this; }; var defineIterator = function defineIterator(Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { createIteratorConstructor(IteratorConstructor, NAME, next); var getIterationMethod = function getIterationMethod(KIND) { if (KIND === DEFAULT && defaultIterator) return defaultIterator; if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND]; switch (KIND) { case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; } return function () { return new IteratorConstructor(this); }; }; var TO_STRING_TAG = NAME + ' Iterator'; var INCORRECT_VALUES_NAME = false; var IterablePrototype = Iterable.prototype; var nativeIterator = IterablePrototype[ITERATOR$4] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT]; var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT); var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; var CurrentIteratorPrototype, methods, KEY; // fix native if (anyNativeIterator) { CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable())); if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) { if ( objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype$2) { if (objectSetPrototypeOf) { objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype$2); } else if (typeof CurrentIteratorPrototype[ITERATOR$4] != 'function') { createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR$4, returnThis$2); } } // Set @@toStringTag to native iterators setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { INCORRECT_VALUES_NAME = true; defaultIterator = function values() { return nativeIterator.call(this); }; } // define iterator if ( IterablePrototype[ITERATOR$4] !== defaultIterator) { createNonEnumerableProperty(IterablePrototype, ITERATOR$4, defaultIterator); } iterators[NAME] = defaultIterator; // export additional methods if (DEFAULT) { methods = { values: getIterationMethod(VALUES), keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), entries: getIterationMethod(ENTRIES) }; if (FORCED) for (KEY in methods) { if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { redefine(IterablePrototype, KEY, methods[KEY]); } } else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods); } return methods; }; var ARRAY_ITERATOR = 'Array Iterator'; var setInternalState$1 = internalState.set; var getInternalState$1 = internalState.getterFor(ARRAY_ITERATOR); // `Array.prototype.entries` method // https://tc39.github.io/ecma262/#sec-array.prototype.entries // `Array.prototype.keys` method // https://tc39.github.io/ecma262/#sec-array.prototype.keys // `Array.prototype.values` method // https://tc39.github.io/ecma262/#sec-array.prototype.values // `Array.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator // `CreateArrayIterator` internal method // https://tc39.github.io/ecma262/#sec-createarrayiterator var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) { setInternalState$1(this, { type: ARRAY_ITERATOR, target: toIndexedObject(iterated), // target index: 0, // next index kind: kind // kind }); // `%ArrayIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next }, function () { var state = getInternalState$1(this); var target = state.target; var kind = state.kind; var index = state.index++; if (!target || index >= target.length) { state.target = undefined; return { value: undefined, done: true }; } if (kind == 'keys') return { value: index, done: false }; if (kind == 'values') return { value: target[index], done: false }; return { value: [index, target[index]], done: false }; }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% // https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject // https://tc39.github.io/ecma262/#sec-createmappedargumentsobject iterators.Arguments = iterators.Array; // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); var nativeJoin = [].join; var ES3_STRINGS = indexedObject != Object; var STRICT_METHOD$3 = arrayMethodIsStrict('join', ','); // `Array.prototype.join` method // https://tc39.github.io/ecma262/#sec-array.prototype.join _export({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$3 }, { join: function join(separator) { return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator); } }); var min$3 = Math.min; var nativeLastIndexOf = [].lastIndexOf; var NEGATIVE_ZERO$1 = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0; var STRICT_METHOD$4 = arrayMethodIsStrict('lastIndexOf'); // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method var USES_TO_LENGTH$7 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); var FORCED$1 = NEGATIVE_ZERO$1 || !STRICT_METHOD$4 || !USES_TO_LENGTH$7; // `Array.prototype.lastIndexOf` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof var arrayLastIndexOf = FORCED$1 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */ ) { // convert -0 to +0 if (NEGATIVE_ZERO$1) return nativeLastIndexOf.apply(this, arguments) || 0; var O = toIndexedObject(this); var length = toLength(O.length); var index = length - 1; if (arguments.length > 1) index = min$3(index, toInteger(arguments[1])); if (index < 0) index = length + index; for (; index >= 0; index--) { if (index in O && O[index] === searchElement) return index || 0; } return -1; } : nativeLastIndexOf; // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof _export({ target: 'Array', proto: true, forced: arrayLastIndexOf !== [].lastIndexOf }, { lastIndexOf: arrayLastIndexOf }); var $map = arrayIteration.map; var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport('map'); // FF49- issue var USES_TO_LENGTH$8 = arrayMethodUsesToLength('map'); // `Array.prototype.map` method // https://tc39.github.io/ecma262/#sec-array.prototype.map // with adding support of @@species _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 || !USES_TO_LENGTH$8 }, { map: function map(callbackfn /* , thisArg */ ) { return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); var ISNT_GENERIC = fails(function () { function F() { /* empty */ } return !(Array.of.call(F) instanceof F); }); // `Array.of` method // https://tc39.github.io/ecma262/#sec-array.of // WebKit Array.of isn't generic _export({ target: 'Array', stat: true, forced: ISNT_GENERIC }, { of: function of() /* ...args */ { var index = 0; var argumentsLength = arguments.length; var result = new (typeof this == 'function' ? this : Array)(argumentsLength); while (argumentsLength > index) { createProperty(result, index, arguments[index++]); } result.length = argumentsLength; return result; } }); var createMethod$2 = function createMethod(IS_RIGHT) { return function (that, callbackfn, argumentsLength, memo) { aFunction$1(callbackfn); var O = toObject(that); var self = indexedObject(O); var length = toLength(O.length); var index = IS_RIGHT ? length - 1 : 0; var i = IS_RIGHT ? -1 : 1; if (argumentsLength < 2) while (true) { if (index in self) { memo = self[index]; index += i; break; } index += i; if (IS_RIGHT ? index < 0 : length <= index) { throw TypeError('Reduce of empty array with no initial value'); } } for (; IS_RIGHT ? index >= 0 : length > index; index += i) { if (index in self) { memo = callbackfn(memo, self[index], index, O); } } return memo; }; }; var arrayReduce = { // `Array.prototype.reduce` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduce left: createMethod$2(false), // `Array.prototype.reduceRight` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright right: createMethod$2(true) }; var $reduce = arrayReduce.left; var STRICT_METHOD$5 = arrayMethodIsStrict('reduce'); var USES_TO_LENGTH$9 = arrayMethodUsesToLength('reduce', { 1: 0 }); // `Array.prototype.reduce` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduce _export({ target: 'Array', proto: true, forced: !STRICT_METHOD$5 || !USES_TO_LENGTH$9 }, { reduce: function reduce(callbackfn /* , initialValue */ ) { return $reduce(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); } }); var $reduceRight = arrayReduce.right; var STRICT_METHOD$6 = arrayMethodIsStrict('reduceRight'); // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method var USES_TO_LENGTH$a = arrayMethodUsesToLength('reduce', { 1: 0 }); // `Array.prototype.reduceRight` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright _export({ target: 'Array', proto: true, forced: !STRICT_METHOD$6 || !USES_TO_LENGTH$a }, { reduceRight: function reduceRight(callbackfn /* , initialValue */ ) { return $reduceRight(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); } }); var nativeReverse = [].reverse; var test$1 = [1, 2]; // `Array.prototype.reverse` method // https://tc39.github.io/ecma262/#sec-array.prototype.reverse // fix for Safari 12.0 bug // https://bugs.webkit.org/show_bug.cgi?id=188794 _export({ target: 'Array', proto: true, forced: String(test$1) === String(test$1.reverse()) }, { reverse: function reverse() { // eslint-disable-next-line no-self-assign if (isArray(this)) this.length = this.length; return nativeReverse.call(this); } }); var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport('slice'); var USES_TO_LENGTH$b = arrayMethodUsesToLength('slice', { ACCESSORS: true, 0: 0, 1: 2 }); var SPECIES$2 = wellKnownSymbol('species'); var nativeSlice = [].slice; var max$1 = Math.max; // `Array.prototype.slice` method // https://tc39.github.io/ecma262/#sec-array.prototype.slice // fallback for not array-like ES3 strings and DOM objects _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 || !USES_TO_LENGTH$b }, { slice: function slice(start, end) { var O = toIndexedObject(this); var length = toLength(O.length); var k = toAbsoluteIndex(start, length); var fin = toAbsoluteIndex(end === undefined ? length : end, length); // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible var Constructor, result, n; if (isArray(O)) { Constructor = O.constructor; // cross-realm fallback if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) { Constructor = undefined; } else if (isObject(Constructor)) { Constructor = Constructor[SPECIES$2]; if (Constructor === null) Constructor = undefined; } if (Constructor === Array || Constructor === undefined) { return nativeSlice.call(O, k, fin); } } result = new (Constructor === undefined ? Array : Constructor)(max$1(fin - k, 0)); for (n = 0; k < fin; k++, n++) { if (k in O) createProperty(result, n, O[k]); } result.length = n; return result; } }); var $some = arrayIteration.some; var STRICT_METHOD$7 = arrayMethodIsStrict('some'); var USES_TO_LENGTH$c = arrayMethodUsesToLength('some'); // `Array.prototype.some` method // https://tc39.github.io/ecma262/#sec-array.prototype.some _export({ target: 'Array', proto: true, forced: !STRICT_METHOD$7 || !USES_TO_LENGTH$c }, { some: function some(callbackfn /* , thisArg */ ) { return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); var test$2 = []; var nativeSort = test$2.sort; // IE8- var FAILS_ON_UNDEFINED = fails(function () { test$2.sort(undefined); }); // V8 bug var FAILS_ON_NULL = fails(function () { test$2.sort(null); }); // Old WebKit var STRICT_METHOD$8 = arrayMethodIsStrict('sort'); var FORCED$2 = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD$8; // `Array.prototype.sort` method // https://tc39.github.io/ecma262/#sec-array.prototype.sort _export({ target: 'Array', proto: true, forced: FORCED$2 }, { sort: function sort(comparefn) { return comparefn === undefined ? nativeSort.call(toObject(this)) : nativeSort.call(toObject(this), aFunction$1(comparefn)); } }); var SPECIES$3 = wellKnownSymbol('species'); var setSpecies = function setSpecies(CONSTRUCTOR_NAME) { var Constructor = getBuiltIn(CONSTRUCTOR_NAME); var defineProperty = objectDefineProperty.f; if (descriptors && Constructor && !Constructor[SPECIES$3]) { defineProperty(Constructor, SPECIES$3, { configurable: true, get: function get() { return this; } }); } }; // https://tc39.github.io/ecma262/#sec-get-array-@@species setSpecies('Array'); var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport('splice'); var USES_TO_LENGTH$d = arrayMethodUsesToLength('splice', { ACCESSORS: true, 0: 0, 1: 2 }); var max$2 = Math.max; var min$4 = Math.min; var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; // `Array.prototype.splice` method // https://tc39.github.io/ecma262/#sec-array.prototype.splice // with adding support of @@species _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 || !USES_TO_LENGTH$d }, { splice: function splice(start, deleteCount /* , ...items */ ) { var O = toObject(this); var len = toLength(O.length); var actualStart = toAbsoluteIndex(start, len); var argumentsLength = arguments.length; var insertCount, actualDeleteCount, A, k, from, to; if (argumentsLength === 0) { insertCount = actualDeleteCount = 0; } else if (argumentsLength === 1) { insertCount = 0; actualDeleteCount = len - actualStart; } else { insertCount = argumentsLength - 2; actualDeleteCount = min$4(max$2(toInteger(deleteCount), 0), len - actualStart); } if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER$1) { throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED); } A = arraySpeciesCreate(O, actualDeleteCount); for (k = 0; k < actualDeleteCount; k++) { from = actualStart + k; if (from in O) createProperty(A, k, O[from]); } A.length = actualDeleteCount; if (insertCount < actualDeleteCount) { for (k = actualStart; k < len - actualDeleteCount; k++) { from = k + actualDeleteCount; to = k + insertCount; if (from in O) O[to] = O[from];else delete O[to]; } for (k = len; k > len - actualDeleteCount + insertCount; k--) { delete O[k - 1]; } } else if (insertCount > actualDeleteCount) { for (k = len - actualDeleteCount; k > actualStart; k--) { from = k + actualDeleteCount - 1; to = k + insertCount - 1; if (from in O) O[to] = O[from];else delete O[to]; } } for (k = 0; k < insertCount; k++) { O[k + actualStart] = arguments[k + 2]; } O.length = len - actualDeleteCount + insertCount; return A; } }); // in popular engines, so it's moved to a separate module addToUnscopables('flat'); // in popular engines, so it's moved to a separate module addToUnscopables('flatMap'); var arrayBufferNative = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined'; var redefineAll = function redefineAll(target, src, options) { for (var key in src) { redefine(target, key, src[key], options); } return target; }; var anInstance = function anInstance(it, Constructor, name) { if (!(it instanceof Constructor)) { throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); } return it; }; // https://tc39.github.io/ecma262/#sec-toindex var toIndex = function toIndex(it) { if (it === undefined) return 0; var number = toInteger(it); var length = toLength(number); if (number !== length) throw RangeError('Wrong length or index'); return length; }; // IEEE754 conversions based on https://github.com/feross/ieee754 // eslint-disable-next-line no-shadow-restricted-names var Infinity$1 = 1 / 0; var abs = Math.abs; var pow = Math.pow; var floor$1 = Math.floor; var log = Math.log; var LN2 = Math.LN2; var pack = function pack(number, mantissaLength, bytes) { var buffer = new Array(bytes); var exponentLength = bytes * 8 - mantissaLength - 1; var eMax = (1 << exponentLength) - 1; var eBias = eMax >> 1; var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0; var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0; var index = 0; var exponent, mantissa, c; number = abs(number); // eslint-disable-next-line no-self-compare if (number != number || number === Infinity$1) { // eslint-disable-next-line no-self-compare mantissa = number != number ? 1 : 0; exponent = eMax; } else { exponent = floor$1(log(number) / LN2); if (number * (c = pow(2, -exponent)) < 1) { exponent--; c *= 2; } if (exponent + eBias >= 1) { number += rt / c; } else { number += rt * pow(2, 1 - eBias); } if (number * c >= 2) { exponent++; c /= 2; } if (exponent + eBias >= eMax) { mantissa = 0; exponent = eMax; } else if (exponent + eBias >= 1) { mantissa = (number * c - 1) * pow(2, mantissaLength); exponent = exponent + eBias; } else { mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength); exponent = 0; } } for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8) { } exponent = exponent << mantissaLength | mantissa; exponentLength += mantissaLength; for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8) { } buffer[--index] |= sign * 128; return buffer; }; var unpack = function unpack(buffer, mantissaLength) { var bytes = buffer.length; var exponentLength = bytes * 8 - mantissaLength - 1; var eMax = (1 << exponentLength) - 1; var eBias = eMax >> 1; var nBits = exponentLength - 7; var index = bytes - 1; var sign = buffer[index--]; var exponent = sign & 127; var mantissa; sign >>= 7; for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8) { } mantissa = exponent & (1 << -nBits) - 1; exponent >>= -nBits; nBits += mantissaLength; for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8) { } if (exponent === 0) { exponent = 1 - eBias; } else if (exponent === eMax) { return mantissa ? NaN : sign ? -Infinity$1 : Infinity$1; } else { mantissa = mantissa + pow(2, mantissaLength); exponent = exponent - eBias; } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength); }; var ieee754 = { pack: pack, unpack: unpack }; var getOwnPropertyNames = objectGetOwnPropertyNames.f; var defineProperty$4 = objectDefineProperty.f; var getInternalState$2 = internalState.get; var setInternalState$2 = internalState.set; var ARRAY_BUFFER = 'ArrayBuffer'; var DATA_VIEW = 'DataView'; var PROTOTYPE$2 = 'prototype'; var WRONG_LENGTH = 'Wrong length'; var WRONG_INDEX = 'Wrong index'; var NativeArrayBuffer = global_1[ARRAY_BUFFER]; var $ArrayBuffer = NativeArrayBuffer; var $DataView = global_1[DATA_VIEW]; var $DataViewPrototype = $DataView && $DataView[PROTOTYPE$2]; var ObjectPrototype$2 = Object.prototype; var RangeError$1 = global_1.RangeError; var packIEEE754 = ieee754.pack; var unpackIEEE754 = ieee754.unpack; var packInt8 = function packInt8(number) { return [number & 0xFF]; }; var packInt16 = function packInt16(number) { return [number & 0xFF, number >> 8 & 0xFF]; }; var packInt32 = function packInt32(number) { return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF]; }; var unpackInt32 = function unpackInt32(buffer) { return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; }; var packFloat32 = function packFloat32(number) { return packIEEE754(number, 23, 4); }; var packFloat64 = function packFloat64(number) { return packIEEE754(number, 52, 8); }; var addGetter = function addGetter(Constructor, key) { defineProperty$4(Constructor[PROTOTYPE$2], key, { get: function get() { return getInternalState$2(this)[key]; } }); }; var get$1 = function get(view, count, index, isLittleEndian) { var intIndex = toIndex(index); var store = getInternalState$2(view); if (intIndex + count > store.byteLength) throw RangeError$1(WRONG_INDEX); var bytes = getInternalState$2(store.buffer).bytes; var start = intIndex + store.byteOffset; var pack = bytes.slice(start, start + count); return isLittleEndian ? pack : pack.reverse(); }; var set$1 = function set(view, count, index, conversion, value, isLittleEndian) { var intIndex = toIndex(index); var store = getInternalState$2(view); if (intIndex + count > store.byteLength) throw RangeError$1(WRONG_INDEX); var bytes = getInternalState$2(store.buffer).bytes; var start = intIndex + store.byteOffset; var pack = conversion(+value); for (var i = 0; i < count; i++) { bytes[start + i] = pack[isLittleEndian ? i : count - i - 1]; } }; if (!arrayBufferNative) { $ArrayBuffer = function ArrayBuffer(length) { anInstance(this, $ArrayBuffer, ARRAY_BUFFER); var byteLength = toIndex(length); setInternalState$2(this, { bytes: arrayFill.call(new Array(byteLength), 0), byteLength: byteLength }); if (!descriptors) this.byteLength = byteLength; }; $DataView = function DataView(buffer, byteOffset, byteLength) { anInstance(this, $DataView, DATA_VIEW); anInstance(buffer, $ArrayBuffer, DATA_VIEW); var bufferLength = getInternalState$2(buffer).byteLength; var offset = toInteger(byteOffset); if (offset < 0 || offset > bufferLength) throw RangeError$1('Wrong offset'); byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); if (offset + byteLength > bufferLength) throw RangeError$1(WRONG_LENGTH); setInternalState$2(this, { buffer: buffer, byteLength: byteLength, byteOffset: offset }); if (!descriptors) { this.buffer = buffer; this.byteLength = byteLength; this.byteOffset = offset; } }; if (descriptors) { addGetter($ArrayBuffer, 'byteLength'); addGetter($DataView, 'buffer'); addGetter($DataView, 'byteLength'); addGetter($DataView, 'byteOffset'); } redefineAll($DataView[PROTOTYPE$2], { getInt8: function getInt8(byteOffset) { return get$1(this, 1, byteOffset)[0] << 24 >> 24; }, getUint8: function getUint8(byteOffset) { return get$1(this, 1, byteOffset)[0]; }, getInt16: function getInt16(byteOffset /* , littleEndian */ ) { var bytes = get$1(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); return (bytes[1] << 8 | bytes[0]) << 16 >> 16; }, getUint16: function getUint16(byteOffset /* , littleEndian */ ) { var bytes = get$1(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); return bytes[1] << 8 | bytes[0]; }, getInt32: function getInt32(byteOffset /* , littleEndian */ ) { return unpackInt32(get$1(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)); }, getUint32: function getUint32(byteOffset /* , littleEndian */ ) { return unpackInt32(get$1(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0; }, getFloat32: function getFloat32(byteOffset /* , littleEndian */ ) { return unpackIEEE754(get$1(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23); }, getFloat64: function getFloat64(byteOffset /* , littleEndian */ ) { return unpackIEEE754(get$1(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52); }, setInt8: function setInt8(byteOffset, value) { set$1(this, 1, byteOffset, packInt8, value); }, setUint8: function setUint8(byteOffset, value) { set$1(this, 1, byteOffset, packInt8, value); }, setInt16: function setInt16(byteOffset, value /* , littleEndian */ ) { set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); }, setUint16: function setUint16(byteOffset, value /* , littleEndian */ ) { set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); }, setInt32: function setInt32(byteOffset, value /* , littleEndian */ ) { set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); }, setUint32: function setUint32(byteOffset, value /* , littleEndian */ ) { set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); }, setFloat32: function setFloat32(byteOffset, value /* , littleEndian */ ) { set$1(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined); }, setFloat64: function setFloat64(byteOffset, value /* , littleEndian */ ) { set$1(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined); } }); } else { if (!fails(function () { NativeArrayBuffer(1); }) || !fails(function () { new NativeArrayBuffer(-1); // eslint-disable-line no-new }) || fails(function () { new NativeArrayBuffer(); // eslint-disable-line no-new new NativeArrayBuffer(1.5); // eslint-disable-line no-new new NativeArrayBuffer(NaN); // eslint-disable-line no-new return NativeArrayBuffer.name != ARRAY_BUFFER; })) { $ArrayBuffer = function ArrayBuffer(length) { anInstance(this, $ArrayBuffer); return new NativeArrayBuffer(toIndex(length)); }; var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE$2] = NativeArrayBuffer[PROTOTYPE$2]; for (var keys$1 = getOwnPropertyNames(NativeArrayBuffer), j = 0, key; keys$1.length > j;) { if (!((key = keys$1[j++]) in $ArrayBuffer)) { createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer[key]); } } ArrayBufferPrototype.constructor = $ArrayBuffer; } // WebKit bug - the same parent prototype for typed arrays and data view if (objectSetPrototypeOf && objectGetPrototypeOf($DataViewPrototype) !== ObjectPrototype$2) { objectSetPrototypeOf($DataViewPrototype, ObjectPrototype$2); } // iOS Safari 7.x bug var testView = new $DataView(new $ArrayBuffer(2)); var nativeSetInt8 = $DataViewPrototype.setInt8; testView.setInt8(0, 2147483648); testView.setInt8(1, 2147483649); if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataViewPrototype, { setInt8: function setInt8(byteOffset, value) { nativeSetInt8.call(this, byteOffset, value << 24 >> 24); }, setUint8: function setUint8(byteOffset, value) { nativeSetInt8.call(this, byteOffset, value << 24 >> 24); } }, { unsafe: true }); } setToStringTag($ArrayBuffer, ARRAY_BUFFER); setToStringTag($DataView, DATA_VIEW); var arrayBuffer = { ArrayBuffer: $ArrayBuffer, DataView: $DataView }; var ARRAY_BUFFER$1 = 'ArrayBuffer'; var ArrayBuffer$1 = arrayBuffer[ARRAY_BUFFER$1]; var NativeArrayBuffer$1 = global_1[ARRAY_BUFFER$1]; // `ArrayBuffer` constructor // https://tc39.github.io/ecma262/#sec-arraybuffer-constructor _export({ global: true, forced: NativeArrayBuffer$1 !== ArrayBuffer$1 }, { ArrayBuffer: ArrayBuffer$1 }); setSpecies(ARRAY_BUFFER$1); var defineProperty$5 = objectDefineProperty.f; var Int8Array$1 = global_1.Int8Array; var Int8ArrayPrototype = Int8Array$1 && Int8Array$1.prototype; var Uint8ClampedArray$1 = global_1.Uint8ClampedArray; var Uint8ClampedArrayPrototype = Uint8ClampedArray$1 && Uint8ClampedArray$1.prototype; var TypedArray = Int8Array$1 && objectGetPrototypeOf(Int8Array$1); var TypedArrayPrototype = Int8ArrayPrototype && objectGetPrototypeOf(Int8ArrayPrototype); var ObjectPrototype$3 = Object.prototype; var isPrototypeOf = ObjectPrototype$3.isPrototypeOf; var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag'); var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); // Fixing native typed arrays in Opera Presto crashes the browser, see #595 var NATIVE_ARRAY_BUFFER_VIEWS = arrayBufferNative && !!objectSetPrototypeOf && classof(global_1.opera) !== 'Opera'; var TYPED_ARRAY_TAG_REQIRED = false; var NAME; var TypedArrayConstructorsList = { Int8Array: 1, Uint8Array: 1, Uint8ClampedArray: 1, Int16Array: 2, Uint16Array: 2, Int32Array: 4, Uint32Array: 4, Float32Array: 4, Float64Array: 8 }; var isView = function isView(it) { var klass = classof(it); return klass === 'DataView' || has(TypedArrayConstructorsList, klass); }; var isTypedArray = function isTypedArray(it) { return isObject(it) && has(TypedArrayConstructorsList, classof(it)); }; var aTypedArray = function aTypedArray(it) { if (isTypedArray(it)) return it; throw TypeError('Target is not a typed array'); }; var aTypedArrayConstructor = function aTypedArrayConstructor(C) { if (objectSetPrototypeOf) { if (isPrototypeOf.call(TypedArray, C)) return C; } else for (var ARRAY in TypedArrayConstructorsList) { if (has(TypedArrayConstructorsList, NAME)) { var TypedArrayConstructor = global_1[ARRAY]; if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) { return C; } } } throw TypeError('Target is not a typed array constructor'); }; var exportTypedArrayMethod = function exportTypedArrayMethod(KEY, property, forced) { if (!descriptors) return; if (forced) for (var ARRAY in TypedArrayConstructorsList) { var TypedArrayConstructor = global_1[ARRAY]; if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) { delete TypedArrayConstructor.prototype[KEY]; } } if (!TypedArrayPrototype[KEY] || forced) { redefine(TypedArrayPrototype, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property); } }; var exportTypedArrayStaticMethod = function exportTypedArrayStaticMethod(KEY, property, forced) { var ARRAY, TypedArrayConstructor; if (!descriptors) return; if (objectSetPrototypeOf) { if (forced) for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global_1[ARRAY]; if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) { delete TypedArrayConstructor[KEY]; } } if (!TypedArray[KEY] || forced) { // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable try { return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array$1[KEY] || property); } catch (error) { /* empty */ } } else return; } for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global_1[ARRAY]; if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { redefine(TypedArrayConstructor, KEY, property); } } }; for (NAME in TypedArrayConstructorsList) { if (!global_1[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false; } // WebKit bug - typed arrays constructors prototype is Object.prototype if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) { // eslint-disable-next-line no-shadow TypedArray = function TypedArray() { throw TypeError('Incorrect invocation'); }; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global_1[NAME]) objectSetPrototypeOf(global_1[NAME], TypedArray); } } if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype$3) { TypedArrayPrototype = TypedArray.prototype; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global_1[NAME]) objectSetPrototypeOf(global_1[NAME].prototype, TypedArrayPrototype); } } // WebKit bug - one more object in Uint8ClampedArray prototype chain if (NATIVE_ARRAY_BUFFER_VIEWS && objectGetPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { objectSetPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); } if (descriptors && !has(TypedArrayPrototype, TO_STRING_TAG$3)) { TYPED_ARRAY_TAG_REQIRED = true; defineProperty$5(TypedArrayPrototype, TO_STRING_TAG$3, { get: function get() { return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; } }); for (NAME in TypedArrayConstructorsList) { if (global_1[NAME]) { createNonEnumerableProperty(global_1[NAME], TYPED_ARRAY_TAG, NAME); } } } var arrayBufferViewCore = { NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG, aTypedArray: aTypedArray, aTypedArrayConstructor: aTypedArrayConstructor, exportTypedArrayMethod: exportTypedArrayMethod, exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, isView: isView, isTypedArray: isTypedArray, TypedArray: TypedArray, TypedArrayPrototype: TypedArrayPrototype }; var NATIVE_ARRAY_BUFFER_VIEWS$1 = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; // `ArrayBuffer.isView` method // https://tc39.github.io/ecma262/#sec-arraybuffer.isview _export({ target: 'ArrayBuffer', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS$1 }, { isView: arrayBufferViewCore.isView }); var SPECIES$4 = wellKnownSymbol('species'); // `SpeciesConstructor` abstract operation // https://tc39.github.io/ecma262/#sec-speciesconstructor var speciesConstructor = function speciesConstructor(O, defaultConstructor) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES$4]) == undefined ? defaultConstructor : aFunction$1(S); }; var ArrayBuffer$2 = arrayBuffer.ArrayBuffer; var DataView$1 = arrayBuffer.DataView; var nativeArrayBufferSlice = ArrayBuffer$2.prototype.slice; var INCORRECT_SLICE = fails(function () { return !new ArrayBuffer$2(2).slice(1, undefined).byteLength; }); // `ArrayBuffer.prototype.slice` method // https://tc39.github.io/ecma262/#sec-arraybuffer.prototype.slice _export({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, { slice: function slice(start, end) { if (nativeArrayBufferSlice !== undefined && end === undefined) { return nativeArrayBufferSlice.call(anObject(this), start); // FF fix } var length = anObject(this).byteLength; var first = toAbsoluteIndex(start, length); var fin = toAbsoluteIndex(end === undefined ? length : end, length); var result = new (speciesConstructor(this, ArrayBuffer$2))(toLength(fin - first)); var viewSource = new DataView$1(this); var viewTarget = new DataView$1(result); var index = 0; while (first < fin) { viewTarget.setUint8(index++, viewSource.getUint8(first++)); } return result; } }); // https://tc39.github.io/ecma262/#sec-dataview-constructor _export({ global: true, forced: !arrayBufferNative }, { DataView: arrayBuffer.DataView }); // https://tc39.github.io/ecma262/#sec-date.now _export({ target: 'Date', stat: true }, { now: function now() { return new Date().getTime(); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.repeat var stringRepeat = ''.repeat || function repeat(count) { var str = String(requireObjectCoercible(this)); var result = ''; var n = toInteger(count); if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions'); for (; n > 0; (n >>>= 1) && (str += str)) { if (n & 1) result += str; } return result; }; var ceil$1 = Math.ceil; // `String.prototype.{ padStart, padEnd }` methods implementation var createMethod$3 = function createMethod(IS_END) { return function ($this, maxLength, fillString) { var S = String(requireObjectCoercible($this)); var stringLength = S.length; var fillStr = fillString === undefined ? ' ' : String(fillString); var intMaxLength = toLength(maxLength); var fillLen, stringFiller; if (intMaxLength <= stringLength || fillStr == '') return S; fillLen = intMaxLength - stringLength; stringFiller = stringRepeat.call(fillStr, ceil$1(fillLen / fillStr.length)); if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); return IS_END ? S + stringFiller : stringFiller + S; }; }; var stringPad = { // `String.prototype.padStart` method // https://tc39.github.io/ecma262/#sec-string.prototype.padstart start: createMethod$3(false), // `String.prototype.padEnd` method // https://tc39.github.io/ecma262/#sec-string.prototype.padend end: createMethod$3(true) }; var padStart = stringPad.start; var abs$1 = Math.abs; var DatePrototype = Date.prototype; var getTime = DatePrototype.getTime; var nativeDateToISOString = DatePrototype.toISOString; // `Date.prototype.toISOString` method implementation // https://tc39.github.io/ecma262/#sec-date.prototype.toisostring // PhantomJS / old WebKit fails here: var dateToIsoString = fails(function () { return nativeDateToISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; }) || !fails(function () { nativeDateToISOString.call(new Date(NaN)); }) ? function toISOString() { if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); var date = this; var year = date.getUTCFullYear(); var milliseconds = date.getUTCMilliseconds(); var sign = year < 0 ? '-' : year > 9999 ? '+' : ''; return sign + padStart(abs$1(year), sign ? 6 : 4, 0) + '-' + padStart(date.getUTCMonth() + 1, 2, 0) + '-' + padStart(date.getUTCDate(), 2, 0) + 'T' + padStart(date.getUTCHours(), 2, 0) + ':' + padStart(date.getUTCMinutes(), 2, 0) + ':' + padStart(date.getUTCSeconds(), 2, 0) + '.' + padStart(milliseconds, 3, 0) + 'Z'; } : nativeDateToISOString; // https://tc39.github.io/ecma262/#sec-date.prototype.toisostring // PhantomJS / old WebKit has a broken implementations _export({ target: 'Date', proto: true, forced: Date.prototype.toISOString !== dateToIsoString }, { toISOString: dateToIsoString }); var FORCED$3 = fails(function () { return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({ toISOString: function toISOString() { return 1; } }) !== 1; }); // `Date.prototype.toJSON` method // https://tc39.github.io/ecma262/#sec-date.prototype.tojson _export({ target: 'Date', proto: true, forced: FORCED$3 }, { // eslint-disable-next-line no-unused-vars toJSON: function toJSON(key) { var O = toObject(this); var pv = toPrimitive(O); return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); } }); var dateToPrimitive = function dateToPrimitive(hint) { if (hint !== 'string' && hint !== 'number' && hint !== 'default') { throw TypeError('Incorrect hint'); } return toPrimitive(anObject(this), hint !== 'number'); }; var TO_PRIMITIVE$1 = wellKnownSymbol('toPrimitive'); var DatePrototype$1 = Date.prototype; // `Date.prototype[@@toPrimitive]` method // https://tc39.github.io/ecma262/#sec-date.prototype-@@toprimitive if (!(TO_PRIMITIVE$1 in DatePrototype$1)) { createNonEnumerableProperty(DatePrototype$1, TO_PRIMITIVE$1, dateToPrimitive); } var DatePrototype$2 = Date.prototype; var INVALID_DATE = 'Invalid Date'; var TO_STRING = 'toString'; var nativeDateToString = DatePrototype$2[TO_STRING]; var getTime$1 = DatePrototype$2.getTime; // `Date.prototype.toString` method // https://tc39.github.io/ecma262/#sec-date.prototype.tostring if (new Date(NaN) + '' != INVALID_DATE) { redefine(DatePrototype$2, TO_STRING, function toString() { var value = getTime$1.call(this); // eslint-disable-next-line no-self-compare return value === value ? nativeDateToString.call(this) : INVALID_DATE; }); } var slice = [].slice; var factories = {}; var construct = function construct(C, argsLength, args) { if (!(argsLength in factories)) { for (var list = [], i = 0; i < argsLength; i++) { list[i] = 'a[' + i + ']'; } // eslint-disable-next-line no-new-func factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')'); } return factories[argsLength](C, args); }; // `Function.prototype.bind` method implementation // https://tc39.github.io/ecma262/#sec-function.prototype.bind var functionBind = Function.bind || function bind(that /* , ...args */ ) { var fn = aFunction$1(this); var partArgs = slice.call(arguments, 1); var boundFunction = function bound() /* args... */ { var args = partArgs.concat(slice.call(arguments)); return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args); }; if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype; return boundFunction; }; // https://tc39.github.io/ecma262/#sec-function.prototype.bind _export({ target: 'Function', proto: true }, { bind: functionBind }); var HAS_INSTANCE = wellKnownSymbol('hasInstance'); var FunctionPrototype = Function.prototype; // `Function.prototype[@@hasInstance]` method // https://tc39.github.io/ecma262/#sec-function.prototype-@@hasinstance if (!(HAS_INSTANCE in FunctionPrototype)) { objectDefineProperty.f(FunctionPrototype, HAS_INSTANCE, { value: function value(O) { if (typeof this != 'function' || !isObject(O)) return false; if (!isObject(this.prototype)) return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: while (O = objectGetPrototypeOf(O)) { if (this.prototype === O) return true; } return false; } }); } var defineProperty$6 = objectDefineProperty.f; var FunctionPrototype$1 = Function.prototype; var FunctionPrototypeToString = FunctionPrototype$1.toString; var nameRE = /^\s*function ([^ (]*)/; var NAME$1 = 'name'; // Function instances `.name` property // https://tc39.github.io/ecma262/#sec-function-instances-name if (descriptors && !(NAME$1 in FunctionPrototype$1)) { defineProperty$6(FunctionPrototype$1, NAME$1, { configurable: true, get: function get() { try { return FunctionPrototypeToString.call(this).match(nameRE)[1]; } catch (error) { return ''; } } }); } // https://github.com/tc39/proposal-global _export({ global: true }, { globalThis: global_1 }); var $stringify$1 = getBuiltIn('JSON', 'stringify'); var re = /[\uD800-\uDFFF]/g; var low = /^[\uD800-\uDBFF]$/; var hi = /^[\uDC00-\uDFFF]$/; var fix = function fix(match, offset, string) { var prev = string.charAt(offset - 1); var next = string.charAt(offset + 1); if (low.test(match) && !hi.test(next) || hi.test(match) && !low.test(prev)) { return "\\u" + match.charCodeAt(0).toString(16); } return match; }; var FORCED$4 = fails(function () { return $stringify$1("\uDF06\uD834") !== "\"\\udf06\\ud834\"" || $stringify$1("\uDEAD") !== "\"\\udead\""; }); if ($stringify$1) { // https://github.com/tc39/proposal-well-formed-stringify _export({ target: 'JSON', stat: true, forced: FORCED$4 }, { // eslint-disable-next-line no-unused-vars stringify: function stringify(it, replacer, space) { var result = $stringify$1.apply(null, arguments); return typeof result == 'string' ? result.replace(re, fix) : result; } }); } // https://tc39.github.io/ecma262/#sec-json-@@tostringtag setToStringTag(global_1.JSON, 'JSON', true); var freezing = !fails(function () { return Object.isExtensible(Object.preventExtensions({})); }); var internalMetadata = createCommonjsModule(function (module) { var defineProperty = objectDefineProperty.f; var METADATA = uid('meta'); var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var setMetadata = function setMetadata(it) { defineProperty(it, METADATA, { value: { objectID: 'O' + ++id, // object ID weakData: {} // weak collections IDs } }); }; var fastKey = function fastKey(it, create) { // return a primitive with prefix if (!isObject(it)) return _typeof(it) == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, METADATA)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMetadata(it); // return object ID } return it[METADATA].objectID; }; var getWeakData = function getWeakData(it, create) { if (!has(it, METADATA)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMetadata(it); // return the store of weak collections IDs } return it[METADATA].weakData; }; // add metadata on freeze-family methods calling var onFreeze = function onFreeze(it) { if (freezing && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it); return it; }; var meta = module.exports = { REQUIRED: false, fastKey: fastKey, getWeakData: getWeakData, onFreeze: onFreeze }; hiddenKeys[METADATA] = true; }); var iterate_1 = createCommonjsModule(function (module) { var Result = function Result(stopped, result) { this.stopped = stopped; this.result = result; }; var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) { var boundFunction = functionBindContext(fn, that, AS_ENTRIES ? 2 : 1); var iterator, iterFn, index, length, result, next, step; if (IS_ITERATOR) { iterator = iterable; } else { iterFn = getIteratorMethod(iterable); if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); // optimisation for array iterators if (isArrayIteratorMethod(iterFn)) { for (index = 0, length = toLength(iterable.length); length > index; index++) { result = AS_ENTRIES ? boundFunction(anObject(step = iterable[index])[0], step[1]) : boundFunction(iterable[index]); if (result && result instanceof Result) return result; } return new Result(false); } iterator = iterFn.call(iterable); } next = iterator.next; while (!(step = next.call(iterator)).done) { result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES); if (_typeof(result) == 'object' && result && result instanceof Result) return result; } return new Result(false); }; iterate.stop = function (result) { return new Result(true, result); }; }); var inheritIfRequired = function inheritIfRequired($this, dummy, Wrapper) { var NewTarget, NewTargetPrototype; if ( // it can work only with native `setPrototypeOf` objectSetPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this typeof (NewTarget = dummy.constructor) == 'function' && NewTarget !== Wrapper && isObject(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype) objectSetPrototypeOf($this, NewTargetPrototype); return $this; }; var collection = function collection(CONSTRUCTOR_NAME, wrapper, common) { var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1; var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1; var ADDER = IS_MAP ? 'set' : 'add'; var NativeConstructor = global_1[CONSTRUCTOR_NAME]; var NativePrototype = NativeConstructor && NativeConstructor.prototype; var Constructor = NativeConstructor; var exported = {}; var fixMethod = function fixMethod(KEY) { var nativeMethod = NativePrototype[KEY]; redefine(NativePrototype, KEY, KEY == 'add' ? function add(value) { nativeMethod.call(this, value === 0 ? 0 : value); return this; } : KEY == 'delete' ? function (key) { return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); } : KEY == 'get' ? function get(key) { return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key); } : KEY == 'has' ? function has(key) { return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); } : function set(key, value) { nativeMethod.call(this, key === 0 ? 0 : key, value); return this; }); }; // eslint-disable-next-line max-len if (isForced_1(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () { new NativeConstructor().entries().next(); })))) { // create collection constructor Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); internalMetadata.REQUIRED = true; } else if (isForced_1(CONSTRUCTOR_NAME, true)) { var instance = new Constructor(); // early implementations not supports chaining var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); // most early implementations doesn't supports iterables, most modern - not close it correctly // eslint-disable-next-line no-new var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); }); // for early implementations -0 and +0 not the same var BUGGY_ZERO = !IS_WEAK && fails(function () { // V8 ~ Chromium 42- fails only with 5+ elements var $instance = new NativeConstructor(); var index = 5; while (index--) { $instance[ADDER](index, index); } return !$instance.has(-0); }); if (!ACCEPT_ITERABLES) { Constructor = wrapper(function (dummy, iterable) { anInstance(dummy, Constructor, CONSTRUCTOR_NAME); var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor); if (iterable != undefined) iterate_1(iterable, that[ADDER], that, IS_MAP); return that; }); Constructor.prototype = NativePrototype; NativePrototype.constructor = Constructor; } if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); // weak collections should not contains .clear method if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; } exported[CONSTRUCTOR_NAME] = Constructor; _export({ global: true, forced: Constructor != NativeConstructor }, exported); setToStringTag(Constructor, CONSTRUCTOR_NAME); if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); return Constructor; }; var defineProperty$7 = objectDefineProperty.f; var fastKey = internalMetadata.fastKey; var setInternalState$3 = internalState.set; var internalStateGetterFor = internalState.getterFor; var collectionStrong = { getConstructor: function getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { var C = wrapper(function (that, iterable) { anInstance(that, C, CONSTRUCTOR_NAME); setInternalState$3(that, { type: CONSTRUCTOR_NAME, index: objectCreate(null), first: undefined, last: undefined, size: 0 }); if (!descriptors) that.size = 0; if (iterable != undefined) iterate_1(iterable, that[ADDER], that, IS_MAP); }); var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); var define = function define(that, key, value) { var state = getInternalState(that); var entry = getEntry(that, key); var previous, index; // change existing entry if (entry) { entry.value = value; // create new entry } else { state.last = entry = { index: index = fastKey(key, true), key: key, value: value, previous: previous = state.last, next: undefined, removed: false }; if (!state.first) state.first = entry; if (previous) previous.next = entry; if (descriptors) state.size++;else that.size++; // add to index if (index !== 'F') state.index[index] = entry; } return that; }; var getEntry = function getEntry(that, key) { var state = getInternalState(that); // fast case var index = fastKey(key); var entry; if (index !== 'F') return state.index[index]; // frozen object case for (entry = state.first; entry; entry = entry.next) { if (entry.key == key) return entry; } }; redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear() { var that = this; var state = getInternalState(that); var data = state.index; var entry = state.first; while (entry) { entry.removed = true; if (entry.previous) entry.previous = entry.previous.next = undefined; delete data[entry.index]; entry = entry.next; } state.first = state.last = undefined; if (descriptors) state.size = 0;else that.size = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function _delete(key) { var that = this; var state = getInternalState(that); var entry = getEntry(that, key); if (entry) { var next = entry.next; var prev = entry.previous; delete state.index[entry.index]; entry.removed = true; if (prev) prev.next = next; if (next) next.previous = prev; if (state.first == entry) state.first = next; if (state.last == entry) state.last = prev; if (descriptors) state.size--;else that.size--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /* , that = undefined */ ) { var state = getInternalState(this); var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); var entry; while (entry = entry ? entry.next : state.first) { boundFunction(entry.value, entry.key, this); // revert to the last existing entry while (entry && entry.removed) { entry = entry.previous; } } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key) { return !!getEntry(this, key); } }); redefineAll(C.prototype, IS_MAP ? { // 23.1.3.6 Map.prototype.get(key) get: function get(key) { var entry = getEntry(this, key); return entry && entry.value; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value) { return define(this, key === 0 ? 0 : key, value); } } : { // 23.2.3.1 Set.prototype.add(value) add: function add(value) { return define(this, value = value === 0 ? 0 : value, value); } }); if (descriptors) defineProperty$7(C.prototype, 'size', { get: function get() { return getInternalState(this).size; } }); return C; }, setStrong: function setStrong(C, CONSTRUCTOR_NAME, IS_MAP) { var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) { setInternalState$3(this, { type: ITERATOR_NAME, target: iterated, state: getInternalCollectionState(iterated), kind: kind, last: undefined }); }, function () { var state = getInternalIteratorState(this); var kind = state.kind; var entry = state.last; // revert to the last existing entry while (entry && entry.removed) { entry = entry.previous; } // get next entry if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { // or finish the iteration state.target = undefined; return { value: undefined, done: true }; } // return step by kind if (kind == 'keys') return { value: entry.key, done: false }; if (kind == 'values') return { value: entry.value, done: false }; return { value: [entry.key, entry.value], done: false }; }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(CONSTRUCTOR_NAME); } }; // https://tc39.github.io/ecma262/#sec-map-objects var es_map = collection('Map', function (init) { return function Map() { return init(this, arguments.length ? arguments[0] : undefined); }; }, collectionStrong); var log$1 = Math.log; // `Math.log1p` method implementation // https://tc39.github.io/ecma262/#sec-math.log1p var mathLog1p = Math.log1p || function log1p(x) { return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log$1(1 + x); }; var nativeAcosh = Math.acosh; var log$2 = Math.log; var sqrt = Math.sqrt; var LN2$1 = Math.LN2; var FORCED$5 = !nativeAcosh // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 || Math.floor(nativeAcosh(Number.MAX_VALUE)) != 710 // Tor Browser bug: Math.acosh(Infinity) -> NaN || nativeAcosh(Infinity) != Infinity; // `Math.acosh` method // https://tc39.github.io/ecma262/#sec-math.acosh _export({ target: 'Math', stat: true, forced: FORCED$5 }, { acosh: function acosh(x) { return (x = +x) < 1 ? NaN : x > 94906265.62425156 ? log$2(x) + LN2$1 : mathLog1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); } }); var nativeAsinh = Math.asinh; var log$3 = Math.log; var sqrt$1 = Math.sqrt; function asinh(x) { return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log$3(x + sqrt$1(x * x + 1)); } // `Math.asinh` method // https://tc39.github.io/ecma262/#sec-math.asinh // Tor Browser bug: Math.asinh(0) -> -0 _export({ target: 'Math', stat: true, forced: !(nativeAsinh && 1 / nativeAsinh(0) > 0) }, { asinh: asinh }); var nativeAtanh = Math.atanh; var log$4 = Math.log; // `Math.atanh` method // https://tc39.github.io/ecma262/#sec-math.atanh // Tor Browser bug: Math.atanh(-0) -> 0 _export({ target: 'Math', stat: true, forced: !(nativeAtanh && 1 / nativeAtanh(-0) < 0) }, { atanh: function atanh(x) { return (x = +x) == 0 ? x : log$4((1 + x) / (1 - x)) / 2; } }); // `Math.sign` method implementation // https://tc39.github.io/ecma262/#sec-math.sign var mathSign = Math.sign || function sign(x) { // eslint-disable-next-line no-self-compare return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; var abs$2 = Math.abs; var pow$1 = Math.pow; // `Math.cbrt` method // https://tc39.github.io/ecma262/#sec-math.cbrt _export({ target: 'Math', stat: true }, { cbrt: function cbrt(x) { return mathSign(x = +x) * pow$1(abs$2(x), 1 / 3); } }); var floor$2 = Math.floor; var log$5 = Math.log; var LOG2E = Math.LOG2E; // `Math.clz32` method // https://tc39.github.io/ecma262/#sec-math.clz32 _export({ target: 'Math', stat: true }, { clz32: function clz32(x) { return (x >>>= 0) ? 31 - floor$2(log$5(x + 0.5) * LOG2E) : 32; } }); var nativeExpm1 = Math.expm1; var exp = Math.exp; // `Math.expm1` method implementation // https://tc39.github.io/ecma262/#sec-math.expm1 var mathExpm1 = !nativeExpm1 // Old FF bug || nativeExpm1(10) > 22025.465794806719 || nativeExpm1(10) < 22025.4657948067165168 // Tor Browser bug || nativeExpm1(-2e-17) != -2e-17 ? function expm1(x) { return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } : nativeExpm1; var nativeCosh = Math.cosh; var abs$3 = Math.abs; var E = Math.E; // `Math.cosh` method // https://tc39.github.io/ecma262/#sec-math.cosh _export({ target: 'Math', stat: true, forced: !nativeCosh || nativeCosh(710) === Infinity }, { cosh: function cosh(x) { var t = mathExpm1(abs$3(x) - 1) + 1; return (t + 1 / (t * E * E)) * (E / 2); } }); // https://tc39.github.io/ecma262/#sec-math.expm1 _export({ target: 'Math', stat: true, forced: mathExpm1 != Math.expm1 }, { expm1: mathExpm1 }); var abs$4 = Math.abs; var pow$2 = Math.pow; var EPSILON = pow$2(2, -52); var EPSILON32 = pow$2(2, -23); var MAX32 = pow$2(2, 127) * (2 - EPSILON32); var MIN32 = pow$2(2, -126); var roundTiesToEven = function roundTiesToEven(n) { return n + 1 / EPSILON - 1 / EPSILON; }; // `Math.fround` method implementation // https://tc39.github.io/ecma262/#sec-math.fround var mathFround = Math.fround || function fround(x) { var $abs = abs$4(x); var $sign = mathSign(x); var a, result; if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); // eslint-disable-next-line no-self-compare if (result > MAX32 || result != result) return $sign * Infinity; return $sign * result; }; // https://tc39.github.io/ecma262/#sec-math.fround _export({ target: 'Math', stat: true }, { fround: mathFround }); var $hypot = Math.hypot; var abs$5 = Math.abs; var sqrt$2 = Math.sqrt; // Chrome 77 bug // https://bugs.chromium.org/p/v8/issues/detail?id=9546 var BUGGY = !!$hypot && $hypot(Infinity, NaN) !== Infinity; // `Math.hypot` method // https://tc39.github.io/ecma262/#sec-math.hypot _export({ target: 'Math', stat: true, forced: BUGGY }, { hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars var sum = 0; var i = 0; var aLen = arguments.length; var larg = 0; var arg, div; while (i < aLen) { arg = abs$5(arguments[i++]); if (larg < arg) { div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if (arg > 0) { div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * sqrt$2(sum); } }); var nativeImul = Math.imul; var FORCED$6 = fails(function () { return nativeImul(0xFFFFFFFF, 5) != -5 || nativeImul.length != 2; }); // `Math.imul` method // https://tc39.github.io/ecma262/#sec-math.imul // some WebKit versions fails with big numbers, some has wrong arity _export({ target: 'Math', stat: true, forced: FORCED$6 }, { imul: function imul(x, y) { var UINT16 = 0xFFFF; var xn = +x; var yn = +y; var xl = UINT16 & xn; var yl = UINT16 & yn; return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); } }); var log$6 = Math.log; var LOG10E = Math.LOG10E; // `Math.log10` method // https://tc39.github.io/ecma262/#sec-math.log10 _export({ target: 'Math', stat: true }, { log10: function log10(x) { return log$6(x) * LOG10E; } }); // https://tc39.github.io/ecma262/#sec-math.log1p _export({ target: 'Math', stat: true }, { log1p: mathLog1p }); var log$7 = Math.log; var LN2$2 = Math.LN2; // `Math.log2` method // https://tc39.github.io/ecma262/#sec-math.log2 _export({ target: 'Math', stat: true }, { log2: function log2(x) { return log$7(x) / LN2$2; } }); // https://tc39.github.io/ecma262/#sec-math.sign _export({ target: 'Math', stat: true }, { sign: mathSign }); var abs$6 = Math.abs; var exp$1 = Math.exp; var E$1 = Math.E; var FORCED$7 = fails(function () { return Math.sinh(-2e-17) != -2e-17; }); // `Math.sinh` method // https://tc39.github.io/ecma262/#sec-math.sinh // V8 near Chromium 38 has a problem with very small numbers _export({ target: 'Math', stat: true, forced: FORCED$7 }, { sinh: function sinh(x) { return abs$6(x = +x) < 1 ? (mathExpm1(x) - mathExpm1(-x)) / 2 : (exp$1(x - 1) - exp$1(-x - 1)) * (E$1 / 2); } }); var exp$2 = Math.exp; // `Math.tanh` method // https://tc39.github.io/ecma262/#sec-math.tanh _export({ target: 'Math', stat: true }, { tanh: function tanh(x) { var a = mathExpm1(x = +x); var b = mathExpm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp$2(x) + exp$2(-x)); } }); // https://tc39.github.io/ecma262/#sec-math-@@tostringtag setToStringTag(Math, 'Math', true); var ceil$2 = Math.ceil; var floor$3 = Math.floor; // `Math.trunc` method // https://tc39.github.io/ecma262/#sec-math.trunc _export({ target: 'Math', stat: true }, { trunc: function trunc(it) { return (it > 0 ? floor$3 : ceil$2)(it); } }); // a string of all valid unicode whitespaces // eslint-disable-next-line max-len var whitespaces = "\t\n\x0B\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF"; var whitespace = '[' + whitespaces + ']'; var ltrim = RegExp('^' + whitespace + whitespace + '*'); var rtrim = RegExp(whitespace + whitespace + '*$'); // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation var createMethod$4 = function createMethod(TYPE) { return function ($this) { var string = String(requireObjectCoercible($this)); if (TYPE & 1) string = string.replace(ltrim, ''); if (TYPE & 2) string = string.replace(rtrim, ''); return string; }; }; var stringTrim = { // `String.prototype.{ trimLeft, trimStart }` methods // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart start: createMethod$4(1), // `String.prototype.{ trimRight, trimEnd }` methods // https://tc39.github.io/ecma262/#sec-string.prototype.trimend end: createMethod$4(2), // `String.prototype.trim` method // https://tc39.github.io/ecma262/#sec-string.prototype.trim trim: createMethod$4(3) }; var getOwnPropertyNames$1 = objectGetOwnPropertyNames.f; var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f; var defineProperty$8 = objectDefineProperty.f; var trim = stringTrim.trim; var NUMBER = 'Number'; var NativeNumber = global_1[NUMBER]; var NumberPrototype = NativeNumber.prototype; // Opera ~12 has broken Object#toString var BROKEN_CLASSOF = classofRaw(objectCreate(NumberPrototype)) == NUMBER; // `ToNumber` abstract operation // https://tc39.github.io/ecma262/#sec-tonumber var toNumber = function toNumber(argument) { var it = toPrimitive(argument, false); var first, third, radix, maxCode, digits, length, index, code; if (typeof it == 'string' && it.length > 2) { it = trim(it); first = it.charCodeAt(0); if (first === 43 || first === 45) { third = it.charCodeAt(2); if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix } else if (first === 48) { switch (it.charCodeAt(1)) { case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i default: return +it; } digits = it.slice(2); length = digits.length; for (index = 0; index < length; index++) { code = digits.charCodeAt(index); // parseInt parses a string to a first unavailable symbol // but ToNumber should return NaN if a string contains unavailable symbols if (code < 48 || code > maxCode) return NaN; } return parseInt(digits, radix); } } return +it; }; // `Number` constructor // https://tc39.github.io/ecma262/#sec-number-constructor if (isForced_1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { var NumberWrapper = function Number(value) { var it = arguments.length < 1 ? 0 : value; var dummy = this; return dummy instanceof NumberWrapper // check on 1..constructor(foo) case && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classofRaw(dummy) != NUMBER) ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); }; for (var keys$2 = descriptors ? getOwnPropertyNames$1(NativeNumber) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES2015 (in case, if modules with ES2015 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger').split(','), j$1 = 0, key$1; keys$2.length > j$1; j$1++) { if (has(NativeNumber, key$1 = keys$2[j$1]) && !has(NumberWrapper, key$1)) { defineProperty$8(NumberWrapper, key$1, getOwnPropertyDescriptor$2(NativeNumber, key$1)); } } NumberWrapper.prototype = NumberPrototype; NumberPrototype.constructor = NumberWrapper; redefine(global_1, NUMBER, NumberWrapper); } // https://tc39.github.io/ecma262/#sec-number.epsilon _export({ target: 'Number', stat: true }, { EPSILON: Math.pow(2, -52) }); var globalIsFinite = global_1.isFinite; // `Number.isFinite` method // https://tc39.github.io/ecma262/#sec-number.isfinite var numberIsFinite = Number.isFinite || function isFinite(it) { return typeof it == 'number' && globalIsFinite(it); }; // https://tc39.github.io/ecma262/#sec-number.isfinite _export({ target: 'Number', stat: true }, { isFinite: numberIsFinite }); var floor$4 = Math.floor; // `Number.isInteger` method implementation // https://tc39.github.io/ecma262/#sec-number.isinteger var isInteger = function isInteger(it) { return !isObject(it) && isFinite(it) && floor$4(it) === it; }; // https://tc39.github.io/ecma262/#sec-number.isinteger _export({ target: 'Number', stat: true }, { isInteger: isInteger }); // https://tc39.github.io/ecma262/#sec-number.isnan _export({ target: 'Number', stat: true }, { isNaN: function isNaN(number) { // eslint-disable-next-line no-self-compare return number != number; } }); var abs$7 = Math.abs; // `Number.isSafeInteger` method // https://tc39.github.io/ecma262/#sec-number.issafeinteger _export({ target: 'Number', stat: true }, { isSafeInteger: function isSafeInteger(number) { return isInteger(number) && abs$7(number) <= 0x1FFFFFFFFFFFFF; } }); // https://tc39.github.io/ecma262/#sec-number.max_safe_integer _export({ target: 'Number', stat: true }, { MAX_SAFE_INTEGER: 0x1FFFFFFFFFFFFF }); // https://tc39.github.io/ecma262/#sec-number.min_safe_integer _export({ target: 'Number', stat: true }, { MIN_SAFE_INTEGER: -0x1FFFFFFFFFFFFF }); var trim$1 = stringTrim.trim; var $parseFloat = global_1.parseFloat; var FORCED$8 = 1 / $parseFloat(whitespaces + '-0') !== -Infinity; // `parseFloat` method // https://tc39.github.io/ecma262/#sec-parsefloat-string var numberParseFloat = FORCED$8 ? function parseFloat(string) { var trimmedString = trim$1(String(string)); var result = $parseFloat(trimmedString); return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result; } : $parseFloat; // https://tc39.github.io/ecma262/#sec-number.parseFloat _export({ target: 'Number', stat: true, forced: Number.parseFloat != numberParseFloat }, { parseFloat: numberParseFloat }); var trim$2 = stringTrim.trim; var $parseInt = global_1.parseInt; var hex = /^[+-]?0[Xx]/; var FORCED$9 = $parseInt(whitespaces + '08') !== 8 || $parseInt(whitespaces + '0x16') !== 22; // `parseInt` method // https://tc39.github.io/ecma262/#sec-parseint-string-radix var numberParseInt = FORCED$9 ? function parseInt(string, radix) { var S = trim$2(String(string)); return $parseInt(S, radix >>> 0 || (hex.test(S) ? 16 : 10)); } : $parseInt; // https://tc39.github.io/ecma262/#sec-number.parseint _export({ target: 'Number', stat: true, forced: Number.parseInt != numberParseInt }, { parseInt: numberParseInt }); // https://tc39.github.io/ecma262/#sec-thisnumbervalue var thisNumberValue = function thisNumberValue(value) { if (typeof value != 'number' && classofRaw(value) != 'Number') { throw TypeError('Incorrect invocation'); } return +value; }; var nativeToFixed = 1.0.toFixed; var floor$5 = Math.floor; var pow$3 = function pow(x, n, acc) { return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); }; var log$8 = function log(x) { var n = 0; var x2 = x; while (x2 >= 4096) { n += 12; x2 /= 4096; } while (x2 >= 2) { n += 1; x2 /= 2; } return n; }; var FORCED$a = nativeToFixed && (0.00008.toFixed(3) !== '0.000' || 0.9.toFixed(0) !== '1' || 1.255.toFixed(2) !== '1.25' || 1000000000000000128.0.toFixed(0) !== '1000000000000000128') || !fails(function () { // V8 ~ Android 4.3- nativeToFixed.call({}); }); // `Number.prototype.toFixed` method // https://tc39.github.io/ecma262/#sec-number.prototype.tofixed _export({ target: 'Number', proto: true, forced: FORCED$a }, { // eslint-disable-next-line max-statements toFixed: function toFixed(fractionDigits) { var number = thisNumberValue(this); var fractDigits = toInteger(fractionDigits); var data = [0, 0, 0, 0, 0, 0]; var sign = ''; var result = '0'; var e, z, j, k; var multiply = function multiply(n, c) { var index = -1; var c2 = c; while (++index < 6) { c2 += n * data[index]; data[index] = c2 % 1e7; c2 = floor$5(c2 / 1e7); } }; var divide = function divide(n) { var index = 6; var c = 0; while (--index >= 0) { c += data[index]; data[index] = floor$5(c / n); c = c % n * 1e7; } }; var dataToString = function dataToString() { var index = 6; var s = ''; while (--index >= 0) { if (s !== '' || index === 0 || data[index] !== 0) { var t = String(data[index]); s = s === '' ? t : s + stringRepeat.call('0', 7 - t.length) + t; } } return s; }; if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits'); // eslint-disable-next-line no-self-compare if (number != number) return 'NaN'; if (number <= -1e21 || number >= 1e21) return String(number); if (number < 0) { sign = '-'; number = -number; } if (number > 1e-21) { e = log$8(number * pow$3(2, 69, 1)) - 69; z = e < 0 ? number * pow$3(2, -e, 1) : number / pow$3(2, e, 1); z *= 0x10000000000000; e = 52 - e; if (e > 0) { multiply(0, z); j = fractDigits; while (j >= 7) { multiply(1e7, 0); j -= 7; } multiply(pow$3(10, j, 1), 0); j = e - 1; while (j >= 23) { divide(1 << 23); j -= 23; } divide(1 << j); multiply(1, 1); divide(2); result = dataToString(); } else { multiply(0, z); multiply(1 << -e, 0); result = dataToString() + stringRepeat.call('0', fractDigits); } } if (fractDigits > 0) { k = result.length; result = sign + (k <= fractDigits ? '0.' + stringRepeat.call('0', fractDigits - k) + result : result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits)); } else { result = sign + result; } return result; } }); var nativeToPrecision = 1.0.toPrecision; var FORCED$b = fails(function () { // IE7- return nativeToPrecision.call(1, undefined) !== '1'; }) || !fails(function () { // V8 ~ Android 4.3- nativeToPrecision.call({}); }); // `Number.prototype.toPrecision` method // https://tc39.github.io/ecma262/#sec-number.prototype.toprecision _export({ target: 'Number', proto: true, forced: FORCED$b }, { toPrecision: function toPrecision(precision) { return precision === undefined ? nativeToPrecision.call(thisNumberValue(this)) : nativeToPrecision.call(thisNumberValue(this), precision); } }); var nativeAssign = Object.assign; var defineProperty$9 = Object.defineProperty; // `Object.assign` method // https://tc39.github.io/ecma262/#sec-object.assign var objectAssign = !nativeAssign || fails(function () { // should have correct order of operations (Edge bug) if (descriptors && nativeAssign({ b: 1 }, nativeAssign(defineProperty$9({}, 'a', { enumerable: true, get: function get() { defineProperty$9(this, 'b', { value: 3, enumerable: false }); } }), { b: 2 })).b !== 1) return true; // should work with symbols and should have deterministic property order (V8 bug) var A = {}; var B = {}; // eslint-disable-next-line no-undef var symbol = Symbol(); var alphabet = 'abcdefghijklmnopqrst'; A[symbol] = 7; alphabet.split('').forEach(function (chr) { B[chr] = chr; }); return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet; }) ? function assign(target, source) { // eslint-disable-line no-unused-vars var T = toObject(target); var argumentsLength = arguments.length; var index = 1; var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; var propertyIsEnumerable = objectPropertyIsEnumerable.f; while (argumentsLength > index) { var S = indexedObject(arguments[index++]); var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S); var length = keys.length; var j = 0; var key; while (length > j) { key = keys[j++]; if (!descriptors || propertyIsEnumerable.call(S, key)) T[key] = S[key]; } } return T; } : nativeAssign; // https://tc39.github.io/ecma262/#sec-object.assign _export({ target: 'Object', stat: true, forced: Object.assign !== objectAssign }, { assign: objectAssign }); // https://tc39.github.io/ecma262/#sec-object.create _export({ target: 'Object', stat: true, sham: !descriptors }, { create: objectCreate }); var objectPrototypeAccessorsForced = !fails(function () { var key = Math.random(); // In FF throws only define methods // eslint-disable-next-line no-undef, no-useless-call __defineSetter__.call(null, key, function () { /* empty */ }); delete global_1[key]; }); // https://tc39.github.io/ecma262/#sec-object.prototype.__defineGetter__ if (descriptors) { _export({ target: 'Object', proto: true, forced: objectPrototypeAccessorsForced }, { __defineGetter__: function __defineGetter__(P, getter) { objectDefineProperty.f(toObject(this), P, { get: aFunction$1(getter), enumerable: true, configurable: true }); } }); } // https://tc39.github.io/ecma262/#sec-object.defineproperties _export({ target: 'Object', stat: true, forced: !descriptors, sham: !descriptors }, { defineProperties: objectDefineProperties }); // https://tc39.github.io/ecma262/#sec-object.defineproperty _export({ target: 'Object', stat: true, forced: !descriptors, sham: !descriptors }, { defineProperty: objectDefineProperty.f }); // https://tc39.github.io/ecma262/#sec-object.prototype.__defineSetter__ if (descriptors) { _export({ target: 'Object', proto: true, forced: objectPrototypeAccessorsForced }, { __defineSetter__: function __defineSetter__(P, setter) { objectDefineProperty.f(toObject(this), P, { set: aFunction$1(setter), enumerable: true, configurable: true }); } }); } var propertyIsEnumerable = objectPropertyIsEnumerable.f; // `Object.{ entries, values }` methods implementation var createMethod$5 = function createMethod(TO_ENTRIES) { return function (it) { var O = toIndexedObject(it); var keys = objectKeys(O); var length = keys.length; var i = 0; var result = []; var key; while (length > i) { key = keys[i++]; if (!descriptors || propertyIsEnumerable.call(O, key)) { result.push(TO_ENTRIES ? [key, O[key]] : O[key]); } } return result; }; }; var objectToArray = { // `Object.entries` method // https://tc39.github.io/ecma262/#sec-object.entries entries: createMethod$5(true), // `Object.values` method // https://tc39.github.io/ecma262/#sec-object.values values: createMethod$5(false) }; var $entries = objectToArray.entries; // `Object.entries` method // https://tc39.github.io/ecma262/#sec-object.entries _export({ target: 'Object', stat: true }, { entries: function entries(O) { return $entries(O); } }); var onFreeze = internalMetadata.onFreeze; var nativeFreeze = Object.freeze; var FAILS_ON_PRIMITIVES = fails(function () { nativeFreeze(1); }); // `Object.freeze` method // https://tc39.github.io/ecma262/#sec-object.freeze _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !freezing }, { freeze: function freeze(it) { return nativeFreeze && isObject(it) ? nativeFreeze(onFreeze(it)) : it; } }); // https://github.com/tc39/proposal-object-from-entries _export({ target: 'Object', stat: true }, { fromEntries: function fromEntries(iterable) { var obj = {}; iterate_1(iterable, function (k, v) { createProperty(obj, k, v); }, undefined, true); return obj; } }); var nativeGetOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f; var FAILS_ON_PRIMITIVES$1 = fails(function () { nativeGetOwnPropertyDescriptor$2(1); }); var FORCED$c = !descriptors || FAILS_ON_PRIMITIVES$1; // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor _export({ target: 'Object', stat: true, forced: FORCED$c, sham: !descriptors }, { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) { return nativeGetOwnPropertyDescriptor$2(toIndexedObject(it), key); } }); // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors _export({ target: 'Object', stat: true, sham: !descriptors }, { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { var O = toIndexedObject(object); var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; var keys = ownKeys(O); var result = {}; var index = 0; var key, descriptor; while (keys.length > index) { descriptor = getOwnPropertyDescriptor(O, key = keys[index++]); if (descriptor !== undefined) createProperty(result, key, descriptor); } return result; } }); var nativeGetOwnPropertyNames$2 = objectGetOwnPropertyNamesExternal.f; var FAILS_ON_PRIMITIVES$2 = fails(function () { return !Object.getOwnPropertyNames(1); }); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$2 }, { getOwnPropertyNames: nativeGetOwnPropertyNames$2 }); var FAILS_ON_PRIMITIVES$3 = fails(function () { objectGetPrototypeOf(1); }); // `Object.getPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.getprototypeof _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$3, sham: !correctPrototypeGetter }, { getPrototypeOf: function getPrototypeOf(it) { return objectGetPrototypeOf(toObject(it)); } }); // `SameValue` abstract operation // https://tc39.github.io/ecma262/#sec-samevalue var sameValue = Object.is || function is(x, y) { // eslint-disable-next-line no-self-compare return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; // https://tc39.github.io/ecma262/#sec-object.is _export({ target: 'Object', stat: true }, { is: sameValue }); var nativeIsExtensible = Object.isExtensible; var FAILS_ON_PRIMITIVES$4 = fails(function () { nativeIsExtensible(1); }); // `Object.isExtensible` method // https://tc39.github.io/ecma262/#sec-object.isextensible _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$4 }, { isExtensible: function isExtensible(it) { return isObject(it) ? nativeIsExtensible ? nativeIsExtensible(it) : true : false; } }); var nativeIsFrozen = Object.isFrozen; var FAILS_ON_PRIMITIVES$5 = fails(function () { nativeIsFrozen(1); }); // `Object.isFrozen` method // https://tc39.github.io/ecma262/#sec-object.isfrozen _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$5 }, { isFrozen: function isFrozen(it) { return isObject(it) ? nativeIsFrozen ? nativeIsFrozen(it) : false : true; } }); var nativeIsSealed = Object.isSealed; var FAILS_ON_PRIMITIVES$6 = fails(function () { nativeIsSealed(1); }); // `Object.isSealed` method // https://tc39.github.io/ecma262/#sec-object.issealed _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$6 }, { isSealed: function isSealed(it) { return isObject(it) ? nativeIsSealed ? nativeIsSealed(it) : false : true; } }); var FAILS_ON_PRIMITIVES$7 = fails(function () { objectKeys(1); }); // `Object.keys` method // https://tc39.github.io/ecma262/#sec-object.keys _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$7 }, { keys: function keys(it) { return objectKeys(toObject(it)); } }); var getOwnPropertyDescriptor$3 = objectGetOwnPropertyDescriptor.f; // `Object.prototype.__lookupGetter__` method // https://tc39.github.io/ecma262/#sec-object.prototype.__lookupGetter__ if (descriptors) { _export({ target: 'Object', proto: true, forced: objectPrototypeAccessorsForced }, { __lookupGetter__: function __lookupGetter__(P) { var O = toObject(this); var key = toPrimitive(P, true); var desc; do { if (desc = getOwnPropertyDescriptor$3(O, key)) return desc.get; } while (O = objectGetPrototypeOf(O)); } }); } var getOwnPropertyDescriptor$4 = objectGetOwnPropertyDescriptor.f; // `Object.prototype.__lookupSetter__` method // https://tc39.github.io/ecma262/#sec-object.prototype.__lookupSetter__ if (descriptors) { _export({ target: 'Object', proto: true, forced: objectPrototypeAccessorsForced }, { __lookupSetter__: function __lookupSetter__(P) { var O = toObject(this); var key = toPrimitive(P, true); var desc; do { if (desc = getOwnPropertyDescriptor$4(O, key)) return desc.set; } while (O = objectGetPrototypeOf(O)); } }); } var onFreeze$1 = internalMetadata.onFreeze; var nativePreventExtensions = Object.preventExtensions; var FAILS_ON_PRIMITIVES$8 = fails(function () { nativePreventExtensions(1); }); // `Object.preventExtensions` method // https://tc39.github.io/ecma262/#sec-object.preventextensions _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$8, sham: !freezing }, { preventExtensions: function preventExtensions(it) { return nativePreventExtensions && isObject(it) ? nativePreventExtensions(onFreeze$1(it)) : it; } }); var onFreeze$2 = internalMetadata.onFreeze; var nativeSeal = Object.seal; var FAILS_ON_PRIMITIVES$9 = fails(function () { nativeSeal(1); }); // `Object.seal` method // https://tc39.github.io/ecma262/#sec-object.seal _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$9, sham: !freezing }, { seal: function seal(it) { return nativeSeal && isObject(it) ? nativeSeal(onFreeze$2(it)) : it; } }); // https://tc39.github.io/ecma262/#sec-object.setprototypeof _export({ target: 'Object', stat: true }, { setPrototypeOf: objectSetPrototypeOf }); // https://tc39.github.io/ecma262/#sec-object.prototype.tostring var objectToString = toStringTagSupport ? {}.toString : function toString() { return '[object ' + classof(this) + ']'; }; // https://tc39.github.io/ecma262/#sec-object.prototype.tostring if (!toStringTagSupport) { redefine(Object.prototype, 'toString', objectToString, { unsafe: true }); } var $values = objectToArray.values; // `Object.values` method // https://tc39.github.io/ecma262/#sec-object.values _export({ target: 'Object', stat: true }, { values: function values(O) { return $values(O); } }); // https://tc39.github.io/ecma262/#sec-parsefloat-string _export({ global: true, forced: parseFloat != numberParseFloat }, { parseFloat: numberParseFloat }); // https://tc39.github.io/ecma262/#sec-parseint-string-radix _export({ global: true, forced: parseInt != numberParseInt }, { parseInt: numberParseInt }); var nativePromiseConstructor = global_1.Promise; var engineIsIos = /(iphone|ipod|ipad).*applewebkit/i.test(engineUserAgent); var location$1 = global_1.location; var set$2 = global_1.setImmediate; var clear = global_1.clearImmediate; var process$1 = global_1.process; var MessageChannel = global_1.MessageChannel; var Dispatch = global_1.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function run(id) { // eslint-disable-next-line no-prototype-builtins if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var runner = function runner(id) { return function () { run(id); }; }; var listener = function listener(event) { run(event.data); }; var post = function post(id) { // old engines have not location.origin global_1.postMessage(id + '', location$1.protocol + '//' + location$1.host); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!set$2 || !clear) { set$2 = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) { args.push(arguments[i++]); } queue[++counter] = function () { // eslint-disable-next-line no-new-func (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args); }; defer(counter); return counter; }; clear = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (classofRaw(process$1) == 'process') { defer = function defer(id) { process$1.nextTick(runner(id)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function defer(id) { Dispatch.now(runner(id)); }; // Browsers with MessageChannel, includes WebWorkers // except iOS - https://github.com/zloirock/core-js/issues/624 } else if (MessageChannel && !engineIsIos) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = functionBindContext(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global_1.addEventListener && typeof postMessage == 'function' && !global_1.importScripts && !fails(post) && location$1.protocol !== 'file:') { defer = post; global_1.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in documentCreateElement('script')) { defer = function defer(id) { html.appendChild(documentCreateElement('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run(id); }; }; // Rest old browsers } else { defer = function defer(id) { setTimeout(runner(id), 0); }; } } var task = { set: set$2, clear: clear }; var getOwnPropertyDescriptor$5 = objectGetOwnPropertyDescriptor.f; var macrotask = task.set; var MutationObserver$1 = global_1.MutationObserver || global_1.WebKitMutationObserver; var process$2 = global_1.process; var Promise$1 = global_1.Promise; var IS_NODE = classofRaw(process$2) == 'process'; // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` var queueMicrotaskDescriptor = getOwnPropertyDescriptor$5(global_1, 'queueMicrotask'); var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value; var flush, head, last, notify, toggle, node, promise, then; // modern engines have queueMicrotask method if (!queueMicrotask) { flush = function flush() { var parent, fn; if (IS_NODE && (parent = process$2.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (error) { if (head) notify();else last = undefined; throw error; } } last = undefined; if (parent) parent.enter(); }; // Node.js if (IS_NODE) { notify = function notify() { process$2.nextTick(flush); }; // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 } else if (MutationObserver$1 && !engineIsIos) { toggle = true; node = document.createTextNode(''); new MutationObserver$1(flush).observe(node, { characterData: true }); notify = function notify() { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (Promise$1 && Promise$1.resolve) { // Promise.resolve without an argument throws an error in LG WebOS 2 promise = Promise$1.resolve(undefined); then = promise.then; notify = function notify() { then.call(promise, flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function notify() { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global_1, flush); }; } } var microtask = queueMicrotask || function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; var PromiseCapability = function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction$1(resolve); this.reject = aFunction$1(reject); }; // 25.4.1.5 NewPromiseCapability(C) var f$7 = function f(C) { return new PromiseCapability(C); }; var newPromiseCapability = { f: f$7 }; var promiseResolve = function promiseResolve(C, x) { anObject(C); if (isObject(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; var hostReportErrors = function hostReportErrors(a, b) { var console = global_1.console; if (console && console.error) { arguments.length === 1 ? console.error(a) : console.error(a, b); } }; var perform = function perform(exec) { try { return { error: false, value: exec() }; } catch (error) { return { error: true, value: error }; } }; var task$1 = task.set; var SPECIES$5 = wellKnownSymbol('species'); var PROMISE = 'Promise'; var getInternalState$3 = internalState.get; var setInternalState$4 = internalState.set; var getInternalPromiseState = internalState.getterFor(PROMISE); var PromiseConstructor = nativePromiseConstructor; var TypeError$1 = global_1.TypeError; var document$2 = global_1.document; var process$3 = global_1.process; var $fetch = getBuiltIn('fetch'); var newPromiseCapability$1 = newPromiseCapability.f; var newGenericPromiseCapability = newPromiseCapability$1; var IS_NODE$1 = classofRaw(process$3) == 'process'; var DISPATCH_EVENT = !!(document$2 && document$2.createEvent && global_1.dispatchEvent); var UNHANDLED_REJECTION = 'unhandledrejection'; var REJECTION_HANDLED = 'rejectionhandled'; var PENDING = 0; var FULFILLED = 1; var REJECTED = 2; var HANDLED = 1; var UNHANDLED = 2; var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen; var FORCED$d = isForced_1(PROMISE, function () { var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor); if (!GLOBAL_CORE_JS_PROMISE) { // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 // We can't detect it synchronously, so just check versions if (engineV8Version === 66) return true; // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test if (!IS_NODE$1 && typeof PromiseRejectionEvent != 'function') return true; } // We need Promise#finally in the pure version for preventing prototype pollution // deoptimization and performance degradation // https://github.com/zloirock/core-js/issues/679 if (engineV8Version >= 51 && /native code/.test(PromiseConstructor)) return false; // Detect correctness of subclassing with @@species support var promise = PromiseConstructor.resolve(1); var FakePromise = function FakePromise(exec) { exec(function () { /* empty */ }, function () { /* empty */ }); }; var constructor = promise.constructor = {}; constructor[SPECIES$5] = FakePromise; return !(promise.then(function () { /* empty */ }) instanceof FakePromise); }); var INCORRECT_ITERATION$1 = FORCED$d || !checkCorrectnessOfIteration(function (iterable) { PromiseConstructor.all(iterable)['catch'](function () { /* empty */ }); }); // helpers var isThenable = function isThenable(it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify$1 = function notify(promise, state, isReject) { if (state.notified) return; state.notified = true; var chain = state.reactions; microtask(function () { var value = state.value; var ok = state.state == FULFILLED; var index = 0; // variable length - can't use forEach while (chain.length > index) { var reaction = chain[index++]; var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then, exited; try { if (handler) { if (!ok) { if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state); state.rejection = HANDLED; } if (handler === true) result = value;else { if (domain) domain.enter(); result = handler(value); // can throw if (domain) { domain.exit(); exited = true; } } if (result === reaction.promise) { reject(TypeError$1('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (error) { if (domain && !exited) domain.exit(); reject(error); } } state.reactions = []; state.notified = false; if (isReject && !state.rejection) onUnhandled(promise, state); }); }; var dispatchEvent = function dispatchEvent(name, promise, reason) { var event, handler; if (DISPATCH_EVENT) { event = document$2.createEvent('Event'); event.promise = promise; event.reason = reason; event.initEvent(name, false, true); global_1.dispatchEvent(event); } else event = { promise: promise, reason: reason }; if (handler = global_1['on' + name]) handler(event);else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason); }; var onUnhandled = function onUnhandled(promise, state) { task$1.call(global_1, function () { var value = state.value; var IS_UNHANDLED = isUnhandled(state); var result; if (IS_UNHANDLED) { result = perform(function () { if (IS_NODE$1) { process$3.emit('unhandledRejection', value, promise); } else dispatchEvent(UNHANDLED_REJECTION, promise, value); }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should state.rejection = IS_NODE$1 || isUnhandled(state) ? UNHANDLED : HANDLED; if (result.error) throw result.value; } }); }; var isUnhandled = function isUnhandled(state) { return state.rejection !== HANDLED && !state.parent; }; var onHandleUnhandled = function onHandleUnhandled(promise, state) { task$1.call(global_1, function () { if (IS_NODE$1) { process$3.emit('rejectionHandled', promise); } else dispatchEvent(REJECTION_HANDLED, promise, state.value); }); }; var bind = function bind(fn, promise, state, unwrap) { return function (value) { fn(promise, state, value, unwrap); }; }; var internalReject = function internalReject(promise, state, value, unwrap) { if (state.done) return; state.done = true; if (unwrap) state = unwrap; state.value = value; state.state = REJECTED; notify$1(promise, state, true); }; var internalResolve = function internalResolve(promise, state, value, unwrap) { if (state.done) return; state.done = true; if (unwrap) state = unwrap; try { if (promise === value) throw TypeError$1("Promise can't be resolved itself"); var then = isThenable(value); if (then) { microtask(function () { var wrapper = { done: false }; try { then.call(value, bind(internalResolve, promise, wrapper, state), bind(internalReject, promise, wrapper, state)); } catch (error) { internalReject(promise, wrapper, error, state); } }); } else { state.value = value; state.state = FULFILLED; notify$1(promise, state, false); } } catch (error) { internalReject(promise, { done: false }, error, state); } }; // constructor polyfill if (FORCED$d) { // 25.4.3.1 Promise(executor) PromiseConstructor = function Promise(executor) { anInstance(this, PromiseConstructor, PROMISE); aFunction$1(executor); Internal.call(this); var state = getInternalState$3(this); try { executor(bind(internalResolve, this, state), bind(internalReject, this, state)); } catch (error) { internalReject(this, state, error); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { setInternalState$4(this, { type: PROMISE, done: false, notified: false, parent: false, reactions: [], rejection: false, state: PENDING, value: undefined }); }; Internal.prototype = redefineAll(PromiseConstructor.prototype, { // `Promise.prototype.then` method // https://tc39.github.io/ecma262/#sec-promise.prototype.then then: function then(onFulfilled, onRejected) { var state = getInternalPromiseState(this); var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = IS_NODE$1 ? process$3.domain : undefined; state.parent = true; state.reactions.push(reaction); if (state.state != PENDING) notify$1(this, state, false); return reaction.promise; }, // `Promise.prototype.catch` method // https://tc39.github.io/ecma262/#sec-promise.prototype.catch 'catch': function _catch(onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function OwnPromiseCapability() { var promise = new Internal(); var state = getInternalState$3(promise); this.promise = promise; this.resolve = bind(internalResolve, promise, state); this.reject = bind(internalReject, promise, state); }; newPromiseCapability.f = newPromiseCapability$1 = function newPromiseCapability(C) { return C === PromiseConstructor || C === PromiseWrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; if ( typeof nativePromiseConstructor == 'function') { nativeThen = nativePromiseConstructor.prototype.then; // wrap native Promise#then for native async functions redefine(nativePromiseConstructor.prototype, 'then', function then(onFulfilled, onRejected) { var that = this; return new PromiseConstructor(function (resolve, reject) { nativeThen.call(that, resolve, reject); }).then(onFulfilled, onRejected); // https://github.com/zloirock/core-js/issues/640 }, { unsafe: true }); // wrap fetch result if (typeof $fetch == 'function') _export({ global: true, enumerable: true, forced: true }, { // eslint-disable-next-line no-unused-vars fetch: function fetch(input /* , init */ ) { return promiseResolve(PromiseConstructor, $fetch.apply(global_1, arguments)); } }); } } _export({ global: true, wrap: true, forced: FORCED$d }, { Promise: PromiseConstructor }); setToStringTag(PromiseConstructor, PROMISE, false); setSpecies(PROMISE); PromiseWrapper = getBuiltIn(PROMISE); // statics _export({ target: PROMISE, stat: true, forced: FORCED$d }, { // `Promise.reject` method // https://tc39.github.io/ecma262/#sec-promise.reject reject: function reject(r) { var capability = newPromiseCapability$1(this); capability.reject.call(undefined, r); return capability.promise; } }); _export({ target: PROMISE, stat: true, forced: FORCED$d }, { // `Promise.resolve` method // https://tc39.github.io/ecma262/#sec-promise.resolve resolve: function resolve(x) { return promiseResolve( this, x); } }); _export({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION$1 }, { // `Promise.all` method // https://tc39.github.io/ecma262/#sec-promise.all all: function all(iterable) { var C = this; var capability = newPromiseCapability$1(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var $promiseResolve = aFunction$1(C.resolve); var values = []; var counter = 0; var remaining = 1; iterate_1(iterable, function (promise) { var index = counter++; var alreadyCalled = false; values.push(undefined); remaining++; $promiseResolve.call(C, promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.error) reject(result.value); return capability.promise; }, // `Promise.race` method // https://tc39.github.io/ecma262/#sec-promise.race race: function race(iterable) { var C = this; var capability = newPromiseCapability$1(C); var reject = capability.reject; var result = perform(function () { var $promiseResolve = aFunction$1(C.resolve); iterate_1(iterable, function (promise) { $promiseResolve.call(C, promise).then(capability.resolve, reject); }); }); if (result.error) reject(result.value); return capability.promise; } }); // https://github.com/tc39/proposal-promise-allSettled _export({ target: 'Promise', stat: true }, { allSettled: function allSettled(iterable) { var C = this; var capability = newPromiseCapability.f(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var promiseResolve = aFunction$1(C.resolve); var values = []; var counter = 0; var remaining = 1; iterate_1(iterable, function (promise) { var index = counter++; var alreadyCalled = false; values.push(undefined); remaining++; promiseResolve.call(C, promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[index] = { status: 'fulfilled', value: value }; --remaining || resolve(values); }, function (e) { if (alreadyCalled) return; alreadyCalled = true; values[index] = { status: 'rejected', reason: e }; --remaining || resolve(values); }); }); --remaining || resolve(values); }); if (result.error) reject(result.value); return capability.promise; } }); var NON_GENERIC = !!nativePromiseConstructor && fails(function () { nativePromiseConstructor.prototype['finally'].call({ then: function then() { /* empty */ } }, function () { /* empty */ }); }); // `Promise.prototype.finally` method // https://tc39.github.io/ecma262/#sec-promise.prototype.finally _export({ target: 'Promise', proto: true, real: true, forced: NON_GENERIC }, { 'finally': function _finally(onFinally) { var C = speciesConstructor(this, getBuiltIn('Promise')); var isFunction = typeof onFinally == 'function'; return this.then(isFunction ? function (x) { return promiseResolve(C, onFinally()).then(function () { return x; }); } : onFinally, isFunction ? function (e) { return promiseResolve(C, onFinally()).then(function () { throw e; }); } : onFinally); } }); // patch native Promise.prototype for native async functions if ( typeof nativePromiseConstructor == 'function' && !nativePromiseConstructor.prototype['finally']) { redefine(nativePromiseConstructor.prototype, 'finally', getBuiltIn('Promise').prototype['finally']); } var nativeApply = getBuiltIn('Reflect', 'apply'); var functionApply = Function.apply; // MS Edge argumentsList argument is optional var OPTIONAL_ARGUMENTS_LIST = !fails(function () { nativeApply(function () { /* empty */ }); }); // `Reflect.apply` method // https://tc39.github.io/ecma262/#sec-reflect.apply _export({ target: 'Reflect', stat: true, forced: OPTIONAL_ARGUMENTS_LIST }, { apply: function apply(target, thisArgument, argumentsList) { aFunction$1(target); anObject(argumentsList); return nativeApply ? nativeApply(target, thisArgument, argumentsList) : functionApply.call(target, thisArgument, argumentsList); } }); var nativeConstruct = getBuiltIn('Reflect', 'construct'); // `Reflect.construct` method // https://tc39.github.io/ecma262/#sec-reflect.construct // MS Edge supports only 2 arguments and argumentsList argument is optional // FF Nightly sets third argument as `new.target`, but does not create `this` from it var NEW_TARGET_BUG = fails(function () { function F() { /* empty */ } return !(nativeConstruct(function () { /* empty */ }, [], F) instanceof F); }); var ARGS_BUG = !fails(function () { nativeConstruct(function () { /* empty */ }); }); var FORCED$e = NEW_TARGET_BUG || ARGS_BUG; _export({ target: 'Reflect', stat: true, forced: FORCED$e, sham: FORCED$e }, { construct: function construct(Target, args /* , newTarget */ ) { aFunction$1(Target); anObject(args); var newTarget = arguments.length < 3 ? Target : aFunction$1(arguments[2]); if (ARGS_BUG && !NEW_TARGET_BUG) return nativeConstruct(Target, args, newTarget); if (Target == newTarget) { // w/o altered newTarget, optimization for 0-4 arguments switch (args.length) { case 0: return new Target(); case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (functionBind.apply(Target, $args))(); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype; var instance = objectCreate(isObject(proto) ? proto : Object.prototype); var result = Function.apply.call(Target, instance, args); return isObject(result) ? result : instance; } }); var ERROR_INSTEAD_OF_FALSE = fails(function () { // eslint-disable-next-line no-undef Reflect.defineProperty(objectDefineProperty.f({}, 1, { value: 1 }), 1, { value: 2 }); }); // `Reflect.defineProperty` method // https://tc39.github.io/ecma262/#sec-reflect.defineproperty _export({ target: 'Reflect', stat: true, forced: ERROR_INSTEAD_OF_FALSE, sham: !descriptors }, { defineProperty: function defineProperty(target, propertyKey, attributes) { anObject(target); var key = toPrimitive(propertyKey, true); anObject(attributes); try { objectDefineProperty.f(target, key, attributes); return true; } catch (error) { return false; } } }); var getOwnPropertyDescriptor$6 = objectGetOwnPropertyDescriptor.f; // `Reflect.deleteProperty` method // https://tc39.github.io/ecma262/#sec-reflect.deleteproperty _export({ target: 'Reflect', stat: true }, { deleteProperty: function deleteProperty(target, propertyKey) { var descriptor = getOwnPropertyDescriptor$6(anObject(target), propertyKey); return descriptor && !descriptor.configurable ? false : delete target[propertyKey]; } }); // https://tc39.github.io/ecma262/#sec-reflect.get function get$2(target, propertyKey /* , receiver */ ) { var receiver = arguments.length < 3 ? target : arguments[2]; var descriptor, prototype; if (anObject(target) === receiver) return target[propertyKey]; if (descriptor = objectGetOwnPropertyDescriptor.f(target, propertyKey)) return has(descriptor, 'value') ? descriptor.value : descriptor.get === undefined ? undefined : descriptor.get.call(receiver); if (isObject(prototype = objectGetPrototypeOf(target))) return get$2(prototype, propertyKey, receiver); } _export({ target: 'Reflect', stat: true }, { get: get$2 }); // https://tc39.github.io/ecma262/#sec-reflect.getownpropertydescriptor _export({ target: 'Reflect', stat: true, sham: !descriptors }, { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { return objectGetOwnPropertyDescriptor.f(anObject(target), propertyKey); } }); // https://tc39.github.io/ecma262/#sec-reflect.getprototypeof _export({ target: 'Reflect', stat: true, sham: !correctPrototypeGetter }, { getPrototypeOf: function getPrototypeOf(target) { return objectGetPrototypeOf(anObject(target)); } }); // https://tc39.github.io/ecma262/#sec-reflect.has _export({ target: 'Reflect', stat: true }, { has: function has(target, propertyKey) { return propertyKey in target; } }); var objectIsExtensible = Object.isExtensible; // `Reflect.isExtensible` method // https://tc39.github.io/ecma262/#sec-reflect.isextensible _export({ target: 'Reflect', stat: true }, { isExtensible: function isExtensible(target) { anObject(target); return objectIsExtensible ? objectIsExtensible(target) : true; } }); // https://tc39.github.io/ecma262/#sec-reflect.ownkeys _export({ target: 'Reflect', stat: true }, { ownKeys: ownKeys }); // https://tc39.github.io/ecma262/#sec-reflect.preventextensions _export({ target: 'Reflect', stat: true, sham: !freezing }, { preventExtensions: function preventExtensions(target) { anObject(target); try { var objectPreventExtensions = getBuiltIn('Object', 'preventExtensions'); if (objectPreventExtensions) objectPreventExtensions(target); return true; } catch (error) { return false; } } }); // https://tc39.github.io/ecma262/#sec-reflect.set function set$3(target, propertyKey, V /* , receiver */ ) { var receiver = arguments.length < 4 ? target : arguments[3]; var ownDescriptor = objectGetOwnPropertyDescriptor.f(anObject(target), propertyKey); var existingDescriptor, prototype; if (!ownDescriptor) { if (isObject(prototype = objectGetPrototypeOf(target))) { return set$3(prototype, propertyKey, V, receiver); } ownDescriptor = createPropertyDescriptor(0); } if (has(ownDescriptor, 'value')) { if (ownDescriptor.writable === false || !isObject(receiver)) return false; if (existingDescriptor = objectGetOwnPropertyDescriptor.f(receiver, propertyKey)) { if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; existingDescriptor.value = V; objectDefineProperty.f(receiver, propertyKey, existingDescriptor); } else objectDefineProperty.f(receiver, propertyKey, createPropertyDescriptor(0, V)); return true; } return ownDescriptor.set === undefined ? false : (ownDescriptor.set.call(receiver, V), true); } // MS Edge 17-18 Reflect.set allows setting the property to object // with non-writable property on the prototype var MS_EDGE_BUG = fails(function () { var object = objectDefineProperty.f({}, 'a', { configurable: true }); // eslint-disable-next-line no-undef return Reflect.set(objectGetPrototypeOf(object), 'a', 1, object) !== false; }); _export({ target: 'Reflect', stat: true, forced: MS_EDGE_BUG }, { set: set$3 }); // https://tc39.github.io/ecma262/#sec-reflect.setprototypeof if (objectSetPrototypeOf) _export({ target: 'Reflect', stat: true }, { setPrototypeOf: function setPrototypeOf(target, proto) { anObject(target); aPossiblePrototype(proto); try { objectSetPrototypeOf(target, proto); return true; } catch (error) { return false; } } }); var MATCH = wellKnownSymbol('match'); // `IsRegExp` abstract operation // https://tc39.github.io/ecma262/#sec-isregexp var isRegexp = function isRegexp(it) { var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp'); }; // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags var regexpFlags = function regexpFlags() { var that = anObject(this); var result = ''; if (that.global) result += 'g'; if (that.ignoreCase) result += 'i'; if (that.multiline) result += 'm'; if (that.dotAll) result += 's'; if (that.unicode) result += 'u'; if (that.sticky) result += 'y'; return result; }; // so we use an intermediate function. function RE(s, f) { return RegExp(s, f); } var UNSUPPORTED_Y = fails(function () { // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError var re = RE('a', 'y'); re.lastIndex = 2; return re.exec('abcd') != null; }); var BROKEN_CARET = fails(function () { // https://bugzilla.mozilla.org/show_bug.cgi?id=773687 var re = RE('^r', 'gy'); re.lastIndex = 2; return re.exec('str') != null; }); var regexpStickyHelpers = { UNSUPPORTED_Y: UNSUPPORTED_Y, BROKEN_CARET: BROKEN_CARET }; var defineProperty$a = objectDefineProperty.f; var getOwnPropertyNames$2 = objectGetOwnPropertyNames.f; var setInternalState$5 = internalState.set; var MATCH$1 = wellKnownSymbol('match'); var NativeRegExp = global_1.RegExp; var RegExpPrototype = NativeRegExp.prototype; var re1 = /a/g; var re2 = /a/g; // "new" should create a new object, old webkit bug var CORRECT_NEW = new NativeRegExp(re1) !== re1; var UNSUPPORTED_Y$1 = regexpStickyHelpers.UNSUPPORTED_Y; var FORCED$f = descriptors && isForced_1('RegExp', !CORRECT_NEW || UNSUPPORTED_Y$1 || fails(function () { re2[MATCH$1] = false; // RegExp constructor can alter flags and IsRegExp works correct with @@match return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i'; })); // `RegExp` constructor // https://tc39.github.io/ecma262/#sec-regexp-constructor if (FORCED$f) { var RegExpWrapper = function RegExp(pattern, flags) { var thisIsRegExp = this instanceof RegExpWrapper; var patternIsRegExp = isRegexp(pattern); var flagsAreUndefined = flags === undefined; var sticky; if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) { return pattern; } if (CORRECT_NEW) { if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source; } else if (pattern instanceof RegExpWrapper) { if (flagsAreUndefined) flags = regexpFlags.call(pattern); pattern = pattern.source; } if (UNSUPPORTED_Y$1) { sticky = !!flags && flags.indexOf('y') > -1; if (sticky) flags = flags.replace(/y/g, ''); } var result = inheritIfRequired(CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags), thisIsRegExp ? this : RegExpPrototype, RegExpWrapper); if (UNSUPPORTED_Y$1 && sticky) setInternalState$5(result, { sticky: sticky }); return result; }; var proxy = function proxy(key) { key in RegExpWrapper || defineProperty$a(RegExpWrapper, key, { configurable: true, get: function get() { return NativeRegExp[key]; }, set: function set(it) { NativeRegExp[key] = it; } }); }; var keys$3 = getOwnPropertyNames$2(NativeRegExp); var index = 0; while (keys$3.length > index) { proxy(keys$3[index++]); } RegExpPrototype.constructor = RegExpWrapper; RegExpWrapper.prototype = RegExpPrototype; redefine(global_1, 'RegExp', RegExpWrapper); } // https://tc39.github.io/ecma262/#sec-get-regexp-@@species setSpecies('RegExp'); var nativeExec = RegExp.prototype.exec; // This always refers to the native implementation, because the // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, // which loads this file before patching the method. var nativeReplace = String.prototype.replace; var patchedExec = nativeExec; var UPDATES_LAST_INDEX_WRONG = function () { var re1 = /a/; var re2 = /b*/g; nativeExec.call(re1, 'a'); nativeExec.call(re2, 'a'); return re1.lastIndex !== 0 || re2.lastIndex !== 0; }(); var UNSUPPORTED_Y$2 = regexpStickyHelpers.UNSUPPORTED_Y || regexpStickyHelpers.BROKEN_CARET; // nonparticipating capturing group, copied from es5-shim's String#split patch. var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$2; if (PATCH) { patchedExec = function exec(str) { var re = this; var lastIndex, reCopy, match, i; var sticky = UNSUPPORTED_Y$2 && re.sticky; var flags = regexpFlags.call(re); var source = re.source; var charsAdded = 0; var strCopy = str; if (sticky) { flags = flags.replace('y', ''); if (flags.indexOf('g') === -1) { flags += 'g'; } strCopy = String(str).slice(re.lastIndex); // Support anchored sticky behavior. if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\n')) { source = '(?: ' + source + ')'; strCopy = ' ' + strCopy; charsAdded++; } // ^(? + rx + ) is needed, in combination with some str slicing, to // simulate the 'y' flag. reCopy = new RegExp('^(?:' + source + ')', flags); } if (NPCG_INCLUDED) { reCopy = new RegExp('^' + source + '$(?!\\s)', flags); } if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; match = nativeExec.call(sticky ? reCopy : re, strCopy); if (sticky) { if (match) { match.input = match.input.slice(charsAdded); match[0] = match[0].slice(charsAdded); match.index = re.lastIndex; re.lastIndex += match[0].length; } else re.lastIndex = 0; } else if (UPDATES_LAST_INDEX_WRONG && match) { re.lastIndex = re.global ? match.index + match[0].length : lastIndex; } if (NPCG_INCLUDED && match && match.length > 1) { // Fix browsers whose `exec` methods don't consistently return `undefined` // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ nativeReplace.call(match[0], reCopy, function () { for (i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undefined) match[i] = undefined; } }); } return match; }; } var regexpExec = patchedExec; _export({ target: 'RegExp', proto: true, forced: /./.exec !== regexpExec }, { exec: regexpExec }); var UNSUPPORTED_Y$3 = regexpStickyHelpers.UNSUPPORTED_Y; // `RegExp.prototype.flags` getter // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags if (descriptors && (/./g.flags != 'g' || UNSUPPORTED_Y$3)) { objectDefineProperty.f(RegExp.prototype, 'flags', { configurable: true, get: regexpFlags }); } var UNSUPPORTED_Y$4 = regexpStickyHelpers.UNSUPPORTED_Y; var defineProperty$b = objectDefineProperty.f; var getInternalState$4 = internalState.get; var RegExpPrototype$1 = RegExp.prototype; // `RegExp.prototype.sticky` getter if (descriptors && UNSUPPORTED_Y$4) { defineProperty$b(RegExp.prototype, 'sticky', { configurable: true, get: function get() { if (this === RegExpPrototype$1) return undefined; // We can't use InternalStateModule.getterFor because // we don't add metadata for regexps created by a literal. if (this instanceof RegExp) { return !!getInternalState$4(this).sticky; } throw TypeError('Incompatible receiver, RegExp required'); } }); } var DELEGATES_TO_EXEC = function () { var execCalled = false; var re = /[ac]/; re.exec = function () { execCalled = true; return /./.exec.apply(this, arguments); }; return re.test('abc') === true && execCalled; }(); var nativeTest = /./.test; _export({ target: 'RegExp', proto: true, forced: !DELEGATES_TO_EXEC }, { test: function test(str) { if (typeof this.exec !== 'function') { return nativeTest.call(this, str); } var result = this.exec(str); if (result !== null && !isObject(result)) { throw new Error('RegExp exec method returned something other than an Object or null'); } return !!result; } }); var TO_STRING$1 = 'toString'; var RegExpPrototype$2 = RegExp.prototype; var nativeToString = RegExpPrototype$2[TO_STRING$1]; var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; }); // FF44- RegExp#toString has a wrong name var INCORRECT_NAME = nativeToString.name != TO_STRING$1; // `RegExp.prototype.toString` method // https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring if (NOT_GENERIC || INCORRECT_NAME) { redefine(RegExp.prototype, TO_STRING$1, function toString() { var R = anObject(this); var p = String(R.source); var rf = R.flags; var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype$2) ? regexpFlags.call(R) : rf); return '/' + p + '/' + f; }, { unsafe: true }); } // https://tc39.github.io/ecma262/#sec-set-objects var es_set = collection('Set', function (init) { return function Set() { return init(this, arguments.length ? arguments[0] : undefined); }; }, collectionStrong); var createMethod$6 = function createMethod(CONVERT_TO_STRING) { return function ($this, pos) { var S = String(requireObjectCoercible($this)); var position = toInteger(pos); var size = S.length; var first, second; if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; first = S.charCodeAt(position); return first < 0xD800 || first > 0xDBFF || position + 1 === size || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; }; }; var stringMultibyte = { // `String.prototype.codePointAt` method // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat codeAt: createMethod$6(false), // `String.prototype.at` method // https://github.com/mathiasbynens/String.prototype.at charAt: createMethod$6(true) }; var codeAt = stringMultibyte.codeAt; // `String.prototype.codePointAt` method // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat _export({ target: 'String', proto: true }, { codePointAt: function codePointAt(pos) { return codeAt(this, pos); } }); var notARegexp = function notARegexp(it) { if (isRegexp(it)) { throw TypeError("The method doesn't accept regular expressions"); } return it; }; var MATCH$2 = wellKnownSymbol('match'); var correctIsRegexpLogic = function correctIsRegexpLogic(METHOD_NAME) { var regexp = /./; try { '/./'[METHOD_NAME](regexp); } catch (e) { try { regexp[MATCH$2] = false; return '/./'[METHOD_NAME](regexp); } catch (f) { /* empty */ } } return false; }; var getOwnPropertyDescriptor$7 = objectGetOwnPropertyDescriptor.f; var nativeEndsWith = ''.endsWith; var min$5 = Math.min; var CORRECT_IS_REGEXP_LOGIC = correctIsRegexpLogic('endsWith'); // https://github.com/zloirock/core-js/pull/702 var MDN_POLYFILL_BUG = !CORRECT_IS_REGEXP_LOGIC && !!function () { var descriptor = getOwnPropertyDescriptor$7(String.prototype, 'endsWith'); return descriptor && !descriptor.writable; }(); // `String.prototype.endsWith` method // https://tc39.github.io/ecma262/#sec-string.prototype.endswith _export({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, { endsWith: function endsWith(searchString /* , endPosition = @length */ ) { var that = String(requireObjectCoercible(this)); notARegexp(searchString); var endPosition = arguments.length > 1 ? arguments[1] : undefined; var len = toLength(that.length); var end = endPosition === undefined ? len : min$5(toLength(endPosition), len); var search = String(searchString); return nativeEndsWith ? nativeEndsWith.call(that, search, end) : that.slice(end - search.length, end) === search; } }); var fromCharCode = String.fromCharCode; var nativeFromCodePoint = String.fromCodePoint; // length should be 1, old FF problem var INCORRECT_LENGTH = !!nativeFromCodePoint && nativeFromCodePoint.length != 1; // `String.fromCodePoint` method // https://tc39.github.io/ecma262/#sec-string.fromcodepoint _export({ target: 'String', stat: true, forced: INCORRECT_LENGTH }, { fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars var elements = []; var length = arguments.length; var i = 0; var code; while (length > i) { code = +arguments[i++]; if (toAbsoluteIndex(code, 0x10FFFF) !== code) throw RangeError(code + ' is not a valid code point'); elements.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xD800, code % 0x400 + 0xDC00)); } return elements.join(''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.includes _export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, { includes: function includes(searchString /* , position = 0 */ ) { return !!~String(requireObjectCoercible(this)).indexOf(notARegexp(searchString), arguments.length > 1 ? arguments[1] : undefined); } }); var charAt = stringMultibyte.charAt; var STRING_ITERATOR = 'String Iterator'; var setInternalState$6 = internalState.set; var getInternalState$5 = internalState.getterFor(STRING_ITERATOR); // `String.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator defineIterator(String, 'String', function (iterated) { setInternalState$6(this, { type: STRING_ITERATOR, string: String(iterated), index: 0 }); // `%StringIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next }, function next() { var state = getInternalState$5(this); var string = state.string; var index = state.index; var point; if (index >= string.length) return { value: undefined, done: true }; point = charAt(string, index); state.index += point.length; return { value: point, done: false }; }); var SPECIES$6 = wellKnownSymbol('species'); var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () { // #replace needs built-in support for named groups. // #match works fine because it just return the exec results, even if it has // a "grops" property. var re = /./; re.exec = function () { var result = []; result.groups = { a: '7' }; return result; }; return ''.replace(re, '$') !== '7'; }); // IE <= 11 replaces $0 with the whole match, as if it was $& // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0 var REPLACE_KEEPS_$0 = function () { return 'a'.replace(/./, '$0') === '$0'; }(); var REPLACE = wellKnownSymbol('replace'); // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = function () { if (/./[REPLACE]) { return /./[REPLACE]('a', '$0') === ''; } return false; }(); // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec // Weex JS has frozen built-in prototypes, so use try / catch wrapper var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () { var re = /(?:)/; var originalExec = re.exec; re.exec = function () { return originalExec.apply(this, arguments); }; var result = 'ab'.split(re); return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b'; }); var fixRegexpWellKnownSymbolLogic = function fixRegexpWellKnownSymbolLogic(KEY, length, exec, sham) { var SYMBOL = wellKnownSymbol(KEY); var DELEGATES_TO_SYMBOL = !fails(function () { // String methods call symbol-named RegEp methods var O = {}; O[SYMBOL] = function () { return 7; }; return ''[KEY](O) != 7; }); var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () { // Symbol-named RegExp methods call .exec var execCalled = false; var re = /a/; if (KEY === 'split') { // We can't use real regex here since it causes deoptimization // and serious performance degradation in V8 // https://github.com/zloirock/core-js/issues/306 re = {}; // RegExp[@@split] doesn't call the regex's exec method, but first creates // a new one. We need to return the patched regex when creating the new one. re.constructor = {}; re.constructor[SPECIES$6] = function () { return re; }; re.flags = ''; re[SYMBOL] = /./[SYMBOL]; } re.exec = function () { execCalled = true; return null; }; re[SYMBOL](''); return !execCalled; }); if (!DELEGATES_TO_SYMBOL || !DELEGATES_TO_EXEC || KEY === 'replace' && !(REPLACE_SUPPORTS_NAMED_GROUPS && REPLACE_KEEPS_$0 && !REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE) || KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) { var nativeRegExpMethod = /./[SYMBOL]; var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { if (regexp.exec === regexpExec) { if (DELEGATES_TO_SYMBOL && !forceStringMethod) { // The native String method already delegates to @@method (this // polyfilled function), leasing to infinite recursion. // We avoid it by directly calling the native @@method method. return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) }; } return { done: true, value: nativeMethod.call(str, regexp, arg2) }; } return { done: false }; }, { REPLACE_KEEPS_$0: REPLACE_KEEPS_$0, REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE: REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE }); var stringMethod = methods[0]; var regexMethod = methods[1]; redefine(String.prototype, KEY, stringMethod); redefine(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) // 21.2.5.11 RegExp.prototype[@@split](string, limit) ? function (string, arg) { return regexMethod.call(string, this, arg); } // 21.2.5.6 RegExp.prototype[@@match](string) // 21.2.5.9 RegExp.prototype[@@search](string) : function (string) { return regexMethod.call(string, this); }); } if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true); }; var charAt$1 = stringMultibyte.charAt; // `AdvanceStringIndex` abstract operation // https://tc39.github.io/ecma262/#sec-advancestringindex var advanceStringIndex = function advanceStringIndex(S, index, unicode) { return index + (unicode ? charAt$1(S, index).length : 1); }; // https://tc39.github.io/ecma262/#sec-regexpexec var regexpExecAbstract = function regexpExecAbstract(R, S) { var exec = R.exec; if (typeof exec === 'function') { var result = exec.call(R, S); if (_typeof(result) !== 'object') { throw TypeError('RegExp exec method returned something other than an Object or null'); } return result; } if (classofRaw(R) !== 'RegExp') { throw TypeError('RegExp#exec called on incompatible receiver'); } return regexpExec.call(R, S); }; fixRegexpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) { return [// `String.prototype.match` method // https://tc39.github.io/ecma262/#sec-string.prototype.match function match(regexp) { var O = requireObjectCoercible(this); var matcher = regexp == undefined ? undefined : regexp[MATCH]; return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); }, // `RegExp.prototype[@@match]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match function (regexp) { var res = maybeCallNative(nativeMatch, regexp, this); if (res.done) return res.value; var rx = anObject(regexp); var S = String(this); if (!rx.global) return regexpExecAbstract(rx, S); var fullUnicode = rx.unicode; rx.lastIndex = 0; var A = []; var n = 0; var result; while ((result = regexpExecAbstract(rx, S)) !== null) { var matchStr = String(result[0]); A[n] = matchStr; if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); n++; } return n === 0 ? null : A; }]; }); var MATCH_ALL = wellKnownSymbol('matchAll'); var REGEXP_STRING = 'RegExp String'; var REGEXP_STRING_ITERATOR = REGEXP_STRING + ' Iterator'; var setInternalState$7 = internalState.set; var getInternalState$6 = internalState.getterFor(REGEXP_STRING_ITERATOR); var RegExpPrototype$3 = RegExp.prototype; var regExpBuiltinExec = RegExpPrototype$3.exec; var nativeMatchAll = ''.matchAll; var WORKS_WITH_NON_GLOBAL_REGEX = !!nativeMatchAll && !fails(function () { 'a'.matchAll(/./); }); var regExpExec = function regExpExec(R, S) { var exec = R.exec; var result; if (typeof exec == 'function') { result = exec.call(R, S); if (_typeof(result) != 'object') throw TypeError('Incorrect exec result'); return result; } return regExpBuiltinExec.call(R, S); }; // eslint-disable-next-line max-len var $RegExpStringIterator = createIteratorConstructor(function RegExpStringIterator(regexp, string, global, fullUnicode) { setInternalState$7(this, { type: REGEXP_STRING_ITERATOR, regexp: regexp, string: string, global: global, unicode: fullUnicode, done: false }); }, REGEXP_STRING, function next() { var state = getInternalState$6(this); if (state.done) return { value: undefined, done: true }; var R = state.regexp; var S = state.string; var match = regExpExec(R, S); if (match === null) return { value: undefined, done: state.done = true }; if (state.global) { if (String(match[0]) == '') R.lastIndex = advanceStringIndex(S, toLength(R.lastIndex), state.unicode); return { value: match, done: false }; } state.done = true; return { value: match, done: false }; }); var $matchAll = function $matchAll(string) { var R = anObject(this); var S = String(string); var C, flagsValue, flags, matcher, global, fullUnicode; C = speciesConstructor(R, RegExp); flagsValue = R.flags; if (flagsValue === undefined && R instanceof RegExp && !('flags' in RegExpPrototype$3)) { flagsValue = regexpFlags.call(R); } flags = flagsValue === undefined ? '' : String(flagsValue); matcher = new C(C === RegExp ? R.source : R, flags); global = !!~flags.indexOf('g'); fullUnicode = !!~flags.indexOf('u'); matcher.lastIndex = toLength(R.lastIndex); return new $RegExpStringIterator(matcher, S, global, fullUnicode); }; // `String.prototype.matchAll` method // https://github.com/tc39/proposal-string-matchall _export({ target: 'String', proto: true, forced: WORKS_WITH_NON_GLOBAL_REGEX }, { matchAll: function matchAll(regexp) { var O = requireObjectCoercible(this); var flags, S, matcher, rx; if (regexp != null) { if (isRegexp(regexp)) { flags = String(requireObjectCoercible('flags' in RegExpPrototype$3 ? regexp.flags : regexpFlags.call(regexp))); if (!~flags.indexOf('g')) throw TypeError('`.matchAll` does not allow non-global regexes'); } if (WORKS_WITH_NON_GLOBAL_REGEX) return nativeMatchAll.apply(O, arguments); matcher = regexp[MATCH_ALL]; if (matcher === undefined && isPure && classofRaw(regexp) == 'RegExp') matcher = $matchAll; if (matcher != null) return aFunction$1(matcher).call(regexp, O); } else if (WORKS_WITH_NON_GLOBAL_REGEX) return nativeMatchAll.apply(O, arguments); S = String(O); rx = new RegExp(regexp, 'g'); return rx[MATCH_ALL](S); } }); MATCH_ALL in RegExpPrototype$3 || createNonEnumerableProperty(RegExpPrototype$3, MATCH_ALL, $matchAll); // eslint-disable-next-line unicorn/no-unsafe-regex var stringPadWebkitBug = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(engineUserAgent); var $padEnd = stringPad.end; // `String.prototype.padEnd` method // https://tc39.github.io/ecma262/#sec-string.prototype.padend _export({ target: 'String', proto: true, forced: stringPadWebkitBug }, { padEnd: function padEnd(maxLength /* , fillString = ' ' */ ) { return $padEnd(this, maxLength, arguments.length > 1 ? arguments[1] : undefined); } }); var $padStart = stringPad.start; // `String.prototype.padStart` method // https://tc39.github.io/ecma262/#sec-string.prototype.padstart _export({ target: 'String', proto: true, forced: stringPadWebkitBug }, { padStart: function padStart(maxLength /* , fillString = ' ' */ ) { return $padStart(this, maxLength, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-string.raw _export({ target: 'String', stat: true }, { raw: function raw(template) { var rawTemplate = toIndexedObject(template.raw); var literalSegments = toLength(rawTemplate.length); var argumentsLength = arguments.length; var elements = []; var i = 0; while (literalSegments > i) { elements.push(String(rawTemplate[i++])); if (i < argumentsLength) elements.push(String(arguments[i])); } return elements.join(''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.repeat _export({ target: 'String', proto: true }, { repeat: stringRepeat }); var max$3 = Math.max; var min$6 = Math.min; var floor$6 = Math.floor; var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g; var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; var maybeToString = function maybeToString(it) { return it === undefined ? it : String(it); }; // @@replace logic fixRegexpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) { var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE; var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0; var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; return [// `String.prototype.replace` method // https://tc39.github.io/ecma262/#sec-string.prototype.replace function replace(searchValue, replaceValue) { var O = requireObjectCoercible(this); var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(String(O), searchValue, replaceValue); }, // `RegExp.prototype[@@replace]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace function (regexp, replaceValue) { if (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0 || typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1) { var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); if (res.done) return res.value; } var rx = anObject(regexp); var S = String(this); var functionalReplace = typeof replaceValue === 'function'; if (!functionalReplace) replaceValue = String(replaceValue); var global = rx.global; if (global) { var fullUnicode = rx.unicode; rx.lastIndex = 0; } var results = []; while (true) { var result = regexpExecAbstract(rx, S); if (result === null) break; results.push(result); if (!global) break; var matchStr = String(result[0]); if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); } var accumulatedResult = ''; var nextSourcePosition = 0; for (var i = 0; i < results.length; i++) { result = results[i]; var matched = String(result[0]); var position = max$3(min$6(toInteger(result.index), S.length), 0); var captures = []; // NOTE: This is equivalent to // captures = result.slice(1).map(maybeToString) // but for some reason `nativeSlice.call(result, 1, result.length)` (called in // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. for (var j = 1; j < result.length; j++) { captures.push(maybeToString(result[j])); } var namedCaptures = result.groups; if (functionalReplace) { var replacerArgs = [matched].concat(captures, position, S); if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); var replacement = String(replaceValue.apply(undefined, replacerArgs)); } else { replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); } if (position >= nextSourcePosition) { accumulatedResult += S.slice(nextSourcePosition, position) + replacement; nextSourcePosition = position + matched.length; } } return accumulatedResult + S.slice(nextSourcePosition); }]; // https://tc39.github.io/ecma262/#sec-getsubstitution function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { var tailPos = position + matched.length; var m = captures.length; var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; if (namedCaptures !== undefined) { namedCaptures = toObject(namedCaptures); symbols = SUBSTITUTION_SYMBOLS; } return nativeReplace.call(replacement, symbols, function (match, ch) { var capture; switch (ch.charAt(0)) { case '$': return '$'; case '&': return matched; case '`': return str.slice(0, position); case "'": return str.slice(tailPos); case '<': capture = namedCaptures[ch.slice(1, -1)]; break; default: // \d\d? var n = +ch; if (n === 0) return match; if (n > m) { var f = floor$6(n / 10); if (f === 0) return match; if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); return match; } capture = captures[n - 1]; } return capture === undefined ? '' : capture; }); } }); fixRegexpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) { return [// `String.prototype.search` method // https://tc39.github.io/ecma262/#sec-string.prototype.search function search(regexp) { var O = requireObjectCoercible(this); var searcher = regexp == undefined ? undefined : regexp[SEARCH]; return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); }, // `RegExp.prototype[@@search]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search function (regexp) { var res = maybeCallNative(nativeSearch, regexp, this); if (res.done) return res.value; var rx = anObject(regexp); var S = String(this); var previousLastIndex = rx.lastIndex; if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0; var result = regexpExecAbstract(rx, S); if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex; return result === null ? -1 : result.index; }]; }); var arrayPush = [].push; var min$7 = Math.min; var MAX_UINT32 = 0xFFFFFFFF; // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); }); // @@split logic fixRegexpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) { var internalSplit; if ('abbc'.split(/(b)*/)[1] == 'c' || 'test'.split(/(?:)/, -1).length != 4 || 'ab'.split(/(?:ab)*/).length != 2 || '.'.split(/(.?)(.?)/).length != 4 || '.'.split(/()()/).length > 1 || ''.split(/.?/).length) { // based on es5-shim implementation, need to rework it internalSplit = function internalSplit(separator, limit) { var string = String(requireObjectCoercible(this)); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; if (lim === 0) return []; if (separator === undefined) return [string]; // If `separator` is not a regex, use native split if (!isRegexp(separator)) { return nativeSplit.call(string, separator, lim); } var output = []; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); var lastLastIndex = 0; // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var match, lastIndex, lastLength; while (match = regexpExec.call(separatorCopy, string)) { lastIndex = separatorCopy.lastIndex; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1)); lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= lim) break; } if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop } if (lastLastIndex === string.length) { if (lastLength || !separatorCopy.test('')) output.push(''); } else output.push(string.slice(lastLastIndex)); return output.length > lim ? output.slice(0, lim) : output; }; // Chakra, V8 } else if ('0'.split(undefined, 0).length) { internalSplit = function internalSplit(separator, limit) { return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit); }; } else internalSplit = nativeSplit; return [// `String.prototype.split` method // https://tc39.github.io/ecma262/#sec-string.prototype.split function split(separator, limit) { var O = requireObjectCoercible(this); var splitter = separator == undefined ? undefined : separator[SPLIT]; return splitter !== undefined ? splitter.call(separator, O, limit) : internalSplit.call(String(O), separator, limit); }, // `RegExp.prototype[@@split]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split // // NOTE: This cannot be properly polyfilled in engines that don't support // the 'y' flag. function (regexp, limit) { var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit); if (res.done) return res.value; var rx = anObject(regexp); var S = String(this); var C = speciesConstructor(rx, RegExp); var unicodeMatching = rx.unicode; var flags = (rx.ignoreCase ? 'i' : '') + (rx.multiline ? 'm' : '') + (rx.unicode ? 'u' : '') + (SUPPORTS_Y ? 'y' : 'g'); // ^(? + rx + ) is needed, in combination with some S slicing, to // simulate the 'y' flag. var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; if (lim === 0) return []; if (S.length === 0) return regexpExecAbstract(splitter, S) === null ? [S] : []; var p = 0; var q = 0; var A = []; while (q < S.length) { splitter.lastIndex = SUPPORTS_Y ? q : 0; var z = regexpExecAbstract(splitter, SUPPORTS_Y ? S : S.slice(q)); var e; if (z === null || (e = min$7(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p) { q = advanceStringIndex(S, q, unicodeMatching); } else { A.push(S.slice(p, q)); if (A.length === lim) return A; for (var i = 1; i <= z.length - 1; i++) { A.push(z[i]); if (A.length === lim) return A; } q = p = e; } } A.push(S.slice(p)); return A; }]; }, !SUPPORTS_Y); var getOwnPropertyDescriptor$8 = objectGetOwnPropertyDescriptor.f; var nativeStartsWith = ''.startsWith; var min$8 = Math.min; var CORRECT_IS_REGEXP_LOGIC$1 = correctIsRegexpLogic('startsWith'); // https://github.com/zloirock/core-js/pull/702 var MDN_POLYFILL_BUG$1 = !CORRECT_IS_REGEXP_LOGIC$1 && !!function () { var descriptor = getOwnPropertyDescriptor$8(String.prototype, 'startsWith'); return descriptor && !descriptor.writable; }(); // `String.prototype.startsWith` method // https://tc39.github.io/ecma262/#sec-string.prototype.startswith _export({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG$1 && !CORRECT_IS_REGEXP_LOGIC$1 }, { startsWith: function startsWith(searchString /* , position = 0 */ ) { var that = String(requireObjectCoercible(this)); notARegexp(searchString); var index = toLength(min$8(arguments.length > 1 ? arguments[1] : undefined, that.length)); var search = String(searchString); return nativeStartsWith ? nativeStartsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); var non = "\u200B\x85\u180E"; // check that a method works with the correct list // of whitespaces and has a correct name var stringTrimForced = function stringTrimForced(METHOD_NAME) { return fails(function () { return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME; }); }; var $trim = stringTrim.trim; // `String.prototype.trim` method // https://tc39.github.io/ecma262/#sec-string.prototype.trim _export({ target: 'String', proto: true, forced: stringTrimForced('trim') }, { trim: function trim() { return $trim(this); } }); var $trimEnd = stringTrim.end; var FORCED$g = stringTrimForced('trimEnd'); var trimEnd = FORCED$g ? function trimEnd() { return $trimEnd(this); } : ''.trimEnd; // `String.prototype.{ trimEnd, trimRight }` methods // https://github.com/tc39/ecmascript-string-left-right-trim _export({ target: 'String', proto: true, forced: FORCED$g }, { trimEnd: trimEnd, trimRight: trimEnd }); var $trimStart = stringTrim.start; var FORCED$h = stringTrimForced('trimStart'); var trimStart = FORCED$h ? function trimStart() { return $trimStart(this); } : ''.trimStart; // `String.prototype.{ trimStart, trimLeft }` methods // https://github.com/tc39/ecmascript-string-left-right-trim _export({ target: 'String', proto: true, forced: FORCED$h }, { trimStart: trimStart, trimLeft: trimStart }); var quot = /"/g; // B.2.3.2.1 CreateHTML(string, tag, attribute, value) // https://tc39.github.io/ecma262/#sec-createhtml var createHtml = function createHtml(string, tag, attribute, value) { var S = String(requireObjectCoercible(string)); var p1 = '<' + tag; if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; return p1 + '>' + S + ''; }; // of a tag and escaping quotes in arguments var stringHtmlForced = function stringHtmlForced(METHOD_NAME) { return fails(function () { var test = ''[METHOD_NAME]('"'); return test !== test.toLowerCase() || test.split('"').length > 3; }); }; // https://tc39.github.io/ecma262/#sec-string.prototype.anchor _export({ target: 'String', proto: true, forced: stringHtmlForced('anchor') }, { anchor: function anchor(name) { return createHtml(this, 'a', 'name', name); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.big _export({ target: 'String', proto: true, forced: stringHtmlForced('big') }, { big: function big() { return createHtml(this, 'big', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.blink _export({ target: 'String', proto: true, forced: stringHtmlForced('blink') }, { blink: function blink() { return createHtml(this, 'blink', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.bold _export({ target: 'String', proto: true, forced: stringHtmlForced('bold') }, { bold: function bold() { return createHtml(this, 'b', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.fixed _export({ target: 'String', proto: true, forced: stringHtmlForced('fixed') }, { fixed: function fixed() { return createHtml(this, 'tt', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.fontcolor _export({ target: 'String', proto: true, forced: stringHtmlForced('fontcolor') }, { fontcolor: function fontcolor(color) { return createHtml(this, 'font', 'color', color); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.fontsize _export({ target: 'String', proto: true, forced: stringHtmlForced('fontsize') }, { fontsize: function fontsize(size) { return createHtml(this, 'font', 'size', size); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.italics _export({ target: 'String', proto: true, forced: stringHtmlForced('italics') }, { italics: function italics() { return createHtml(this, 'i', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.link _export({ target: 'String', proto: true, forced: stringHtmlForced('link') }, { link: function link(url) { return createHtml(this, 'a', 'href', url); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.small _export({ target: 'String', proto: true, forced: stringHtmlForced('small') }, { small: function small() { return createHtml(this, 'small', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.strike _export({ target: 'String', proto: true, forced: stringHtmlForced('strike') }, { strike: function strike() { return createHtml(this, 'strike', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.sub _export({ target: 'String', proto: true, forced: stringHtmlForced('sub') }, { sub: function sub() { return createHtml(this, 'sub', '', ''); } }); // https://tc39.github.io/ecma262/#sec-string.prototype.sup _export({ target: 'String', proto: true, forced: stringHtmlForced('sup') }, { sup: function sup() { return createHtml(this, 'sup', '', ''); } }); /* eslint-disable no-new */ var NATIVE_ARRAY_BUFFER_VIEWS$2 = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; var ArrayBuffer$3 = global_1.ArrayBuffer; var Int8Array$2 = global_1.Int8Array; var typedArrayConstructorsRequireWrappers = !NATIVE_ARRAY_BUFFER_VIEWS$2 || !fails(function () { Int8Array$2(1); }) || !fails(function () { new Int8Array$2(-1); }) || !checkCorrectnessOfIteration(function (iterable) { new Int8Array$2(); new Int8Array$2(null); new Int8Array$2(1.5); new Int8Array$2(iterable); }, true) || fails(function () { // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill return new Int8Array$2(new ArrayBuffer$3(2), 1, undefined).length !== 1; }); var toPositiveInteger = function toPositiveInteger(it) { var result = toInteger(it); if (result < 0) throw RangeError("The argument can't be less than 0"); return result; }; var toOffset = function toOffset(it, BYTES) { var offset = toPositiveInteger(it); if (offset % BYTES) throw RangeError('Wrong offset'); return offset; }; var aTypedArrayConstructor$1 = arrayBufferViewCore.aTypedArrayConstructor; var typedArrayFrom = function from(source /* , mapfn, thisArg */ ) { var O = toObject(source); var argumentsLength = arguments.length; var mapfn = argumentsLength > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var iteratorMethod = getIteratorMethod(O); var i, length, result, step, iterator, next; if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) { iterator = iteratorMethod.call(O); next = iterator.next; O = []; while (!(step = next.call(iterator)).done) { O.push(step.value); } } if (mapping && argumentsLength > 2) { mapfn = functionBindContext(mapfn, arguments[2], 2); } length = toLength(O.length); result = new (aTypedArrayConstructor$1(this))(length); for (i = 0; length > i; i++) { result[i] = mapping ? mapfn(O[i], i) : O[i]; } return result; }; var typedArrayConstructor = createCommonjsModule(function (module) { var getOwnPropertyNames = objectGetOwnPropertyNames.f; var forEach = arrayIteration.forEach; var getInternalState = internalState.get; var setInternalState = internalState.set; var nativeDefineProperty = objectDefineProperty.f; var nativeGetOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; var round = Math.round; var RangeError = global_1.RangeError; var ArrayBuffer = arrayBuffer.ArrayBuffer; var DataView = arrayBuffer.DataView; var NATIVE_ARRAY_BUFFER_VIEWS = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; var TYPED_ARRAY_TAG = arrayBufferViewCore.TYPED_ARRAY_TAG; var TypedArray = arrayBufferViewCore.TypedArray; var TypedArrayPrototype = arrayBufferViewCore.TypedArrayPrototype; var aTypedArrayConstructor = arrayBufferViewCore.aTypedArrayConstructor; var isTypedArray = arrayBufferViewCore.isTypedArray; var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; var WRONG_LENGTH = 'Wrong length'; var fromList = function fromList(C, list) { var index = 0; var length = list.length; var result = new (aTypedArrayConstructor(C))(length); while (length > index) { result[index] = list[index++]; } return result; }; var addGetter = function addGetter(it, key) { nativeDefineProperty(it, key, { get: function get() { return getInternalState(this)[key]; } }); }; var isArrayBuffer = function isArrayBuffer(it) { var klass; return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer'; }; var isTypedArrayIndex = function isTypedArrayIndex(target, key) { return isTypedArray(target) && _typeof(key) != 'symbol' && key in target && String(+key) == String(key); }; var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) { return isTypedArrayIndex(target, key = toPrimitive(key, true)) ? createPropertyDescriptor(2, target[key]) : nativeGetOwnPropertyDescriptor(target, key); }; var wrappedDefineProperty = function defineProperty(target, key, descriptor) { if (isTypedArrayIndex(target, key = toPrimitive(key, true)) && isObject(descriptor) && has(descriptor, 'value') && !has(descriptor, 'get') && !has(descriptor, 'set') // TODO: add validation descriptor w/o calling accessors && !descriptor.configurable && (!has(descriptor, 'writable') || descriptor.writable) && (!has(descriptor, 'enumerable') || descriptor.enumerable)) { target[key] = descriptor.value; return target; } return nativeDefineProperty(target, key, descriptor); }; if (descriptors) { if (!NATIVE_ARRAY_BUFFER_VIEWS) { objectGetOwnPropertyDescriptor.f = wrappedGetOwnPropertyDescriptor; objectDefineProperty.f = wrappedDefineProperty; addGetter(TypedArrayPrototype, 'buffer'); addGetter(TypedArrayPrototype, 'byteOffset'); addGetter(TypedArrayPrototype, 'byteLength'); addGetter(TypedArrayPrototype, 'length'); } _export({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor, defineProperty: wrappedDefineProperty }); module.exports = function (TYPE, wrapper, CLAMPED) { var BYTES = TYPE.match(/\d+$/)[0] / 8; var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array'; var GETTER = 'get' + TYPE; var SETTER = 'set' + TYPE; var NativeTypedArrayConstructor = global_1[CONSTRUCTOR_NAME]; var TypedArrayConstructor = NativeTypedArrayConstructor; var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype; var exported = {}; var getter = function getter(that, index) { var data = getInternalState(that); return data.view[GETTER](index * BYTES + data.byteOffset, true); }; var setter = function setter(that, index, value) { var data = getInternalState(that); if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF; data.view[SETTER](index * BYTES + data.byteOffset, value, true); }; var addElement = function addElement(that, index) { nativeDefineProperty(that, index, { get: function get() { return getter(this, index); }, set: function set(value) { return setter(this, index, value); }, enumerable: true }); }; if (!NATIVE_ARRAY_BUFFER_VIEWS) { TypedArrayConstructor = wrapper(function (that, data, offset, $length) { anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME); var index = 0; var byteOffset = 0; var buffer, byteLength, length; if (!isObject(data)) { length = toIndex(data); byteLength = length * BYTES; buffer = new ArrayBuffer(byteLength); } else if (isArrayBuffer(data)) { buffer = data; byteOffset = toOffset(offset, BYTES); var $len = data.byteLength; if ($length === undefined) { if ($len % BYTES) throw RangeError(WRONG_LENGTH); byteLength = $len - byteOffset; if (byteLength < 0) throw RangeError(WRONG_LENGTH); } else { byteLength = toLength($length) * BYTES; if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH); } length = byteLength / BYTES; } else if (isTypedArray(data)) { return fromList(TypedArrayConstructor, data); } else { return typedArrayFrom.call(TypedArrayConstructor, data); } setInternalState(that, { buffer: buffer, byteOffset: byteOffset, byteLength: byteLength, length: length, view: new DataView(buffer) }); while (index < length) { addElement(that, index++); } }); if (objectSetPrototypeOf) objectSetPrototypeOf(TypedArrayConstructor, TypedArray); TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = objectCreate(TypedArrayPrototype); } else if (typedArrayConstructorsRequireWrappers) { TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) { anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME); return inheritIfRequired(function () { if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data)); if (isArrayBuffer(data)) return $length !== undefined ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length) : typedArrayOffset !== undefined ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES)) : new NativeTypedArrayConstructor(data); if (isTypedArray(data)) return fromList(TypedArrayConstructor, data); return typedArrayFrom.call(TypedArrayConstructor, data); }(), dummy, TypedArrayConstructor); }); if (objectSetPrototypeOf) objectSetPrototypeOf(TypedArrayConstructor, TypedArray); forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) { if (!(key in TypedArrayConstructor)) { createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]); } }); TypedArrayConstructor.prototype = TypedArrayConstructorPrototype; } if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) { createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor); } if (TYPED_ARRAY_TAG) { createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME); } exported[CONSTRUCTOR_NAME] = TypedArrayConstructor; _export({ global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS }, exported); if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) { createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES); } if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) { createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES); } setSpecies(CONSTRUCTOR_NAME); }; } else module.exports = function () { /* empty */ }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Float32', function (init) { return function Float32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Float64', function (init) { return function Float64Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Int8', function (init) { return function Int8Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Int16', function (init) { return function Int16Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Int32', function (init) { return function Int32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Uint8', function (init) { return function Uint8Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Uint8', function (init) { return function Uint8ClampedArray(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }, true); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Uint16', function (init) { return function Uint16Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); // https://tc39.github.io/ecma262/#sec-typedarray-objects typedArrayConstructor('Uint32', function (init) { return function Uint32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); var aTypedArray$1 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$1 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.copyWithin` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.copywithin exportTypedArrayMethod$1('copyWithin', function copyWithin(target, start /* , end */ ) { return arrayCopyWithin.call(aTypedArray$1(this), target, start, arguments.length > 2 ? arguments[2] : undefined); }); var $every$1 = arrayIteration.every; var aTypedArray$2 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$2 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.every` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every exportTypedArrayMethod$2('every', function every(callbackfn /* , thisArg */ ) { return $every$1(aTypedArray$2(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); var aTypedArray$3 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$3 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.fill` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill // eslint-disable-next-line no-unused-vars exportTypedArrayMethod$3('fill', function fill(value /* , start, end */ ) { return arrayFill.apply(aTypedArray$3(this), arguments); }); var $filter$1 = arrayIteration.filter; var aTypedArray$4 = arrayBufferViewCore.aTypedArray; var aTypedArrayConstructor$2 = arrayBufferViewCore.aTypedArrayConstructor; var exportTypedArrayMethod$4 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.filter` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.filter exportTypedArrayMethod$4('filter', function filter(callbackfn /* , thisArg */ ) { var list = $filter$1(aTypedArray$4(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); var C = speciesConstructor(this, this.constructor); var index = 0; var length = list.length; var result = new (aTypedArrayConstructor$2(C))(length); while (length > index) { result[index] = list[index++]; } return result; }); var $find$1 = arrayIteration.find; var aTypedArray$5 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$5 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.find` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.find exportTypedArrayMethod$5('find', function find(predicate /* , thisArg */ ) { return $find$1(aTypedArray$5(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }); var $findIndex$1 = arrayIteration.findIndex; var aTypedArray$6 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$6 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.findIndex` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findindex exportTypedArrayMethod$6('findIndex', function findIndex(predicate /* , thisArg */ ) { return $findIndex$1(aTypedArray$6(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }); var $forEach$2 = arrayIteration.forEach; var aTypedArray$7 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$7 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.forEach` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.foreach exportTypedArrayMethod$7('forEach', function forEach(callbackfn /* , thisArg */ ) { $forEach$2(aTypedArray$7(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); var exportTypedArrayStaticMethod$1 = arrayBufferViewCore.exportTypedArrayStaticMethod; // `%TypedArray%.from` method // https://tc39.github.io/ecma262/#sec-%typedarray%.from exportTypedArrayStaticMethod$1('from', typedArrayFrom, typedArrayConstructorsRequireWrappers); var $includes$1 = arrayIncludes.includes; var aTypedArray$8 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$8 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.includes` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.includes exportTypedArrayMethod$8('includes', function includes(searchElement /* , fromIndex */ ) { return $includes$1(aTypedArray$8(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }); var $indexOf$1 = arrayIncludes.indexOf; var aTypedArray$9 = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$9 = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.indexof exportTypedArrayMethod$9('indexOf', function indexOf(searchElement /* , fromIndex */ ) { return $indexOf$1(aTypedArray$9(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }); var ITERATOR$5 = wellKnownSymbol('iterator'); var Uint8Array$1 = global_1.Uint8Array; var arrayValues = es_array_iterator.values; var arrayKeys = es_array_iterator.keys; var arrayEntries = es_array_iterator.entries; var aTypedArray$a = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$a = arrayBufferViewCore.exportTypedArrayMethod; var nativeTypedArrayIterator = Uint8Array$1 && Uint8Array$1.prototype[ITERATOR$5]; var CORRECT_ITER_NAME = !!nativeTypedArrayIterator && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined); var typedArrayValues = function values() { return arrayValues.call(aTypedArray$a(this)); }; // `%TypedArray%.prototype.entries` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries exportTypedArrayMethod$a('entries', function entries() { return arrayEntries.call(aTypedArray$a(this)); }); // `%TypedArray%.prototype.keys` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys exportTypedArrayMethod$a('keys', function keys() { return arrayKeys.call(aTypedArray$a(this)); }); // `%TypedArray%.prototype.values` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values exportTypedArrayMethod$a('values', typedArrayValues, !CORRECT_ITER_NAME); // `%TypedArray%.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator exportTypedArrayMethod$a(ITERATOR$5, typedArrayValues, !CORRECT_ITER_NAME); var aTypedArray$b = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$b = arrayBufferViewCore.exportTypedArrayMethod; var $join = [].join; // `%TypedArray%.prototype.join` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join // eslint-disable-next-line no-unused-vars exportTypedArrayMethod$b('join', function join(separator) { return $join.apply(aTypedArray$b(this), arguments); }); var aTypedArray$c = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$c = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.lastIndexOf` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.lastindexof // eslint-disable-next-line no-unused-vars exportTypedArrayMethod$c('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */ ) { return arrayLastIndexOf.apply(aTypedArray$c(this), arguments); }); var $map$1 = arrayIteration.map; var aTypedArray$d = arrayBufferViewCore.aTypedArray; var aTypedArrayConstructor$3 = arrayBufferViewCore.aTypedArrayConstructor; var exportTypedArrayMethod$d = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.map` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.map exportTypedArrayMethod$d('map', function map(mapfn /* , thisArg */ ) { return $map$1(aTypedArray$d(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) { return new (aTypedArrayConstructor$3(speciesConstructor(O, O.constructor)))(length); }); }); var aTypedArrayConstructor$4 = arrayBufferViewCore.aTypedArrayConstructor; var exportTypedArrayStaticMethod$2 = arrayBufferViewCore.exportTypedArrayStaticMethod; // `%TypedArray%.of` method // https://tc39.github.io/ecma262/#sec-%typedarray%.of exportTypedArrayStaticMethod$2('of', function of() /* ...items */ { var index = 0; var length = arguments.length; var result = new (aTypedArrayConstructor$4(this))(length); while (length > index) { result[index] = arguments[index++]; } return result; }, typedArrayConstructorsRequireWrappers); var $reduce$1 = arrayReduce.left; var aTypedArray$e = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$e = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.reduce` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce exportTypedArrayMethod$e('reduce', function reduce(callbackfn /* , initialValue */ ) { return $reduce$1(aTypedArray$e(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); }); var $reduceRight$1 = arrayReduce.right; var aTypedArray$f = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$f = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.reduceRicht` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduceright exportTypedArrayMethod$f('reduceRight', function reduceRight(callbackfn /* , initialValue */ ) { return $reduceRight$1(aTypedArray$f(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); }); var aTypedArray$g = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$g = arrayBufferViewCore.exportTypedArrayMethod; var floor$7 = Math.floor; // `%TypedArray%.prototype.reverse` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reverse exportTypedArrayMethod$g('reverse', function reverse() { var that = this; var length = aTypedArray$g(that).length; var middle = floor$7(length / 2); var index = 0; var value; while (index < middle) { value = that[index]; that[index++] = that[--length]; that[length] = value; } return that; }); var aTypedArray$h = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$h = arrayBufferViewCore.exportTypedArrayMethod; var FORCED$i = fails(function () { // eslint-disable-next-line no-undef new Int8Array(1).set({}); }); // `%TypedArray%.prototype.set` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.set exportTypedArrayMethod$h('set', function set(arrayLike /* , offset */ ) { aTypedArray$h(this); var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1); var length = this.length; var src = toObject(arrayLike); var len = toLength(src.length); var index = 0; if (len + offset > length) throw RangeError('Wrong length'); while (index < len) { this[offset + index] = src[index++]; } }, FORCED$i); var aTypedArray$i = arrayBufferViewCore.aTypedArray; var aTypedArrayConstructor$5 = arrayBufferViewCore.aTypedArrayConstructor; var exportTypedArrayMethod$i = arrayBufferViewCore.exportTypedArrayMethod; var $slice = [].slice; var FORCED$j = fails(function () { // eslint-disable-next-line no-undef new Int8Array(1).slice(); }); // `%TypedArray%.prototype.slice` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice exportTypedArrayMethod$i('slice', function slice(start, end) { var list = $slice.call(aTypedArray$i(this), start, end); var C = speciesConstructor(this, this.constructor); var index = 0; var length = list.length; var result = new (aTypedArrayConstructor$5(C))(length); while (length > index) { result[index] = list[index++]; } return result; }, FORCED$j); var $some$1 = arrayIteration.some; var aTypedArray$j = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$j = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.some` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some exportTypedArrayMethod$j('some', function some(callbackfn /* , thisArg */ ) { return $some$1(aTypedArray$j(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); var aTypedArray$k = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$k = arrayBufferViewCore.exportTypedArrayMethod; var $sort = [].sort; // `%TypedArray%.prototype.sort` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.sort exportTypedArrayMethod$k('sort', function sort(comparefn) { return $sort.call(aTypedArray$k(this), comparefn); }); var aTypedArray$l = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$l = arrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.subarray` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.subarray exportTypedArrayMethod$l('subarray', function subarray(begin, end) { var O = aTypedArray$l(this); var length = O.length; var beginIndex = toAbsoluteIndex(begin, length); return new (speciesConstructor(O, O.constructor))(O.buffer, O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT, toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex)); }); var Int8Array$3 = global_1.Int8Array; var aTypedArray$m = arrayBufferViewCore.aTypedArray; var exportTypedArrayMethod$m = arrayBufferViewCore.exportTypedArrayMethod; var $toLocaleString = [].toLocaleString; var $slice$1 = [].slice; // iOS Safari 6.x fails here var TO_LOCALE_STRING_BUG = !!Int8Array$3 && fails(function () { $toLocaleString.call(new Int8Array$3(1)); }); var FORCED$k = fails(function () { return [1, 2].toLocaleString() != new Int8Array$3([1, 2]).toLocaleString(); }) || !fails(function () { Int8Array$3.prototype.toLocaleString.call([1, 2]); }); // `%TypedArray%.prototype.toLocaleString` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring exportTypedArrayMethod$m('toLocaleString', function toLocaleString() { return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice$1.call(aTypedArray$m(this)) : aTypedArray$m(this), arguments); }, FORCED$k); var exportTypedArrayMethod$n = arrayBufferViewCore.exportTypedArrayMethod; var Uint8Array$2 = global_1.Uint8Array; var Uint8ArrayPrototype = Uint8Array$2 && Uint8Array$2.prototype || {}; var arrayToString = [].toString; var arrayJoin = [].join; if (fails(function () { arrayToString.call({}); })) { arrayToString = function toString() { return arrayJoin.call(this); }; } var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString; // `%TypedArray%.prototype.toString` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tostring exportTypedArrayMethod$n('toString', arrayToString, IS_NOT_ARRAY_METHOD); var getWeakData = internalMetadata.getWeakData; var setInternalState$8 = internalState.set; var internalStateGetterFor$1 = internalState.getterFor; var find = arrayIteration.find; var findIndex = arrayIteration.findIndex; var id$1 = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function uncaughtFrozenStore(store) { return store.frozen || (store.frozen = new UncaughtFrozenStore()); }; var UncaughtFrozenStore = function UncaughtFrozenStore() { this.entries = []; }; var findUncaughtFrozen = function findUncaughtFrozen(store, key) { return find(store.entries, function (it) { return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function get(key) { var entry = findUncaughtFrozen(this, key); if (entry) return entry[1]; }, has: function has(key) { return !!findUncaughtFrozen(this, key); }, set: function set(key, value) { var entry = findUncaughtFrozen(this, key); if (entry) entry[1] = value;else this.entries.push([key, value]); }, 'delete': function _delete(key) { var index = findIndex(this.entries, function (it) { return it[0] === key; }); if (~index) this.entries.splice(index, 1); return !!~index; } }; var collectionWeak = { getConstructor: function getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { var C = wrapper(function (that, iterable) { anInstance(that, C, CONSTRUCTOR_NAME); setInternalState$8(that, { type: CONSTRUCTOR_NAME, id: id$1++, frozen: undefined }); if (iterable != undefined) iterate_1(iterable, that[ADDER], that, IS_MAP); }); var getInternalState = internalStateGetterFor$1(CONSTRUCTOR_NAME); var define = function define(that, key, value) { var state = getInternalState(that); var data = getWeakData(anObject(key), true); if (data === true) uncaughtFrozenStore(state).set(key, value);else data[state.id] = value; return that; }; redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function _delete(key) { var state = getInternalState(this); if (!isObject(key)) return false; var data = getWeakData(key); if (data === true) return uncaughtFrozenStore(state)['delete'](key); return data && has(data, state.id) && delete data[state.id]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has$1(key) { var state = getInternalState(this); if (!isObject(key)) return false; var data = getWeakData(key); if (data === true) return uncaughtFrozenStore(state).has(key); return data && has(data, state.id); } }); redefineAll(C.prototype, IS_MAP ? { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key) { var state = getInternalState(this); if (isObject(key)) { var data = getWeakData(key); if (data === true) return uncaughtFrozenStore(state).get(key); return data ? data[state.id] : undefined; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value) { return define(this, key, value); } } : { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value) { return define(this, value, true); } }); return C; } }; var es_weakMap = createCommonjsModule(function (module) { var enforceIternalState = internalState.enforce; var IS_IE11 = !global_1.ActiveXObject && 'ActiveXObject' in global_1; var isExtensible = Object.isExtensible; var InternalWeakMap; var wrapper = function wrapper(init) { return function WeakMap() { return init(this, arguments.length ? arguments[0] : undefined); }; }; // `WeakMap` constructor // https://tc39.github.io/ecma262/#sec-weakmap-constructor var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak); // IE11 WeakMap frozen keys fix // We can't use feature detection because it crash some old IE builds // https://github.com/zloirock/core-js/issues/485 if (nativeWeakMap && IS_IE11) { InternalWeakMap = collectionWeak.getConstructor(wrapper, 'WeakMap', true); internalMetadata.REQUIRED = true; var WeakMapPrototype = $WeakMap.prototype; var nativeDelete = WeakMapPrototype['delete']; var nativeHas = WeakMapPrototype.has; var nativeGet = WeakMapPrototype.get; var nativeSet = WeakMapPrototype.set; redefineAll(WeakMapPrototype, { 'delete': function _delete(key) { if (isObject(key) && !isExtensible(key)) { var state = enforceIternalState(this); if (!state.frozen) state.frozen = new InternalWeakMap(); return nativeDelete.call(this, key) || state.frozen['delete'](key); } return nativeDelete.call(this, key); }, has: function has(key) { if (isObject(key) && !isExtensible(key)) { var state = enforceIternalState(this); if (!state.frozen) state.frozen = new InternalWeakMap(); return nativeHas.call(this, key) || state.frozen.has(key); } return nativeHas.call(this, key); }, get: function get(key) { if (isObject(key) && !isExtensible(key)) { var state = enforceIternalState(this); if (!state.frozen) state.frozen = new InternalWeakMap(); return nativeHas.call(this, key) ? nativeGet.call(this, key) : state.frozen.get(key); } return nativeGet.call(this, key); }, set: function set(key, value) { if (isObject(key) && !isExtensible(key)) { var state = enforceIternalState(this); if (!state.frozen) state.frozen = new InternalWeakMap(); nativeHas.call(this, key) ? nativeSet.call(this, key, value) : state.frozen.set(key, value); } else nativeSet.call(this, key, value); return this; } }); } }); // https://tc39.github.io/ecma262/#sec-weakset-constructor collection('WeakSet', function (init) { return function WeakSet() { return init(this, arguments.length ? arguments[0] : undefined); }; }, collectionWeak); // iterable DOM collections // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods var domIterables = { CSSRuleList: 0, CSSStyleDeclaration: 0, CSSValueList: 0, ClientRectList: 0, DOMRectList: 0, DOMStringList: 0, DOMTokenList: 1, DataTransferItemList: 0, FileList: 0, HTMLAllCollection: 0, HTMLCollection: 0, HTMLFormElement: 0, HTMLSelectElement: 0, MediaList: 0, MimeTypeArray: 0, NamedNodeMap: 0, NodeList: 1, PaintRequestList: 0, Plugin: 0, PluginArray: 0, SVGLengthList: 0, SVGNumberList: 0, SVGPathSegList: 0, SVGPointList: 0, SVGStringList: 0, SVGTransformList: 0, SourceBufferList: 0, StyleSheetList: 0, TextTrackCueList: 0, TextTrackList: 0, TouchList: 0 }; for (var COLLECTION_NAME in domIterables) { var Collection = global_1[COLLECTION_NAME]; var CollectionPrototype = Collection && Collection.prototype; // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try { createNonEnumerableProperty(CollectionPrototype, 'forEach', arrayForEach); } catch (error) { CollectionPrototype.forEach = arrayForEach; } } var ITERATOR$6 = wellKnownSymbol('iterator'); var TO_STRING_TAG$4 = wellKnownSymbol('toStringTag'); var ArrayValues = es_array_iterator.values; for (var COLLECTION_NAME$1 in domIterables) { var Collection$1 = global_1[COLLECTION_NAME$1]; var CollectionPrototype$1 = Collection$1 && Collection$1.prototype; if (CollectionPrototype$1) { // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype$1[ITERATOR$6] !== ArrayValues) try { createNonEnumerableProperty(CollectionPrototype$1, ITERATOR$6, ArrayValues); } catch (error) { CollectionPrototype$1[ITERATOR$6] = ArrayValues; } if (!CollectionPrototype$1[TO_STRING_TAG$4]) { createNonEnumerableProperty(CollectionPrototype$1, TO_STRING_TAG$4, COLLECTION_NAME$1); } if (domIterables[COLLECTION_NAME$1]) for (var METHOD_NAME in es_array_iterator) { // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype$1[METHOD_NAME] !== es_array_iterator[METHOD_NAME]) try { createNonEnumerableProperty(CollectionPrototype$1, METHOD_NAME, es_array_iterator[METHOD_NAME]); } catch (error) { CollectionPrototype$1[METHOD_NAME] = es_array_iterator[METHOD_NAME]; } } } } var FORCED$l = !global_1.setImmediate || !global_1.clearImmediate; // http://w3c.github.io/setImmediate/ _export({ global: true, bind: true, enumerable: true, forced: FORCED$l }, { // `setImmediate` method // http://w3c.github.io/setImmediate/#si-setImmediate setImmediate: task.set, // `clearImmediate` method // http://w3c.github.io/setImmediate/#si-clearImmediate clearImmediate: task.clear }); var process$4 = global_1.process; var isNode = classofRaw(process$4) == 'process'; // `queueMicrotask` method // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask _export({ global: true, enumerable: true, noTargetGet: true }, { queueMicrotask: function queueMicrotask(fn) { var domain = isNode && process$4.domain; microtask(domain ? domain.bind(fn) : fn); } }); var ITERATOR$7 = wellKnownSymbol('iterator'); var nativeUrl = !fails(function () { var url = new URL('b?a=1&b=2&c=3', 'http://a'); var searchParams = url.searchParams; var result = ''; url.pathname = 'c%20d'; searchParams.forEach(function (value, key) { searchParams['delete']('b'); result += key + value; }); return isPure && !url.toJSON || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR$7] // throws in Edge || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- || result !== 'a1c3' // throws in Safari || new URL('http://x', undefined).host !== 'x'; }); var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 var base = 36; var tMin = 1; var tMax = 26; var skew = 38; var damp = 700; var initialBias = 72; var initialN = 128; // 0x80 var delimiter = '-'; // '\x2D' var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process'; var baseMinusTMin = base - tMin; var floor$8 = Math.floor; var stringFromCharCode = String.fromCharCode; /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. */ var ucs2decode = function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; while (counter < length) { var value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // It's a high surrogate, and there is a next character. var extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // It's an unmatched surrogate; only append this code unit, in case the // next code unit is the high surrogate of a surrogate pair. output.push(value); counter--; } } else { output.push(value); } } return output; }; /** * Converts a digit/integer into a basic code point. */ var digitToBasic = function digitToBasic(digit) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26); }; /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 */ var adapt = function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor$8(delta / damp) : delta >> 1; delta += floor$8(delta / numPoints); for (; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor$8(delta / baseMinusTMin); } return floor$8(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. */ // eslint-disable-next-line max-statements var encode = function encode(input) { var output = []; // Convert the input in UCS-2 to an array of Unicode code points. input = ucs2decode(input); // Cache the length. var inputLength = input.length; // Initialize the state. var n = initialN; var delta = 0; var bias = initialBias; var i, currentValue; // Handle the basic code points. for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } var basicLength = output.length; // number of basic code points. var handledCPCount = basicLength; // number of code points that have been handled; // Finish the basic string with a delimiter unless it's empty. if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next larger one: var m = maxInt; for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , but guard against overflow. var handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor$8((maxInt - delta) / handledCPCountPlusOne)) { throw RangeError(OVERFLOW_ERROR); } delta += (m - n) * handledCPCountPlusOne; n = m; for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue < n && ++delta > maxInt) { throw RangeError(OVERFLOW_ERROR); } if (currentValue == n) { // Represent delta as a generalized variable-length integer. var q = delta; for (var k = base;; /* no condition */ k += base) { var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) break; var qMinusT = q - t; var baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT))); q = floor$8(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); }; var stringPunycodeToAscii = function stringPunycodeToAscii(input) { var encoded = []; var labels = input.toLowerCase().replace(regexSeparators, ".").split('.'); var i, label; for (i = 0; i < labels.length; i++) { label = labels[i]; encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label); } return encoded.join('.'); }; var getIterator = function getIterator(it) { var iteratorMethod = getIteratorMethod(it); if (typeof iteratorMethod != 'function') { throw TypeError(String(it) + ' is not iterable'); } return anObject(iteratorMethod.call(it)); }; var $fetch$1 = getBuiltIn('fetch'); var Headers = getBuiltIn('Headers'); var ITERATOR$8 = wellKnownSymbol('iterator'); var URL_SEARCH_PARAMS = 'URLSearchParams'; var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator'; var setInternalState$9 = internalState.set; var getInternalParamsState = internalState.getterFor(URL_SEARCH_PARAMS); var getInternalIteratorState = internalState.getterFor(URL_SEARCH_PARAMS_ITERATOR); var plus = /\+/g; var sequences = Array(4); var percentSequence = function percentSequence(bytes) { return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi')); }; var percentDecode = function percentDecode(sequence) { try { return decodeURIComponent(sequence); } catch (error) { return sequence; } }; var deserialize = function deserialize(it) { var result = it.replace(plus, ' '); var bytes = 4; try { return decodeURIComponent(result); } catch (error) { while (bytes) { result = result.replace(percentSequence(bytes--), percentDecode); } return result; } }; var find$1 = /[!'()~]|%20/g; var replace = { '!': '%21', "'": '%27', '(': '%28', ')': '%29', '~': '%7E', '%20': '+' }; var replacer = function replacer(match) { return replace[match]; }; var serialize = function serialize(it) { return encodeURIComponent(it).replace(find$1, replacer); }; var parseSearchParams = function parseSearchParams(result, query) { if (query) { var attributes = query.split('&'); var index = 0; var attribute, entry; while (index < attributes.length) { attribute = attributes[index++]; if (attribute.length) { entry = attribute.split('='); result.push({ key: deserialize(entry.shift()), value: deserialize(entry.join('=')) }); } } } }; var updateSearchParams = function updateSearchParams(query) { this.entries.length = 0; parseSearchParams(this.entries, query); }; var validateArgumentsLength = function validateArgumentsLength(passed, required) { if (passed < required) throw TypeError('Not enough arguments'); }; var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) { setInternalState$9(this, { type: URL_SEARCH_PARAMS_ITERATOR, iterator: getIterator(getInternalParamsState(params).entries), kind: kind }); }, 'Iterator', function next() { var state = getInternalIteratorState(this); var kind = state.kind; var step = state.iterator.next(); var entry = step.value; if (!step.done) { step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value]; } return step; }); // `URLSearchParams` constructor // https://url.spec.whatwg.org/#interface-urlsearchparams var URLSearchParamsConstructor = function URLSearchParams() /* init */ { anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS); var init = arguments.length > 0 ? arguments[0] : undefined; var that = this; var entries = []; var iteratorMethod, iterator, next, step, entryIterator, entryNext, first, second, key; setInternalState$9(that, { type: URL_SEARCH_PARAMS, entries: entries, updateURL: function updateURL() { /* empty */ }, updateSearchParams: updateSearchParams }); if (init !== undefined) { if (isObject(init)) { iteratorMethod = getIteratorMethod(init); if (typeof iteratorMethod === 'function') { iterator = iteratorMethod.call(init); next = iterator.next; while (!(step = next.call(iterator)).done) { entryIterator = getIterator(anObject(step.value)); entryNext = entryIterator.next; if ((first = entryNext.call(entryIterator)).done || (second = entryNext.call(entryIterator)).done || !entryNext.call(entryIterator).done) throw TypeError('Expected sequence with length 2'); entries.push({ key: first.value + '', value: second.value + '' }); } } else for (key in init) { if (has(init, key)) entries.push({ key: key, value: init[key] + '' }); } } else { parseSearchParams(entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : init + ''); } } }; var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype; redefineAll(URLSearchParamsPrototype, { // `URLSearchParams.prototype.appent` method // https://url.spec.whatwg.org/#dom-urlsearchparams-append append: function append(name, value) { validateArgumentsLength(arguments.length, 2); var state = getInternalParamsState(this); state.entries.push({ key: name + '', value: value + '' }); state.updateURL(); }, // `URLSearchParams.prototype.delete` method // https://url.spec.whatwg.org/#dom-urlsearchparams-delete 'delete': function _delete(name) { validateArgumentsLength(arguments.length, 1); var state = getInternalParamsState(this); var entries = state.entries; var key = name + ''; var index = 0; while (index < entries.length) { if (entries[index].key === key) entries.splice(index, 1);else index++; } state.updateURL(); }, // `URLSearchParams.prototype.get` method // https://url.spec.whatwg.org/#dom-urlsearchparams-get get: function get(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = name + ''; var index = 0; for (; index < entries.length; index++) { if (entries[index].key === key) return entries[index].value; } return null; }, // `URLSearchParams.prototype.getAll` method // https://url.spec.whatwg.org/#dom-urlsearchparams-getall getAll: function getAll(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = name + ''; var result = []; var index = 0; for (; index < entries.length; index++) { if (entries[index].key === key) result.push(entries[index].value); } return result; }, // `URLSearchParams.prototype.has` method // https://url.spec.whatwg.org/#dom-urlsearchparams-has has: function has(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = name + ''; var index = 0; while (index < entries.length) { if (entries[index++].key === key) return true; } return false; }, // `URLSearchParams.prototype.set` method // https://url.spec.whatwg.org/#dom-urlsearchparams-set set: function set(name, value) { validateArgumentsLength(arguments.length, 1); var state = getInternalParamsState(this); var entries = state.entries; var found = false; var key = name + ''; var val = value + ''; var index = 0; var entry; for (; index < entries.length; index++) { entry = entries[index]; if (entry.key === key) { if (found) entries.splice(index--, 1);else { found = true; entry.value = val; } } } if (!found) entries.push({ key: key, value: val }); state.updateURL(); }, // `URLSearchParams.prototype.sort` method // https://url.spec.whatwg.org/#dom-urlsearchparams-sort sort: function sort() { var state = getInternalParamsState(this); var entries = state.entries; // Array#sort is not stable in some engines var slice = entries.slice(); var entry, entriesIndex, sliceIndex; entries.length = 0; for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) { entry = slice[sliceIndex]; for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) { if (entries[entriesIndex].key > entry.key) { entries.splice(entriesIndex, 0, entry); break; } } if (entriesIndex === sliceIndex) entries.push(entry); } state.updateURL(); }, // `URLSearchParams.prototype.forEach` method forEach: function forEach(callback /* , thisArg */ ) { var entries = getInternalParamsState(this).entries; var boundFunction = functionBindContext(callback, arguments.length > 1 ? arguments[1] : undefined, 3); var index = 0; var entry; while (index < entries.length) { entry = entries[index++]; boundFunction(entry.value, entry.key, this); } }, // `URLSearchParams.prototype.keys` method keys: function keys() { return new URLSearchParamsIterator(this, 'keys'); }, // `URLSearchParams.prototype.values` method values: function values() { return new URLSearchParamsIterator(this, 'values'); }, // `URLSearchParams.prototype.entries` method entries: function entries() { return new URLSearchParamsIterator(this, 'entries'); } }, { enumerable: true }); // `URLSearchParams.prototype[@@iterator]` method redefine(URLSearchParamsPrototype, ITERATOR$8, URLSearchParamsPrototype.entries); // `URLSearchParams.prototype.toString` method // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior redefine(URLSearchParamsPrototype, 'toString', function toString() { var entries = getInternalParamsState(this).entries; var result = []; var index = 0; var entry; while (index < entries.length) { entry = entries[index++]; result.push(serialize(entry.key) + '=' + serialize(entry.value)); } return result.join('&'); }, { enumerable: true }); setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS); _export({ global: true, forced: !nativeUrl }, { URLSearchParams: URLSearchParamsConstructor }); // Wrap `fetch` for correct work with polyfilled `URLSearchParams` // https://github.com/zloirock/core-js/issues/674 if (!nativeUrl && typeof $fetch$1 == 'function' && typeof Headers == 'function') { _export({ global: true, enumerable: true, forced: true }, { fetch: function fetch(input /* , init */ ) { var args = [input]; var init, body, headers; if (arguments.length > 1) { init = arguments[1]; if (isObject(init)) { body = init.body; if (classof(body) === URL_SEARCH_PARAMS) { headers = init.headers ? new Headers(init.headers) : new Headers(); if (!headers.has('content-type')) { headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); } init = objectCreate(init, { body: createPropertyDescriptor(0, String(body)), headers: createPropertyDescriptor(0, headers) }); } } args.push(init); } return $fetch$1.apply(this, args); } }); } var web_urlSearchParams = { URLSearchParams: URLSearchParamsConstructor, getState: getInternalParamsState }; var codeAt$1 = stringMultibyte.codeAt; var NativeURL = global_1.URL; var URLSearchParams$1 = web_urlSearchParams.URLSearchParams; var getInternalSearchParamsState = web_urlSearchParams.getState; var setInternalState$a = internalState.set; var getInternalURLState = internalState.getterFor('URL'); var floor$9 = Math.floor; var pow$4 = Math.pow; var INVALID_AUTHORITY = 'Invalid authority'; var INVALID_SCHEME = 'Invalid scheme'; var INVALID_HOST = 'Invalid host'; var INVALID_PORT = 'Invalid port'; var ALPHA = /[A-Za-z]/; var ALPHANUMERIC = /[\d+-.A-Za-z]/; var DIGIT = /\d/; var HEX_START = /^(0x|0X)/; var OCT = /^[0-7]+$/; var DEC = /^\d+$/; var HEX = /^[\dA-Fa-f]+$/; // eslint-disable-next-line no-control-regex var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/; // eslint-disable-next-line no-control-regex var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/; // eslint-disable-next-line no-control-regex var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g; // eslint-disable-next-line no-control-regex var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g; var EOF; var parseHost = function parseHost(url, input) { var result, codePoints, index; if (input.charAt(0) == '[') { if (input.charAt(input.length - 1) != ']') return INVALID_HOST; result = parseIPv6(input.slice(1, -1)); if (!result) return INVALID_HOST; url.host = result; // opaque host } else if (!isSpecial(url)) { if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST; result = ''; codePoints = arrayFrom(input); for (index = 0; index < codePoints.length; index++) { result += percentEncode(codePoints[index], C0ControlPercentEncodeSet); } url.host = result; } else { input = stringPunycodeToAscii(input); if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST; result = parseIPv4(input); if (result === null) return INVALID_HOST; url.host = result; } }; var parseIPv4 = function parseIPv4(input) { var parts = input.split('.'); var partsLength, numbers, index, part, radix, number, ipv4; if (parts.length && parts[parts.length - 1] == '') { parts.pop(); } partsLength = parts.length; if (partsLength > 4) return input; numbers = []; for (index = 0; index < partsLength; index++) { part = parts[index]; if (part == '') return input; radix = 10; if (part.length > 1 && part.charAt(0) == '0') { radix = HEX_START.test(part) ? 16 : 8; part = part.slice(radix == 8 ? 1 : 2); } if (part === '') { number = 0; } else { if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input; number = parseInt(part, radix); } numbers.push(number); } for (index = 0; index < partsLength; index++) { number = numbers[index]; if (index == partsLength - 1) { if (number >= pow$4(256, 5 - partsLength)) return null; } else if (number > 255) return null; } ipv4 = numbers.pop(); for (index = 0; index < numbers.length; index++) { ipv4 += numbers[index] * pow$4(256, 3 - index); } return ipv4; }; // eslint-disable-next-line max-statements var parseIPv6 = function parseIPv6(input) { var address = [0, 0, 0, 0, 0, 0, 0, 0]; var pieceIndex = 0; var compress = null; var pointer = 0; var value, length, numbersSeen, ipv4Piece, number, swaps, swap; var _char = function _char() { return input.charAt(pointer); }; if (_char() == ':') { if (input.charAt(1) != ':') return; pointer += 2; pieceIndex++; compress = pieceIndex; } while (_char()) { if (pieceIndex == 8) return; if (_char() == ':') { if (compress !== null) return; pointer++; pieceIndex++; compress = pieceIndex; continue; } value = length = 0; while (length < 4 && HEX.test(_char())) { value = value * 16 + parseInt(_char(), 16); pointer++; length++; } if (_char() == '.') { if (length == 0) return; pointer -= length; if (pieceIndex > 6) return; numbersSeen = 0; while (_char()) { ipv4Piece = null; if (numbersSeen > 0) { if (_char() == '.' && numbersSeen < 4) pointer++;else return; } if (!DIGIT.test(_char())) return; while (DIGIT.test(_char())) { number = parseInt(_char(), 10); if (ipv4Piece === null) ipv4Piece = number;else if (ipv4Piece == 0) return;else ipv4Piece = ipv4Piece * 10 + number; if (ipv4Piece > 255) return; pointer++; } address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece; numbersSeen++; if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++; } if (numbersSeen != 4) return; break; } else if (_char() == ':') { pointer++; if (!_char()) return; } else if (_char()) return; address[pieceIndex++] = value; } if (compress !== null) { swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex != 0 && swaps > 0) { swap = address[pieceIndex]; address[pieceIndex--] = address[compress + swaps - 1]; address[compress + --swaps] = swap; } } else if (pieceIndex != 8) return; return address; }; var findLongestZeroSequence = function findLongestZeroSequence(ipv6) { var maxIndex = null; var maxLength = 1; var currStart = null; var currLength = 0; var index = 0; for (; index < 8; index++) { if (ipv6[index] !== 0) { if (currLength > maxLength) { maxIndex = currStart; maxLength = currLength; } currStart = null; currLength = 0; } else { if (currStart === null) currStart = index; ++currLength; } } if (currLength > maxLength) { maxIndex = currStart; maxLength = currLength; } return maxIndex; }; var serializeHost = function serializeHost(host) { var result, index, compress, ignore0; // ipv4 if (typeof host == 'number') { result = []; for (index = 0; index < 4; index++) { result.unshift(host % 256); host = floor$9(host / 256); } return result.join('.'); // ipv6 } else if (_typeof(host) == 'object') { result = ''; compress = findLongestZeroSequence(host); for (index = 0; index < 8; index++) { if (ignore0 && host[index] === 0) continue; if (ignore0) ignore0 = false; if (compress === index) { result += index ? ':' : '::'; ignore0 = true; } else { result += host[index].toString(16); if (index < 7) result += ':'; } } return '[' + result + ']'; } return host; }; var C0ControlPercentEncodeSet = {}; var fragmentPercentEncodeSet = objectAssign({}, C0ControlPercentEncodeSet, { ' ': 1, '"': 1, '<': 1, '>': 1, '`': 1 }); var pathPercentEncodeSet = objectAssign({}, fragmentPercentEncodeSet, { '#': 1, '?': 1, '{': 1, '}': 1 }); var userinfoPercentEncodeSet = objectAssign({}, pathPercentEncodeSet, { '/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1 }); var percentEncode = function percentEncode(_char2, set) { var code = codeAt$1(_char2, 0); return code > 0x20 && code < 0x7F && !has(set, _char2) ? _char2 : encodeURIComponent(_char2); }; var specialSchemes = { ftp: 21, file: null, http: 80, https: 443, ws: 80, wss: 443 }; var isSpecial = function isSpecial(url) { return has(specialSchemes, url.scheme); }; var includesCredentials = function includesCredentials(url) { return url.username != '' || url.password != ''; }; var cannotHaveUsernamePasswordPort = function cannotHaveUsernamePasswordPort(url) { return !url.host || url.cannotBeABaseURL || url.scheme == 'file'; }; var isWindowsDriveLetter = function isWindowsDriveLetter(string, normalized) { var second; return string.length == 2 && ALPHA.test(string.charAt(0)) && ((second = string.charAt(1)) == ':' || !normalized && second == '|'); }; var startsWithWindowsDriveLetter = function startsWithWindowsDriveLetter(string) { var third; return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && (string.length == 2 || (third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#'); }; var shortenURLsPath = function shortenURLsPath(url) { var path = url.path; var pathSize = path.length; if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) { path.pop(); } }; var isSingleDot = function isSingleDot(segment) { return segment === '.' || segment.toLowerCase() === '%2e'; }; var isDoubleDot = function isDoubleDot(segment) { segment = segment.toLowerCase(); return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e'; }; // States: var SCHEME_START = {}; var SCHEME = {}; var NO_SCHEME = {}; var SPECIAL_RELATIVE_OR_AUTHORITY = {}; var PATH_OR_AUTHORITY = {}; var RELATIVE = {}; var RELATIVE_SLASH = {}; var SPECIAL_AUTHORITY_SLASHES = {}; var SPECIAL_AUTHORITY_IGNORE_SLASHES = {}; var AUTHORITY = {}; var HOST = {}; var HOSTNAME = {}; var PORT = {}; var FILE = {}; var FILE_SLASH = {}; var FILE_HOST = {}; var PATH_START = {}; var PATH = {}; var CANNOT_BE_A_BASE_URL_PATH = {}; var QUERY = {}; var FRAGMENT = {}; // eslint-disable-next-line max-statements var parseURL = function parseURL(url, input, stateOverride, base) { var state = stateOverride || SCHEME_START; var pointer = 0; var buffer = ''; var seenAt = false; var seenBracket = false; var seenPasswordToken = false; var codePoints, _char3, bufferCodePoints, failure; if (!stateOverride) { url.scheme = ''; url.username = ''; url.password = ''; url.host = null; url.port = null; url.path = []; url.query = null; url.fragment = null; url.cannotBeABaseURL = false; input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, ''); } input = input.replace(TAB_AND_NEW_LINE, ''); codePoints = arrayFrom(input); while (pointer <= codePoints.length) { _char3 = codePoints[pointer]; switch (state) { case SCHEME_START: if (_char3 && ALPHA.test(_char3)) { buffer += _char3.toLowerCase(); state = SCHEME; } else if (!stateOverride) { state = NO_SCHEME; continue; } else return INVALID_SCHEME; break; case SCHEME: if (_char3 && (ALPHANUMERIC.test(_char3) || _char3 == '+' || _char3 == '-' || _char3 == '.')) { buffer += _char3.toLowerCase(); } else if (_char3 == ':') { if (stateOverride && (isSpecial(url) != has(specialSchemes, buffer) || buffer == 'file' && (includesCredentials(url) || url.port !== null) || url.scheme == 'file' && !url.host)) return; url.scheme = buffer; if (stateOverride) { if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null; return; } buffer = ''; if (url.scheme == 'file') { state = FILE; } else if (isSpecial(url) && base && base.scheme == url.scheme) { state = SPECIAL_RELATIVE_OR_AUTHORITY; } else if (isSpecial(url)) { state = SPECIAL_AUTHORITY_SLASHES; } else if (codePoints[pointer + 1] == '/') { state = PATH_OR_AUTHORITY; pointer++; } else { url.cannotBeABaseURL = true; url.path.push(''); state = CANNOT_BE_A_BASE_URL_PATH; } } else if (!stateOverride) { buffer = ''; state = NO_SCHEME; pointer = 0; continue; } else return INVALID_SCHEME; break; case NO_SCHEME: if (!base || base.cannotBeABaseURL && _char3 != '#') return INVALID_SCHEME; if (base.cannotBeABaseURL && _char3 == '#') { url.scheme = base.scheme; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; url.cannotBeABaseURL = true; state = FRAGMENT; break; } state = base.scheme == 'file' ? FILE : RELATIVE; continue; case SPECIAL_RELATIVE_OR_AUTHORITY: if (_char3 == '/' && codePoints[pointer + 1] == '/') { state = SPECIAL_AUTHORITY_IGNORE_SLASHES; pointer++; } else { state = RELATIVE; continue; } break; case PATH_OR_AUTHORITY: if (_char3 == '/') { state = AUTHORITY; break; } else { state = PATH; continue; } case RELATIVE: url.scheme = base.scheme; if (_char3 == EOF) { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = base.query; } else if (_char3 == '/' || _char3 == '\\' && isSpecial(url)) { state = RELATIVE_SLASH; } else if (_char3 == '?') { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = ''; state = QUERY; } else if (_char3 == '#') { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; state = FRAGMENT; } else { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.path.pop(); state = PATH; continue; } break; case RELATIVE_SLASH: if (isSpecial(url) && (_char3 == '/' || _char3 == '\\')) { state = SPECIAL_AUTHORITY_IGNORE_SLASHES; } else if (_char3 == '/') { state = AUTHORITY; } else { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; state = PATH; continue; } break; case SPECIAL_AUTHORITY_SLASHES: state = SPECIAL_AUTHORITY_IGNORE_SLASHES; if (_char3 != '/' || buffer.charAt(pointer + 1) != '/') continue; pointer++; break; case SPECIAL_AUTHORITY_IGNORE_SLASHES: if (_char3 != '/' && _char3 != '\\') { state = AUTHORITY; continue; } break; case AUTHORITY: if (_char3 == '@') { if (seenAt) buffer = '%40' + buffer; seenAt = true; bufferCodePoints = arrayFrom(buffer); for (var i = 0; i < bufferCodePoints.length; i++) { var codePoint = bufferCodePoints[i]; if (codePoint == ':' && !seenPasswordToken) { seenPasswordToken = true; continue; } var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet); if (seenPasswordToken) url.password += encodedCodePoints;else url.username += encodedCodePoints; } buffer = ''; } else if (_char3 == EOF || _char3 == '/' || _char3 == '?' || _char3 == '#' || _char3 == '\\' && isSpecial(url)) { if (seenAt && buffer == '') return INVALID_AUTHORITY; pointer -= arrayFrom(buffer).length + 1; buffer = ''; state = HOST; } else buffer += _char3; break; case HOST: case HOSTNAME: if (stateOverride && url.scheme == 'file') { state = FILE_HOST; continue; } else if (_char3 == ':' && !seenBracket) { if (buffer == '') return INVALID_HOST; failure = parseHost(url, buffer); if (failure) return failure; buffer = ''; state = PORT; if (stateOverride == HOSTNAME) return; } else if (_char3 == EOF || _char3 == '/' || _char3 == '?' || _char3 == '#' || _char3 == '\\' && isSpecial(url)) { if (isSpecial(url) && buffer == '') return INVALID_HOST; if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return; failure = parseHost(url, buffer); if (failure) return failure; buffer = ''; state = PATH_START; if (stateOverride) return; continue; } else { if (_char3 == '[') seenBracket = true;else if (_char3 == ']') seenBracket = false; buffer += _char3; } break; case PORT: if (DIGIT.test(_char3)) { buffer += _char3; } else if (_char3 == EOF || _char3 == '/' || _char3 == '?' || _char3 == '#' || _char3 == '\\' && isSpecial(url) || stateOverride) { if (buffer != '') { var port = parseInt(buffer, 10); if (port > 0xFFFF) return INVALID_PORT; url.port = isSpecial(url) && port === specialSchemes[url.scheme] ? null : port; buffer = ''; } if (stateOverride) return; state = PATH_START; continue; } else return INVALID_PORT; break; case FILE: url.scheme = 'file'; if (_char3 == '/' || _char3 == '\\') state = FILE_SLASH;else if (base && base.scheme == 'file') { if (_char3 == EOF) { url.host = base.host; url.path = base.path.slice(); url.query = base.query; } else if (_char3 == '?') { url.host = base.host; url.path = base.path.slice(); url.query = ''; state = QUERY; } else if (_char3 == '#') { url.host = base.host; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; state = FRAGMENT; } else { if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { url.host = base.host; url.path = base.path.slice(); shortenURLsPath(url); } state = PATH; continue; } } else { state = PATH; continue; } break; case FILE_SLASH: if (_char3 == '/' || _char3 == '\\') { state = FILE_HOST; break; } if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]);else url.host = base.host; } state = PATH; continue; case FILE_HOST: if (_char3 == EOF || _char3 == '/' || _char3 == '\\' || _char3 == '?' || _char3 == '#') { if (!stateOverride && isWindowsDriveLetter(buffer)) { state = PATH; } else if (buffer == '') { url.host = ''; if (stateOverride) return; state = PATH_START; } else { failure = parseHost(url, buffer); if (failure) return failure; if (url.host == 'localhost') url.host = ''; if (stateOverride) return; buffer = ''; state = PATH_START; } continue; } else buffer += _char3; break; case PATH_START: if (isSpecial(url)) { state = PATH; if (_char3 != '/' && _char3 != '\\') continue; } else if (!stateOverride && _char3 == '?') { url.query = ''; state = QUERY; } else if (!stateOverride && _char3 == '#') { url.fragment = ''; state = FRAGMENT; } else if (_char3 != EOF) { state = PATH; if (_char3 != '/') continue; } break; case PATH: if (_char3 == EOF || _char3 == '/' || _char3 == '\\' && isSpecial(url) || !stateOverride && (_char3 == '?' || _char3 == '#')) { if (isDoubleDot(buffer)) { shortenURLsPath(url); if (_char3 != '/' && !(_char3 == '\\' && isSpecial(url))) { url.path.push(''); } } else if (isSingleDot(buffer)) { if (_char3 != '/' && !(_char3 == '\\' && isSpecial(url))) { url.path.push(''); } } else { if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) { if (url.host) url.host = ''; buffer = buffer.charAt(0) + ':'; // normalize windows drive letter } url.path.push(buffer); } buffer = ''; if (url.scheme == 'file' && (_char3 == EOF || _char3 == '?' || _char3 == '#')) { while (url.path.length > 1 && url.path[0] === '') { url.path.shift(); } } if (_char3 == '?') { url.query = ''; state = QUERY; } else if (_char3 == '#') { url.fragment = ''; state = FRAGMENT; } } else { buffer += percentEncode(_char3, pathPercentEncodeSet); } break; case CANNOT_BE_A_BASE_URL_PATH: if (_char3 == '?') { url.query = ''; state = QUERY; } else if (_char3 == '#') { url.fragment = ''; state = FRAGMENT; } else if (_char3 != EOF) { url.path[0] += percentEncode(_char3, C0ControlPercentEncodeSet); } break; case QUERY: if (!stateOverride && _char3 == '#') { url.fragment = ''; state = FRAGMENT; } else if (_char3 != EOF) { if (_char3 == "'" && isSpecial(url)) url.query += '%27';else if (_char3 == '#') url.query += '%23';else url.query += percentEncode(_char3, C0ControlPercentEncodeSet); } break; case FRAGMENT: if (_char3 != EOF) url.fragment += percentEncode(_char3, fragmentPercentEncodeSet); break; } pointer++; } }; // `URL` constructor // https://url.spec.whatwg.org/#url-class var URLConstructor = function URL(url /* , base */ ) { var that = anInstance(this, URLConstructor, 'URL'); var base = arguments.length > 1 ? arguments[1] : undefined; var urlString = String(url); var state = setInternalState$a(that, { type: 'URL' }); var baseState, failure; if (base !== undefined) { if (base instanceof URLConstructor) baseState = getInternalURLState(base);else { failure = parseURL(baseState = {}, String(base)); if (failure) throw TypeError(failure); } } failure = parseURL(state, urlString, null, baseState); if (failure) throw TypeError(failure); var searchParams = state.searchParams = new URLSearchParams$1(); var searchParamsState = getInternalSearchParamsState(searchParams); searchParamsState.updateSearchParams(state.query); searchParamsState.updateURL = function () { state.query = String(searchParams) || null; }; if (!descriptors) { that.href = serializeURL.call(that); that.origin = getOrigin.call(that); that.protocol = getProtocol.call(that); that.username = getUsername.call(that); that.password = getPassword.call(that); that.host = getHost.call(that); that.hostname = getHostname.call(that); that.port = getPort.call(that); that.pathname = getPathname.call(that); that.search = getSearch.call(that); that.searchParams = getSearchParams.call(that); that.hash = getHash.call(that); } }; var URLPrototype = URLConstructor.prototype; var serializeURL = function serializeURL() { var url = getInternalURLState(this); var scheme = url.scheme; var username = url.username; var password = url.password; var host = url.host; var port = url.port; var path = url.path; var query = url.query; var fragment = url.fragment; var output = scheme + ':'; if (host !== null) { output += '//'; if (includesCredentials(url)) { output += username + (password ? ':' + password : '') + '@'; } output += serializeHost(host); if (port !== null) output += ':' + port; } else if (scheme == 'file') output += '//'; output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; if (query !== null) output += '?' + query; if (fragment !== null) output += '#' + fragment; return output; }; var getOrigin = function getOrigin() { var url = getInternalURLState(this); var scheme = url.scheme; var port = url.port; if (scheme == 'blob') try { return new URL(scheme.path[0]).origin; } catch (error) { return 'null'; } if (scheme == 'file' || !isSpecial(url)) return 'null'; return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : ''); }; var getProtocol = function getProtocol() { return getInternalURLState(this).scheme + ':'; }; var getUsername = function getUsername() { return getInternalURLState(this).username; }; var getPassword = function getPassword() { return getInternalURLState(this).password; }; var getHost = function getHost() { var url = getInternalURLState(this); var host = url.host; var port = url.port; return host === null ? '' : port === null ? serializeHost(host) : serializeHost(host) + ':' + port; }; var getHostname = function getHostname() { var host = getInternalURLState(this).host; return host === null ? '' : serializeHost(host); }; var getPort = function getPort() { var port = getInternalURLState(this).port; return port === null ? '' : String(port); }; var getPathname = function getPathname() { var url = getInternalURLState(this); var path = url.path; return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; }; var getSearch = function getSearch() { var query = getInternalURLState(this).query; return query ? '?' + query : ''; }; var getSearchParams = function getSearchParams() { return getInternalURLState(this).searchParams; }; var getHash = function getHash() { var fragment = getInternalURLState(this).fragment; return fragment ? '#' + fragment : ''; }; var accessorDescriptor = function accessorDescriptor(getter, setter) { return { get: getter, set: setter, configurable: true, enumerable: true }; }; if (descriptors) { objectDefineProperties(URLPrototype, { // `URL.prototype.href` accessors pair // https://url.spec.whatwg.org/#dom-url-href href: accessorDescriptor(serializeURL, function (href) { var url = getInternalURLState(this); var urlString = String(href); var failure = parseURL(url, urlString); if (failure) throw TypeError(failure); getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); }), // `URL.prototype.origin` getter // https://url.spec.whatwg.org/#dom-url-origin origin: accessorDescriptor(getOrigin), // `URL.prototype.protocol` accessors pair // https://url.spec.whatwg.org/#dom-url-protocol protocol: accessorDescriptor(getProtocol, function (protocol) { var url = getInternalURLState(this); parseURL(url, String(protocol) + ':', SCHEME_START); }), // `URL.prototype.username` accessors pair // https://url.spec.whatwg.org/#dom-url-username username: accessorDescriptor(getUsername, function (username) { var url = getInternalURLState(this); var codePoints = arrayFrom(String(username)); if (cannotHaveUsernamePasswordPort(url)) return; url.username = ''; for (var i = 0; i < codePoints.length; i++) { url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet); } }), // `URL.prototype.password` accessors pair // https://url.spec.whatwg.org/#dom-url-password password: accessorDescriptor(getPassword, function (password) { var url = getInternalURLState(this); var codePoints = arrayFrom(String(password)); if (cannotHaveUsernamePasswordPort(url)) return; url.password = ''; for (var i = 0; i < codePoints.length; i++) { url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet); } }), // `URL.prototype.host` accessors pair // https://url.spec.whatwg.org/#dom-url-host host: accessorDescriptor(getHost, function (host) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; parseURL(url, String(host), HOST); }), // `URL.prototype.hostname` accessors pair // https://url.spec.whatwg.org/#dom-url-hostname hostname: accessorDescriptor(getHostname, function (hostname) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; parseURL(url, String(hostname), HOSTNAME); }), // `URL.prototype.port` accessors pair // https://url.spec.whatwg.org/#dom-url-port port: accessorDescriptor(getPort, function (port) { var url = getInternalURLState(this); if (cannotHaveUsernamePasswordPort(url)) return; port = String(port); if (port == '') url.port = null;else parseURL(url, port, PORT); }), // `URL.prototype.pathname` accessors pair // https://url.spec.whatwg.org/#dom-url-pathname pathname: accessorDescriptor(getPathname, function (pathname) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; url.path = []; parseURL(url, pathname + '', PATH_START); }), // `URL.prototype.search` accessors pair // https://url.spec.whatwg.org/#dom-url-search search: accessorDescriptor(getSearch, function (search) { var url = getInternalURLState(this); search = String(search); if (search == '') { url.query = null; } else { if ('?' == search.charAt(0)) search = search.slice(1); url.query = ''; parseURL(url, search, QUERY); } getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); }), // `URL.prototype.searchParams` getter // https://url.spec.whatwg.org/#dom-url-searchparams searchParams: accessorDescriptor(getSearchParams), // `URL.prototype.hash` accessors pair // https://url.spec.whatwg.org/#dom-url-hash hash: accessorDescriptor(getHash, function (hash) { var url = getInternalURLState(this); hash = String(hash); if (hash == '') { url.fragment = null; return; } if ('#' == hash.charAt(0)) hash = hash.slice(1); url.fragment = ''; parseURL(url, hash, FRAGMENT); }) }); } // `URL.prototype.toJSON` method // https://url.spec.whatwg.org/#dom-url-tojson redefine(URLPrototype, 'toJSON', function toJSON() { return serializeURL.call(this); }, { enumerable: true }); // `URL.prototype.toString` method // https://url.spec.whatwg.org/#URL-stringification-behavior redefine(URLPrototype, 'toString', function toString() { return serializeURL.call(this); }, { enumerable: true }); if (NativeURL) { var nativeCreateObjectURL = NativeURL.createObjectURL; var nativeRevokeObjectURL = NativeURL.revokeObjectURL; // `URL.createObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL // eslint-disable-next-line no-unused-vars if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) { return nativeCreateObjectURL.apply(NativeURL, arguments); }); // `URL.revokeObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL // eslint-disable-next-line no-unused-vars if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) { return nativeRevokeObjectURL.apply(NativeURL, arguments); }); } setToStringTag(URLConstructor, 'URL'); _export({ global: true, forced: !nativeUrl, sham: !descriptors }, { URL: URLConstructor }); // https://url.spec.whatwg.org/#dom-url-tojson _export({ target: 'URL', proto: true, enumerable: true }, { toJSON: function toJSON() { return URL.prototype.toString.call(this); } }); var runtime_1 = createCommonjsModule(function (module) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var runtime = function (exports) { var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined$1; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); return obj[key]; } try { // IE 8 has a broken Object.defineProperty that only works on DOM objects. define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } exports.isGeneratorFunction = function (genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports.mark = function (genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; define(genFun, toStringTagSymbol, "GeneratorFunction"); } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. exports.awrap = function (arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && _typeof(value) === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function (unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function (error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined$1) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined$1; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (!info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined$1; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function () { return this; }; Gp.toString = function () { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined$1; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined$1, done: true }; } Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined$1; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined$1; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined$1; } } } }, stop: function stop() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined$1; } return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function complete(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined$1; } return ContinueSentinel; } }; // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. module.exports ); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { // This module should not be running in strict mode, so the above // assignment should always work unless something is misconfigured. Just // in case runtime.js accidentally runs in strict mode, we can escape // strict mode using a global Function call. This could conceivably fail // if a Content Security Policy forbids using Function, but in that case // the proper solution is to fix the accidental strict mode problem. If // you've misconfigured your bundler to force strict mode and applied a // CSP to forbid Function, and you're not willing to fix either of those // problems, please detail your unique predicament in a GitHub issue. Function("r", "regeneratorRuntime = r")(runtime); } }); // http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/ /** * * @param {Event} ev * @returns {void} */ function touchHandler(ev) { var changedTouches = ev.changedTouches, first = changedTouches[0]; var type = ''; switch (ev.type) { case 'touchstart': type = 'mousedown'; break; case 'touchmove': type = 'mousemove'; break; case 'touchend': type = 'mouseup'; break; default: return; } var screenX = first.screenX, screenY = first.screenY, clientX = first.clientX, clientY = first.clientY; // eslint-disable-line no-shadow var simulatedEvent = new MouseEvent(type, { // Event interface bubbles: true, cancelable: true, // UIEvent interface view: window, detail: 1, // click count // MouseEvent interface (customized) screenX: screenX, screenY: screenY, clientX: clientX, clientY: clientY, // MouseEvent interface (defaults) - these could be removed ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, button: 0, // main button (usually left) relatedTarget: null }); if (changedTouches.length < 2) { first.target.dispatchEvent(simulatedEvent); ev.preventDefault(); } } document.addEventListener('touchstart', touchHandler, true); document.addEventListener('touchmove', touchHandler, true); document.addEventListener('touchend', touchHandler, true); document.addEventListener('touchcancel', touchHandler, true); /** * Namespaces or tools therefor. * @module namespaces * @license MIT */ /** * Common namepaces constants in alpha order. * @enum {string} * @type {PlainObject} * @memberof module:namespaces */ var NS = { HTML: 'http://www.w3.org/1999/xhtml', MATH: 'http://www.w3.org/1998/Math/MathML', SE: 'http://svg-edit.googlecode.com', SVG: 'http://www.w3.org/2000/svg', XLINK: 'http://www.w3.org/1999/xlink', XML: 'http://www.w3.org/XML/1998/namespace', XMLNS: 'http://www.w3.org/2000/xmlns/' // see http://www.w3.org/TR/REC-xml-names/#xmlReserved }; /** * @function module:namespaces.getReverseNS * @returns {string} The NS with key values switched and lowercase */ var getReverseNS = function getReverseNS() { var reverseNS = {}; Object.entries(NS).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), name = _ref2[0], URI = _ref2[1]; reverseNS[URI] = name.toLowerCase(); }); return reverseNS; }; /* eslint-disable import/unambiguous, max-len */ /* globals SVGPathSeg, SVGPathSegMovetoRel, SVGPathSegMovetoAbs, SVGPathSegMovetoRel, SVGPathSegLinetoRel, SVGPathSegLinetoAbs, SVGPathSegLinetoHorizontalRel, SVGPathSegLinetoHorizontalAbs, SVGPathSegLinetoVerticalRel, SVGPathSegLinetoVerticalAbs, SVGPathSegClosePath, SVGPathSegCurvetoCubicRel, SVGPathSegCurvetoCubicAbs, SVGPathSegCurvetoCubicSmoothRel, SVGPathSegCurvetoCubicSmoothAbs, SVGPathSegCurvetoQuadraticRel, SVGPathSegCurvetoQuadraticAbs, SVGPathSegCurvetoQuadraticSmoothRel, SVGPathSegCurvetoQuadraticSmoothAbs, SVGPathSegArcRel, SVGPathSegArcAbs */ /** * SVGPathSeg API polyfill * https://github.com/progers/pathseg * * This is a drop-in replacement for the `SVGPathSeg` and `SVGPathSegList` APIs * that were removed from SVG2 ({@link https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html}), * including the latest spec changes which were implemented in Firefox 43 and * Chrome 46. */ /* eslint-disable no-shadow, class-methods-use-this, jsdoc/require-jsdoc */ // Linting: We avoid `no-shadow` as ESLint thinks these are still available globals // Linting: We avoid `class-methods-use-this` as this is a polyfill that must // follow the conventions (function () { if (!('SVGPathSeg' in window)) { // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg var _SVGPathSeg = /*#__PURE__*/function () { function _SVGPathSeg(type, typeAsLetter, owningPathSegList) { _classCallCheck(this, _SVGPathSeg); this.pathSegType = type; this.pathSegTypeAsLetter = typeAsLetter; this._owningPathSegList = owningPathSegList; } // Notify owning PathSegList on any changes so they can be synchronized back to the path element. _createClass(_SVGPathSeg, [{ key: "_segmentChanged", value: function _segmentChanged() { if (this._owningPathSegList) { this._owningPathSegList.segmentChanged(this); } } }]); return _SVGPathSeg; }(); _SVGPathSeg.prototype.classname = 'SVGPathSeg'; _SVGPathSeg.PATHSEG_UNKNOWN = 0; _SVGPathSeg.PATHSEG_CLOSEPATH = 1; _SVGPathSeg.PATHSEG_MOVETO_ABS = 2; _SVGPathSeg.PATHSEG_MOVETO_REL = 3; _SVGPathSeg.PATHSEG_LINETO_ABS = 4; _SVGPathSeg.PATHSEG_LINETO_REL = 5; _SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6; _SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7; _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8; _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9; _SVGPathSeg.PATHSEG_ARC_ABS = 10; _SVGPathSeg.PATHSEG_ARC_REL = 11; _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12; _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13; _SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14; _SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15; _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16; _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17; _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18; _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19; var _SVGPathSegClosePath = /*#__PURE__*/function (_SVGPathSeg2) { _inherits(_SVGPathSegClosePath, _SVGPathSeg2); var _super = _createSuper(_SVGPathSegClosePath); function _SVGPathSegClosePath(owningPathSegList) { _classCallCheck(this, _SVGPathSegClosePath); return _super.call(this, _SVGPathSeg.PATHSEG_CLOSEPATH, 'z', owningPathSegList); } _createClass(_SVGPathSegClosePath, [{ key: "toString", value: function toString() { return '[object SVGPathSegClosePath]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter; } }, { key: "clone", value: function clone() { return new _SVGPathSegClosePath(undefined); } }]); return _SVGPathSegClosePath; }(_SVGPathSeg); var _SVGPathSegMovetoAbs = /*#__PURE__*/function (_SVGPathSeg3) { _inherits(_SVGPathSegMovetoAbs, _SVGPathSeg3); var _super2 = _createSuper(_SVGPathSegMovetoAbs); function _SVGPathSegMovetoAbs(owningPathSegList, x, y) { var _this; _classCallCheck(this, _SVGPathSegMovetoAbs); _this = _super2.call(this, _SVGPathSeg.PATHSEG_MOVETO_ABS, 'M', owningPathSegList); _this._x = x; _this._y = y; return _this; } _createClass(_SVGPathSegMovetoAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegMovetoAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegMovetoAbs(undefined, this._x, this._y); } }]); return _SVGPathSegMovetoAbs; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegMovetoAbs.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegMovetoRel = /*#__PURE__*/function (_SVGPathSeg4) { _inherits(_SVGPathSegMovetoRel, _SVGPathSeg4); var _super3 = _createSuper(_SVGPathSegMovetoRel); function _SVGPathSegMovetoRel(owningPathSegList, x, y) { var _this2; _classCallCheck(this, _SVGPathSegMovetoRel); _this2 = _super3.call(this, _SVGPathSeg.PATHSEG_MOVETO_REL, 'm', owningPathSegList); _this2._x = x; _this2._y = y; return _this2; } _createClass(_SVGPathSegMovetoRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegMovetoRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegMovetoRel(undefined, this._x, this._y); } }]); return _SVGPathSegMovetoRel; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegMovetoRel.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegLinetoAbs = /*#__PURE__*/function (_SVGPathSeg5) { _inherits(_SVGPathSegLinetoAbs, _SVGPathSeg5); var _super4 = _createSuper(_SVGPathSegLinetoAbs); function _SVGPathSegLinetoAbs(owningPathSegList, x, y) { var _this3; _classCallCheck(this, _SVGPathSegLinetoAbs); _this3 = _super4.call(this, _SVGPathSeg.PATHSEG_LINETO_ABS, 'L', owningPathSegList); _this3._x = x; _this3._y = y; return _this3; } _createClass(_SVGPathSegLinetoAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegLinetoAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegLinetoAbs(undefined, this._x, this._y); } }]); return _SVGPathSegLinetoAbs; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegLinetoAbs.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegLinetoRel = /*#__PURE__*/function (_SVGPathSeg6) { _inherits(_SVGPathSegLinetoRel, _SVGPathSeg6); var _super5 = _createSuper(_SVGPathSegLinetoRel); function _SVGPathSegLinetoRel(owningPathSegList, x, y) { var _this4; _classCallCheck(this, _SVGPathSegLinetoRel); _this4 = _super5.call(this, _SVGPathSeg.PATHSEG_LINETO_REL, 'l', owningPathSegList); _this4._x = x; _this4._y = y; return _this4; } _createClass(_SVGPathSegLinetoRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegLinetoRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegLinetoRel(undefined, this._x, this._y); } }]); return _SVGPathSegLinetoRel; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegLinetoRel.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegCurvetoCubicAbs = /*#__PURE__*/function (_SVGPathSeg7) { _inherits(_SVGPathSegCurvetoCubicAbs, _SVGPathSeg7); var _super6 = _createSuper(_SVGPathSegCurvetoCubicAbs); function _SVGPathSegCurvetoCubicAbs(owningPathSegList, x, y, x1, y1, x2, y2) { var _this5; _classCallCheck(this, _SVGPathSegCurvetoCubicAbs); _this5 = _super6.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, 'C', owningPathSegList); _this5._x = x; _this5._y = y; _this5._x1 = x1; _this5._y1 = y1; _this5._x2 = x2; _this5._y2 = y2; return _this5; } _createClass(_SVGPathSegCurvetoCubicAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoCubicAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); } }]); return _SVGPathSegCurvetoCubicAbs; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoCubicAbs.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, x1: { get: function get() { return this._x1; }, set: function set(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }, y1: { get: function get() { return this._y1; }, set: function set(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }, x2: { get: function get() { return this._x2; }, set: function set(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }, y2: { get: function get() { return this._y2; }, set: function set(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegCurvetoCubicRel = /*#__PURE__*/function (_SVGPathSeg8) { _inherits(_SVGPathSegCurvetoCubicRel, _SVGPathSeg8); var _super7 = _createSuper(_SVGPathSegCurvetoCubicRel); function _SVGPathSegCurvetoCubicRel(owningPathSegList, x, y, x1, y1, x2, y2) { var _this6; _classCallCheck(this, _SVGPathSegCurvetoCubicRel); _this6 = _super7.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, 'c', owningPathSegList); _this6._x = x; _this6._y = y; _this6._x1 = x1; _this6._y1 = y1; _this6._x2 = x2; _this6._y2 = y2; return _this6; } _createClass(_SVGPathSegCurvetoCubicRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoCubicRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); } }]); return _SVGPathSegCurvetoCubicRel; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoCubicRel.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, x1: { get: function get() { return this._x1; }, set: function set(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }, y1: { get: function get() { return this._y1; }, set: function set(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }, x2: { get: function get() { return this._x2; }, set: function set(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }, y2: { get: function get() { return this._y2; }, set: function set(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegCurvetoQuadraticAbs = /*#__PURE__*/function (_SVGPathSeg9) { _inherits(_SVGPathSegCurvetoQuadraticAbs, _SVGPathSeg9); var _super8 = _createSuper(_SVGPathSegCurvetoQuadraticAbs); function _SVGPathSegCurvetoQuadraticAbs(owningPathSegList, x, y, x1, y1) { var _this7; _classCallCheck(this, _SVGPathSegCurvetoQuadraticAbs); _this7 = _super8.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, 'Q', owningPathSegList); _this7._x = x; _this7._y = y; _this7._x1 = x1; _this7._y1 = y1; return _this7; } _createClass(_SVGPathSegCurvetoQuadraticAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoQuadraticAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1); } }]); return _SVGPathSegCurvetoQuadraticAbs; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoQuadraticAbs.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, x1: { get: function get() { return this._x1; }, set: function set(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }, y1: { get: function get() { return this._y1; }, set: function set(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegCurvetoQuadraticRel = /*#__PURE__*/function (_SVGPathSeg10) { _inherits(_SVGPathSegCurvetoQuadraticRel, _SVGPathSeg10); var _super9 = _createSuper(_SVGPathSegCurvetoQuadraticRel); function _SVGPathSegCurvetoQuadraticRel(owningPathSegList, x, y, x1, y1) { var _this8; _classCallCheck(this, _SVGPathSegCurvetoQuadraticRel); _this8 = _super9.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, 'q', owningPathSegList); _this8._x = x; _this8._y = y; _this8._x1 = x1; _this8._y1 = y1; return _this8; } _createClass(_SVGPathSegCurvetoQuadraticRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoQuadraticRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1); } }]); return _SVGPathSegCurvetoQuadraticRel; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoQuadraticRel.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, x1: { get: function get() { return this._x1; }, set: function set(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }, y1: { get: function get() { return this._y1; }, set: function set(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegArcAbs = /*#__PURE__*/function (_SVGPathSeg11) { _inherits(_SVGPathSegArcAbs, _SVGPathSeg11); var _super10 = _createSuper(_SVGPathSegArcAbs); function _SVGPathSegArcAbs(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { var _this9; _classCallCheck(this, _SVGPathSegArcAbs); _this9 = _super10.call(this, _SVGPathSeg.PATHSEG_ARC_ABS, 'A', owningPathSegList); _this9._x = x; _this9._y = y; _this9._r1 = r1; _this9._r2 = r2; _this9._angle = angle; _this9._largeArcFlag = largeArcFlag; _this9._sweepFlag = sweepFlag; return _this9; } _createClass(_SVGPathSegArcAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegArcAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); } }]); return _SVGPathSegArcAbs; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegArcAbs.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, r1: { get: function get() { return this._r1; }, set: function set(r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true }, r2: { get: function get() { return this._r2; }, set: function set(r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true }, angle: { get: function get() { return this._angle; }, set: function set(angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true }, largeArcFlag: { get: function get() { return this._largeArcFlag; }, set: function set(largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true }, sweepFlag: { get: function get() { return this._sweepFlag; }, set: function set(sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegArcRel = /*#__PURE__*/function (_SVGPathSeg12) { _inherits(_SVGPathSegArcRel, _SVGPathSeg12); var _super11 = _createSuper(_SVGPathSegArcRel); function _SVGPathSegArcRel(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { var _this10; _classCallCheck(this, _SVGPathSegArcRel); _this10 = _super11.call(this, _SVGPathSeg.PATHSEG_ARC_REL, 'a', owningPathSegList); _this10._x = x; _this10._y = y; _this10._r1 = r1; _this10._r2 = r2; _this10._angle = angle; _this10._largeArcFlag = largeArcFlag; _this10._sweepFlag = sweepFlag; return _this10; } _createClass(_SVGPathSegArcRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegArcRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); } }]); return _SVGPathSegArcRel; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegArcRel.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, r1: { get: function get() { return this._r1; }, set: function set(r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true }, r2: { get: function get() { return this._r2; }, set: function set(r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true }, angle: { get: function get() { return this._angle; }, set: function set(angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true }, largeArcFlag: { get: function get() { return this._largeArcFlag; }, set: function set(largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true }, sweepFlag: { get: function get() { return this._sweepFlag; }, set: function set(sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegLinetoHorizontalAbs = /*#__PURE__*/function (_SVGPathSeg13) { _inherits(_SVGPathSegLinetoHorizontalAbs, _SVGPathSeg13); var _super12 = _createSuper(_SVGPathSegLinetoHorizontalAbs); function _SVGPathSegLinetoHorizontalAbs(owningPathSegList, x) { var _this11; _classCallCheck(this, _SVGPathSegLinetoHorizontalAbs); _this11 = _super12.call(this, _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, 'H', owningPathSegList); _this11._x = x; return _this11; } _createClass(_SVGPathSegLinetoHorizontalAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegLinetoHorizontalAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x; } }, { key: "clone", value: function clone() { return new _SVGPathSegLinetoHorizontalAbs(undefined, this._x); } }]); return _SVGPathSegLinetoHorizontalAbs; }(_SVGPathSeg); Object.defineProperty(_SVGPathSegLinetoHorizontalAbs.prototype, 'x', { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); var _SVGPathSegLinetoHorizontalRel = /*#__PURE__*/function (_SVGPathSeg14) { _inherits(_SVGPathSegLinetoHorizontalRel, _SVGPathSeg14); var _super13 = _createSuper(_SVGPathSegLinetoHorizontalRel); function _SVGPathSegLinetoHorizontalRel(owningPathSegList, x) { var _this12; _classCallCheck(this, _SVGPathSegLinetoHorizontalRel); _this12 = _super13.call(this, _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, 'h', owningPathSegList); _this12._x = x; return _this12; } _createClass(_SVGPathSegLinetoHorizontalRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegLinetoHorizontalRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x; } }, { key: "clone", value: function clone() { return new _SVGPathSegLinetoHorizontalRel(undefined, this._x); } }]); return _SVGPathSegLinetoHorizontalRel; }(_SVGPathSeg); Object.defineProperty(_SVGPathSegLinetoHorizontalRel.prototype, 'x', { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); var _SVGPathSegLinetoVerticalAbs = /*#__PURE__*/function (_SVGPathSeg15) { _inherits(_SVGPathSegLinetoVerticalAbs, _SVGPathSeg15); var _super14 = _createSuper(_SVGPathSegLinetoVerticalAbs); function _SVGPathSegLinetoVerticalAbs(owningPathSegList, y) { var _this13; _classCallCheck(this, _SVGPathSegLinetoVerticalAbs); _this13 = _super14.call(this, _SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, 'V', owningPathSegList); _this13._y = y; return _this13; } _createClass(_SVGPathSegLinetoVerticalAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegLinetoVerticalAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegLinetoVerticalAbs(undefined, this._y); } }]); return _SVGPathSegLinetoVerticalAbs; }(_SVGPathSeg); Object.defineProperty(_SVGPathSegLinetoVerticalAbs.prototype, 'y', { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); var _SVGPathSegLinetoVerticalRel = /*#__PURE__*/function (_SVGPathSeg16) { _inherits(_SVGPathSegLinetoVerticalRel, _SVGPathSeg16); var _super15 = _createSuper(_SVGPathSegLinetoVerticalRel); function _SVGPathSegLinetoVerticalRel(owningPathSegList, y) { var _this14; _classCallCheck(this, _SVGPathSegLinetoVerticalRel); _this14 = _super15.call(this, _SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, 'v', owningPathSegList); _this14._y = y; return _this14; } _createClass(_SVGPathSegLinetoVerticalRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegLinetoVerticalRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegLinetoVerticalRel(undefined, this._y); } }]); return _SVGPathSegLinetoVerticalRel; }(_SVGPathSeg); Object.defineProperty(_SVGPathSegLinetoVerticalRel.prototype, 'y', { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); var _SVGPathSegCurvetoCubicSmoothAbs = /*#__PURE__*/function (_SVGPathSeg17) { _inherits(_SVGPathSegCurvetoCubicSmoothAbs, _SVGPathSeg17); var _super16 = _createSuper(_SVGPathSegCurvetoCubicSmoothAbs); function _SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, x, y, x2, y2) { var _this15; _classCallCheck(this, _SVGPathSegCurvetoCubicSmoothAbs); _this15 = _super16.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, 'S', owningPathSegList); _this15._x = x; _this15._y = y; _this15._x2 = x2; _this15._y2 = y2; return _this15; } _createClass(_SVGPathSegCurvetoCubicSmoothAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoCubicSmoothAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2); } }]); return _SVGPathSegCurvetoCubicSmoothAbs; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoCubicSmoothAbs.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, x2: { get: function get() { return this._x2; }, set: function set(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }, y2: { get: function get() { return this._y2; }, set: function set(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegCurvetoCubicSmoothRel = /*#__PURE__*/function (_SVGPathSeg18) { _inherits(_SVGPathSegCurvetoCubicSmoothRel, _SVGPathSeg18); var _super17 = _createSuper(_SVGPathSegCurvetoCubicSmoothRel); function _SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, x, y, x2, y2) { var _this16; _classCallCheck(this, _SVGPathSegCurvetoCubicSmoothRel); _this16 = _super17.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, 's', owningPathSegList); _this16._x = x; _this16._y = y; _this16._x2 = x2; _this16._y2 = y2; return _this16; } _createClass(_SVGPathSegCurvetoCubicSmoothRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoCubicSmoothRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2); } }]); return _SVGPathSegCurvetoCubicSmoothRel; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoCubicSmoothRel.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true }, x2: { get: function get() { return this._x2; }, set: function set(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }, y2: { get: function get() { return this._y2; }, set: function set(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegCurvetoQuadraticSmoothAbs = /*#__PURE__*/function (_SVGPathSeg19) { _inherits(_SVGPathSegCurvetoQuadraticSmoothAbs, _SVGPathSeg19); var _super18 = _createSuper(_SVGPathSegCurvetoQuadraticSmoothAbs); function _SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, x, y) { var _this17; _classCallCheck(this, _SVGPathSegCurvetoQuadraticSmoothAbs); _this17 = _super18.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, 'T', owningPathSegList); _this17._x = x; _this17._y = y; return _this17; } _createClass(_SVGPathSegCurvetoQuadraticSmoothAbs, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoQuadraticSmoothAbs]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y); } }]); return _SVGPathSegCurvetoQuadraticSmoothAbs; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoQuadraticSmoothAbs.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true } }); var _SVGPathSegCurvetoQuadraticSmoothRel = /*#__PURE__*/function (_SVGPathSeg20) { _inherits(_SVGPathSegCurvetoQuadraticSmoothRel, _SVGPathSeg20); var _super19 = _createSuper(_SVGPathSegCurvetoQuadraticSmoothRel); function _SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, x, y) { var _this18; _classCallCheck(this, _SVGPathSegCurvetoQuadraticSmoothRel); _this18 = _super19.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, 't', owningPathSegList); _this18._x = x; _this18._y = y; return _this18; } _createClass(_SVGPathSegCurvetoQuadraticSmoothRel, [{ key: "toString", value: function toString() { return '[object SVGPathSegCurvetoQuadraticSmoothRel]'; } }, { key: "_asPathString", value: function _asPathString() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; } }, { key: "clone", value: function clone() { return new _SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y); } }]); return _SVGPathSegCurvetoQuadraticSmoothRel; }(_SVGPathSeg); Object.defineProperties(_SVGPathSegCurvetoQuadraticSmoothRel.prototype, { x: { get: function get() { return this._x; }, set: function set(x) { this._x = x; this._segmentChanged(); }, enumerable: true }, y: { get: function get() { return this._y; }, set: function set(y) { this._y = y; this._segmentChanged(); }, enumerable: true } }); // Add createSVGPathSeg* functions to SVGPathElement. // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathElement. SVGPathElement.prototype.createSVGPathSegClosePath = function () { return new _SVGPathSegClosePath(undefined); }; SVGPathElement.prototype.createSVGPathSegMovetoAbs = function (x, y) { return new _SVGPathSegMovetoAbs(undefined, x, y); }; SVGPathElement.prototype.createSVGPathSegMovetoRel = function (x, y) { return new _SVGPathSegMovetoRel(undefined, x, y); }; SVGPathElement.prototype.createSVGPathSegLinetoAbs = function (x, y) { return new _SVGPathSegLinetoAbs(undefined, x, y); }; SVGPathElement.prototype.createSVGPathSegLinetoRel = function (x, y) { return new _SVGPathSegLinetoRel(undefined, x, y); }; SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function (x, y, x1, y1, x2, y2) { return new _SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2); }; SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function (x, y, x1, y1, x2, y2) { return new _SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2); }; SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function (x, y, x1, y1) { return new _SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1); }; SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function (x, y, x1, y1) { return new _SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1); }; SVGPathElement.prototype.createSVGPathSegArcAbs = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new _SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); }; SVGPathElement.prototype.createSVGPathSegArcRel = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new _SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); }; SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function (x) { return new _SVGPathSegLinetoHorizontalAbs(undefined, x); }; SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function (x) { return new _SVGPathSegLinetoHorizontalRel(undefined, x); }; SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function (y) { return new _SVGPathSegLinetoVerticalAbs(undefined, y); }; SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function (y) { return new _SVGPathSegLinetoVerticalRel(undefined, y); }; SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function (x, y, x2, y2) { return new _SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2); }; SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function (x, y, x2, y2) { return new _SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2); }; SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function (x, y) { return new _SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y); }; SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function (x, y) { return new _SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y); }; if (!('getPathSegAtLength' in SVGPathElement.prototype)) { // Add getPathSegAtLength to SVGPathElement. // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-__svg__SVGPathElement__getPathSegAtLength // This polyfill requires SVGPathElement.getTotalLength to implement the distance-along-a-path algorithm. SVGPathElement.prototype.getPathSegAtLength = function (distance) { if (distance === undefined || !isFinite(distance)) { throw new Error('Invalid arguments.'); } var measurementElement = document.createElementNS('http://www.w3.org/2000/svg', 'path'); measurementElement.setAttribute('d', this.getAttribute('d')); var lastPathSegment = measurementElement.pathSegList.numberOfItems - 1; // If the path is empty, return 0. if (lastPathSegment <= 0) { return 0; } do { measurementElement.pathSegList.removeItem(lastPathSegment); if (distance > measurementElement.getTotalLength()) { break; } lastPathSegment--; } while (lastPathSegment > 0); return lastPathSegment; }; } window.SVGPathSeg = _SVGPathSeg; window.SVGPathSegClosePath = _SVGPathSegClosePath; window.SVGPathSegMovetoAbs = _SVGPathSegMovetoAbs; window.SVGPathSegMovetoRel = _SVGPathSegMovetoRel; window.SVGPathSegLinetoAbs = _SVGPathSegLinetoAbs; window.SVGPathSegLinetoRel = _SVGPathSegLinetoRel; window.SVGPathSegCurvetoCubicAbs = _SVGPathSegCurvetoCubicAbs; window.SVGPathSegCurvetoCubicRel = _SVGPathSegCurvetoCubicRel; window.SVGPathSegCurvetoQuadraticAbs = _SVGPathSegCurvetoQuadraticAbs; window.SVGPathSegCurvetoQuadraticRel = _SVGPathSegCurvetoQuadraticRel; window.SVGPathSegArcAbs = _SVGPathSegArcAbs; window.SVGPathSegArcRel = _SVGPathSegArcRel; window.SVGPathSegLinetoHorizontalAbs = _SVGPathSegLinetoHorizontalAbs; window.SVGPathSegLinetoHorizontalRel = _SVGPathSegLinetoHorizontalRel; window.SVGPathSegLinetoVerticalAbs = _SVGPathSegLinetoVerticalAbs; window.SVGPathSegLinetoVerticalRel = _SVGPathSegLinetoVerticalRel; window.SVGPathSegCurvetoCubicSmoothAbs = _SVGPathSegCurvetoCubicSmoothAbs; window.SVGPathSegCurvetoCubicSmoothRel = _SVGPathSegCurvetoCubicSmoothRel; window.SVGPathSegCurvetoQuadraticSmoothAbs = _SVGPathSegCurvetoQuadraticSmoothAbs; window.SVGPathSegCurvetoQuadraticSmoothRel = _SVGPathSegCurvetoQuadraticSmoothRel; } // Checking for SVGPathSegList in window checks for the case of an implementation without the // SVGPathSegList API. // The second check for appendItem is specific to Firefox 59+ which removed only parts of the // SVGPathSegList API (e.g., appendItem). In this case we need to re-implement the entire API // so the polyfill data (i.e., _list) is used throughout. if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.prototype)) { // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList var SVGPathSegList = /*#__PURE__*/function () { function SVGPathSegList(pathElement) { _classCallCheck(this, SVGPathSegList); this._pathElement = pathElement; this._list = this._parsePath(this._pathElement.getAttribute('d')); // Use a MutationObserver to catch changes to the path's "d" attribute. this._mutationObserverConfig = { attributes: true, attributeFilter: ['d'] }; this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this)); this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig); } // Process any pending mutations to the path element and update the list as needed. // This should be the first call of all public functions and is needed because // MutationObservers are not synchronous so we can have pending asynchronous mutations. _createClass(SVGPathSegList, [{ key: "_checkPathSynchronizedToList", value: function _checkPathSynchronizedToList() { this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords()); } }, { key: "_updateListFromPathMutations", value: function _updateListFromPathMutations(mutationRecords) { if (!this._pathElement) { return; } var hasPathMutations = false; mutationRecords.forEach(function (record) { if (record.attributeName === 'd') { hasPathMutations = true; } }); if (hasPathMutations) { this._list = this._parsePath(this._pathElement.getAttribute('d')); } } // Serialize the list and update the path's 'd' attribute. }, { key: "_writeListToPath", value: function _writeListToPath() { this._pathElementMutationObserver.disconnect(); this._pathElement.setAttribute('d', SVGPathSegList._pathSegArrayAsString(this._list)); this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig); } // When a path segment changes the list needs to be synchronized back to the path element. }, { key: "segmentChanged", value: function segmentChanged(pathSeg) { this._writeListToPath(); } }, { key: "clear", value: function clear() { this._checkPathSynchronizedToList(); this._list.forEach(function (pathSeg) { pathSeg._owningPathSegList = null; }); this._list = []; this._writeListToPath(); } }, { key: "initialize", value: function initialize(newItem) { this._checkPathSynchronizedToList(); this._list = [newItem]; newItem._owningPathSegList = this; this._writeListToPath(); return newItem; } }, { key: "_checkValidIndex", value: function _checkValidIndex(index) { if (isNaN(index) || index < 0 || index >= this.numberOfItems) { throw new Error('INDEX_SIZE_ERR'); } } }, { key: "getItem", value: function getItem(index) { this._checkPathSynchronizedToList(); this._checkValidIndex(index); return this._list[index]; } }, { key: "insertItemBefore", value: function insertItemBefore(newItem, index) { this._checkPathSynchronizedToList(); // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list. if (index > this.numberOfItems) { index = this.numberOfItems; } if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone(); } this._list.splice(index, 0, newItem); newItem._owningPathSegList = this; this._writeListToPath(); return newItem; } }, { key: "replaceItem", value: function replaceItem(newItem, index) { this._checkPathSynchronizedToList(); if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone(); } this._checkValidIndex(index); this._list[index] = newItem; newItem._owningPathSegList = this; this._writeListToPath(); return newItem; } }, { key: "removeItem", value: function removeItem(index) { this._checkPathSynchronizedToList(); this._checkValidIndex(index); var item = this._list[index]; this._list.splice(index, 1); this._writeListToPath(); return item; } }, { key: "appendItem", value: function appendItem(newItem) { this._checkPathSynchronizedToList(); if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone(); } this._list.push(newItem); newItem._owningPathSegList = this; // TODO: Optimize this to just append to the existing attribute. this._writeListToPath(); return newItem; } // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp. }, { key: "_parsePath", value: function _parsePath(string) { if (!string || !string.length) { return []; } var owningPathSegList = this; var Builder = /*#__PURE__*/function () { function Builder() { _classCallCheck(this, Builder); this.pathSegList = []; } _createClass(Builder, [{ key: "appendSegment", value: function appendSegment(pathSeg) { this.pathSegList.push(pathSeg); } }]); return Builder; }(); var Source = /*#__PURE__*/function () { function Source(string) { _classCallCheck(this, Source); this._string = string; this._currentIndex = 0; this._endIndex = this._string.length; this._previousCommand = SVGPathSeg.PATHSEG_UNKNOWN; this._skipOptionalSpaces(); } _createClass(Source, [{ key: "_isCurrentSpace", value: function _isCurrentSpace() { var character = this._string[this._currentIndex]; return character <= ' ' && (character === ' ' || character === '\n' || character === '\t' || character === '\r' || character === '\f'); } }, { key: "_skipOptionalSpaces", value: function _skipOptionalSpaces() { while (this._currentIndex < this._endIndex && this._isCurrentSpace()) { this._currentIndex++; } return this._currentIndex < this._endIndex; } }, { key: "_skipOptionalSpacesOrDelimiter", value: function _skipOptionalSpacesOrDelimiter() { if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) !== ',') { return false; } if (this._skipOptionalSpaces()) { if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === ',') { this._currentIndex++; this._skipOptionalSpaces(); } } return this._currentIndex < this._endIndex; } }, { key: "hasMoreData", value: function hasMoreData() { return this._currentIndex < this._endIndex; } }, { key: "peekSegmentType", value: function peekSegmentType() { var lookahead = this._string[this._currentIndex]; return this._pathSegTypeFromChar(lookahead); } }, { key: "_pathSegTypeFromChar", value: function _pathSegTypeFromChar(lookahead) { switch (lookahead) { case 'Z': case 'z': return SVGPathSeg.PATHSEG_CLOSEPATH; case 'M': return SVGPathSeg.PATHSEG_MOVETO_ABS; case 'm': return SVGPathSeg.PATHSEG_MOVETO_REL; case 'L': return SVGPathSeg.PATHSEG_LINETO_ABS; case 'l': return SVGPathSeg.PATHSEG_LINETO_REL; case 'C': return SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS; case 'c': return SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL; case 'Q': return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS; case 'q': return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL; case 'A': return SVGPathSeg.PATHSEG_ARC_ABS; case 'a': return SVGPathSeg.PATHSEG_ARC_REL; case 'H': return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS; case 'h': return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL; case 'V': return SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS; case 'v': return SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL; case 'S': return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS; case 's': return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL; case 'T': return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS; case 't': return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL; default: return SVGPathSeg.PATHSEG_UNKNOWN; } } }, { key: "_nextCommandHelper", value: function _nextCommandHelper(lookahead, previousCommand) { // Check for remaining coordinates in the current command. if ((lookahead === '+' || lookahead === '-' || lookahead === '.' || lookahead >= '0' && lookahead <= '9') && previousCommand !== SVGPathSeg.PATHSEG_CLOSEPATH) { if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_ABS) { return SVGPathSeg.PATHSEG_LINETO_ABS; } if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_REL) { return SVGPathSeg.PATHSEG_LINETO_REL; } return previousCommand; } return SVGPathSeg.PATHSEG_UNKNOWN; } }, { key: "initialCommandIsMoveTo", value: function initialCommandIsMoveTo() { // If the path is empty it is still valid, so return true. if (!this.hasMoreData()) { return true; } var command = this.peekSegmentType(); // Path must start with moveTo. return command === SVGPathSeg.PATHSEG_MOVETO_ABS || command === SVGPathSeg.PATHSEG_MOVETO_REL; } // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp. // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF }, { key: "_parseNumber", value: function _parseNumber() { var exponent = 0; var integer = 0; var frac = 1; var decimal = 0; var sign = 1; var expsign = 1; var startIndex = this._currentIndex; this._skipOptionalSpaces(); // Read the sign. if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '+') { this._currentIndex++; } else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '-') { this._currentIndex++; sign = -1; } if (this._currentIndex === this._endIndex || (this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') && this._string.charAt(this._currentIndex) !== '.') { // The first character of a number must be one of [0-9+-.]. return undefined; } // Read the integer part, build right-to-left. var startIntPartIndex = this._currentIndex; while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') { this._currentIndex++; // Advance to first non-digit. } if (this._currentIndex !== startIntPartIndex) { var scanIntPartIndex = this._currentIndex - 1; var multiplier = 1; while (scanIntPartIndex >= startIntPartIndex) { integer += multiplier * (this._string.charAt(scanIntPartIndex--) - '0'); multiplier *= 10; } } // Read the decimals. if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '.') { this._currentIndex++; // There must be a least one digit following the . if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') { return undefined; } while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') { frac *= 10; decimal += (this._string.charAt(this._currentIndex) - '0') / frac; this._currentIndex += 1; } } // Read the exponent part. if (this._currentIndex !== startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) === 'e' || this._string.charAt(this._currentIndex) === 'E') && this._string.charAt(this._currentIndex + 1) !== 'x' && this._string.charAt(this._currentIndex + 1) !== 'm') { this._currentIndex++; // Read the sign of the exponent. if (this._string.charAt(this._currentIndex) === '+') { this._currentIndex++; } else if (this._string.charAt(this._currentIndex) === '-') { this._currentIndex++; expsign = -1; } // There must be an exponent. if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') { return undefined; } while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') { exponent *= 10; exponent += this._string.charAt(this._currentIndex) - '0'; this._currentIndex++; } } var number = integer + decimal; number *= sign; if (exponent) { number *= Math.pow(10, expsign * exponent); } if (startIndex === this._currentIndex) { return undefined; } this._skipOptionalSpacesOrDelimiter(); return number; } }, { key: "_parseArcFlag", value: function _parseArcFlag() { if (this._currentIndex >= this._endIndex) { return undefined; } var flag = false; var flagChar = this._string.charAt(this._currentIndex++); if (flagChar === '0') { flag = false; } else if (flagChar === '1') { flag = true; } else { return undefined; } this._skipOptionalSpacesOrDelimiter(); return flag; } }, { key: "parseSegment", value: function parseSegment() { var lookahead = this._string[this._currentIndex]; var command = this._pathSegTypeFromChar(lookahead); if (command === SVGPathSeg.PATHSEG_UNKNOWN) { // Possibly an implicit command. Not allowed if this is the first command. if (this._previousCommand === SVGPathSeg.PATHSEG_UNKNOWN) { return null; } command = this._nextCommandHelper(lookahead, this._previousCommand); if (command === SVGPathSeg.PATHSEG_UNKNOWN) { return null; } } else { this._currentIndex++; } this._previousCommand = command; switch (command) { case SVGPathSeg.PATHSEG_MOVETO_REL: return new SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_MOVETO_ABS: return new SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_REL: return new SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_ABS: return new SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL: return new SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS: return new SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL: return new SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS: return new SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_CLOSEPATH: this._skipOptionalSpaces(); return new SVGPathSegClosePath(owningPathSegList); case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: { var points = { x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2); } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: { var _points = { x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegCurvetoCubicAbs(owningPathSegList, _points.x, _points.y, _points.x1, _points.y1, _points.x2, _points.y2); } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: { var _points2 = { x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, _points2.x, _points2.y, _points2.x2, _points2.y2); } case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: { var _points3 = { x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, _points3.x, _points3.y, _points3.x2, _points3.y2); } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: { var _points4 = { x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegCurvetoQuadraticRel(owningPathSegList, _points4.x, _points4.y, _points4.x1, _points4.y1); } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: { var _points5 = { x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegCurvetoQuadraticAbs(owningPathSegList, _points5.x, _points5.y, _points5.x1, _points5.y1); } case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: return new SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: return new SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_ARC_REL: { var _points6 = { x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegArcRel(owningPathSegList, _points6.x, _points6.y, _points6.x1, _points6.y1, _points6.arcAngle, _points6.arcLarge, _points6.arcSweep); } case SVGPathSeg.PATHSEG_ARC_ABS: { var _points7 = { x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber() }; return new SVGPathSegArcAbs(owningPathSegList, _points7.x, _points7.y, _points7.x1, _points7.y1, _points7.arcAngle, _points7.arcLarge, _points7.arcSweep); } default: throw new Error('Unknown path seg type.'); } } }]); return Source; }(); var builder = new Builder(); var source = new Source(string); if (!source.initialCommandIsMoveTo()) { return []; } while (source.hasMoreData()) { var pathSeg = source.parseSegment(); if (!pathSeg) { return []; } builder.appendSegment(pathSeg); } return builder.pathSegList; } // STATIC }], [{ key: "_pathSegArrayAsString", value: function _pathSegArrayAsString(pathSegArray) { var string = ''; var first = true; pathSegArray.forEach(function (pathSeg) { if (first) { first = false; string += pathSeg._asPathString(); } else { string += ' ' + pathSeg._asPathString(); } }); return string; } }]); return SVGPathSegList; }(); SVGPathSegList.prototype.classname = 'SVGPathSegList'; Object.defineProperty(SVGPathSegList.prototype, 'numberOfItems', { get: function get() { this._checkPathSynchronizedToList(); return this._list.length; }, enumerable: true }); // Add the pathSegList accessors to SVGPathElement. // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData Object.defineProperties(SVGPathElement.prototype, { pathSegList: { get: function get() { if (!this._pathSegList) { this._pathSegList = new SVGPathSegList(this); } return this._pathSegList; }, enumerable: true }, // TODO: The following are not implemented and simply return SVGPathElement.pathSegList. normalizedPathSegList: { get: function get() { return this.pathSegList; }, enumerable: true }, animatedPathSegList: { get: function get() { return this.pathSegList; }, enumerable: true }, animatedNormalizedPathSegList: { get: function get() { return this.pathSegList; }, enumerable: true } }); window.SVGPathSegList = SVGPathSegList; } })(); var $ = jQuery; var supportsSVG_ = function () { return Boolean(document.createElementNS && document.createElementNS(NS.SVG, 'svg').createSVGRect); }(); var _navigator = navigator, userAgent = _navigator.userAgent; var svg = document.createElementNS(NS.SVG, 'svg'); // Note: Browser sniffing should only be used if no other detection method is possible var isOpera_ = Boolean(window.opera); var isWebkit_ = userAgent.includes('AppleWebKit'); var isGecko_ = userAgent.includes('Gecko/'); var isIE_ = userAgent.includes('MSIE'); var isChrome_ = userAgent.includes('Chrome/'); var isWindows_ = userAgent.includes('Windows'); var isMac_ = userAgent.includes('Macintosh'); var isTouch_ = ('ontouchstart' in window); var supportsSelectors_ = function () { return Boolean(svg.querySelector); }(); var supportsXpath_ = function () { return Boolean(document.evaluate); }(); // segList functions (for FF1.5 and 2.0) var supportsPathReplaceItem_ = function () { var path = document.createElementNS(NS.SVG, 'path'); path.setAttribute('d', 'M0,0 10,10'); var seglist = path.pathSegList; var seg = path.createSVGPathSegLinetoAbs(5, 5); try { seglist.replaceItem(seg, 1); return true; } catch (err) {} return false; }(); var supportsPathInsertItemBefore_ = function () { var path = document.createElementNS(NS.SVG, 'path'); path.setAttribute('d', 'M0,0 10,10'); var seglist = path.pathSegList; var seg = path.createSVGPathSegLinetoAbs(5, 5); try { seglist.insertItemBefore(seg, 1); return true; } catch (err) {} return false; }(); // text character positioning (for IE9 and now Chrome) var supportsGoodTextCharPos_ = function () { var svgroot = document.createElementNS(NS.SVG, 'svg'); var svgcontent = document.createElementNS(NS.SVG, 'svg'); document.documentElement.append(svgroot); svgcontent.setAttribute('x', 5); svgroot.append(svgcontent); var text = document.createElementNS(NS.SVG, 'text'); text.textContent = 'a'; svgcontent.append(text); try { // Chrome now fails here var pos = text.getStartPositionOfChar(0).x; return pos === 0; } catch (err) { return false; } finally { svgroot.remove(); } }(); var supportsPathBBox_ = function () { var svgcontent = document.createElementNS(NS.SVG, 'svg'); document.documentElement.append(svgcontent); var path = document.createElementNS(NS.SVG, 'path'); path.setAttribute('d', 'M0,0 C0,0 10,10 10,0'); svgcontent.append(path); var bbox = path.getBBox(); svgcontent.remove(); return bbox.height > 4 && bbox.height < 5; }(); // Support for correct bbox sizing on groups with horizontal/vertical lines var supportsHVLineContainerBBox_ = function () { var svgcontent = document.createElementNS(NS.SVG, 'svg'); document.documentElement.append(svgcontent); var path = document.createElementNS(NS.SVG, 'path'); path.setAttribute('d', 'M0,0 10,0'); var path2 = document.createElementNS(NS.SVG, 'path'); path2.setAttribute('d', 'M5,0 15,0'); var g = document.createElementNS(NS.SVG, 'g'); g.append(path, path2); svgcontent.append(g); var bbox = g.getBBox(); svgcontent.remove(); // Webkit gives 0, FF gives 10, Opera (correctly) gives 15 return bbox.width === 15; }(); var supportsGoodDecimals_ = function () { // Correct decimals on clone attributes (Opera < 10.5/win/non-en) var rect = document.createElementNS(NS.SVG, 'rect'); rect.setAttribute('x', 0.1); var crect = rect.cloneNode(false); var retValue = !crect.getAttribute('x').includes(','); if (!retValue) { // Todo: i18nize or remove $.alert('NOTE: This version of Opera is known to contain bugs in SVG-edit.\n' + 'Please upgrade to the latest version in which the problems have been fixed.'); } return retValue; }(); var supportsNonScalingStroke_ = function () { var rect = document.createElementNS(NS.SVG, 'rect'); rect.setAttribute('style', 'vector-effect:non-scaling-stroke'); return rect.style.vectorEffect === 'non-scaling-stroke'; }(); var supportsNativeSVGTransformLists_ = function () { var rect = document.createElementNS(NS.SVG, 'rect'); var rxform = rect.transform.baseVal; var t1 = svg.createSVGTransform(); rxform.appendItem(t1); var r1 = rxform.getItem(0); var isSVGTransform = function isSVGTransform(o) { // https://developer.mozilla.org/en-US/docs/Web/API/SVGTransform return o && _typeof(o) === 'object' && typeof o.setMatrix === 'function' && 'angle' in o; }; return isSVGTransform(r1) && isSVGTransform(t1) && r1.type === t1.type && r1.angle === t1.angle && r1.matrix.a === t1.matrix.a && r1.matrix.b === t1.matrix.b && r1.matrix.c === t1.matrix.c && r1.matrix.d === t1.matrix.d && r1.matrix.e === t1.matrix.e && r1.matrix.f === t1.matrix.f; }(); // Public API /** * @function module:browser.isOpera * @returns {boolean} */ var isOpera = function isOpera() { return isOpera_; }; /** * @function module:browser.isWebkit * @returns {boolean} */ var isWebkit = function isWebkit() { return isWebkit_; }; /** * @function module:browser.isGecko * @returns {boolean} */ var isGecko = function isGecko() { return isGecko_; }; /** * @function module:browser.isIE * @returns {boolean} */ var isIE = function isIE() { return isIE_; }; /** * @function module:browser.isChrome * @returns {boolean} */ var isChrome = function isChrome() { return isChrome_; }; /** * @function module:browser.isMac * @returns {boolean} */ var isMac = function isMac() { return isMac_; }; /** * @function module:browser.isTouch * @returns {boolean} */ var isTouch = function isTouch() { return isTouch_; }; /** * @function module:browser.supportsSelectors * @returns {boolean} */ var supportsSelectors = function supportsSelectors() { return supportsSelectors_; }; /** * @function module:browser.supportsXpath * @returns {boolean} */ var supportsXpath = function supportsXpath() { return supportsXpath_; }; /** * @function module:browser.supportsPathReplaceItem * @returns {boolean} */ var supportsPathReplaceItem = function supportsPathReplaceItem() { return supportsPathReplaceItem_; }; /** * @function module:browser.supportsPathInsertItemBefore * @returns {boolean} */ var supportsPathInsertItemBefore = function supportsPathInsertItemBefore() { return supportsPathInsertItemBefore_; }; /** * @function module:browser.supportsPathBBox * @returns {boolean} */ var supportsPathBBox = function supportsPathBBox() { return supportsPathBBox_; }; /** * @function module:browser.supportsHVLineContainerBBox * @returns {boolean} */ var supportsHVLineContainerBBox = function supportsHVLineContainerBBox() { return supportsHVLineContainerBBox_; }; /** * @function module:browser.supportsGoodTextCharPos * @returns {boolean} */ var supportsGoodTextCharPos = function supportsGoodTextCharPos() { return supportsGoodTextCharPos_; }; /** * @function module:browser.supportsNonScalingStroke * @returns {boolean} */ var supportsNonScalingStroke = function supportsNonScalingStroke() { return supportsNonScalingStroke_; }; /** * @function module:browser.supportsNativeTransformLists * @returns {boolean} */ var supportsNativeTransformLists = function supportsNativeTransformLists() { return supportsNativeSVGTransformLists_; }; /** * A jQuery module to work with SVG attributes. * @module jQueryAttr * @license MIT */ /** * This fixes `$(...).attr()` to work as expected with SVG elements. * Does not currently use `*AttributeNS()` since we rarely need that. * Adds {@link external:jQuery.fn.attr}. * See {@link https://api.jquery.com/attr/} for basic documentation of `.attr()`. * * Additional functionality: * - When getting attributes, a string that's a number is returned as type number. * - If an array is supplied as the first parameter, multiple values are returned * as an object with values for each given attribute. * @function module:jQueryAttr.jQueryAttr * @param {external:jQuery} $ The jQuery object to which to add the plug-in * @returns {external:jQuery} */ function jQueryPluginSVG($) { var proxied = $.fn.attr, svgns = 'http://www.w3.org/2000/svg'; /** * @typedef {PlainObject} module:jQueryAttr.Attributes */ /** * @function external:jQuery.fn.attr * @param {string|string[]|PlainObject} key * @param {string} value * @returns {external:jQuery|module:jQueryAttr.Attributes} */ $.fn.attr = function (key, value) { var len = this.length; if (!len) { return proxied.call(this, key, value); } for (var i = 0; i < len; ++i) { var elem = this[i]; // set/get SVG attribute if (elem.namespaceURI === svgns) { // Setting attribute if (value !== undefined) { elem.setAttribute(key, value); } else if (Array.isArray(key)) { // Getting attributes from array var obj = {}; var j = key.length; while (j--) { var aname = key[j]; var attr = elem.getAttribute(aname); // This returns a number when appropriate if (attr || attr === '0') { attr = isNaN(attr) ? attr : attr - 0; } obj[aname] = attr; } return obj; } if (_typeof(key) === 'object') { // Setting attributes from object for (var _i = 0, _Object$entries = Object.entries(key); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), name = _Object$entries$_i[0], val = _Object$entries$_i[1]; elem.setAttribute(name, val); } // Getting attribute } else { var _attr = elem.getAttribute(key); if (_attr || _attr === '0') { _attr = isNaN(_attr) ? _attr : _attr - 0; } return _attr; } } else { return proxied.call(this, key, value); } } return this; }; return $; } var svgroot = document.createElementNS(NS.SVG, 'svg'); /** * Helper function to convert `SVGTransform` to a string. * @param {SVGTransform} xform * @returns {string} */ function transformToString(xform) { var m = xform.matrix; var text = ''; switch (xform.type) { case 1: // MATRIX text = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')'; break; case 2: // TRANSLATE text = 'translate(' + m.e + ',' + m.f + ')'; break; case 3: // SCALE if (m.a === m.d) { text = 'scale(' + m.a + ')'; } else { text = 'scale(' + m.a + ',' + m.d + ')'; } break; case 4: { // ROTATE var cx = 0; var cy = 0; // this prevents divide by zero if (xform.angle !== 0) { var K = 1 - m.a; cy = (K * m.f + m.b * m.e) / (K * K + m.b * m.b); cx = (m.e - m.b * cy) / K; } text = 'rotate(' + xform.angle + ' ' + cx + ',' + cy + ')'; break; } } return text; } /** * Map of SVGTransformList objects. */ var listMap_ = {}; /** * @interface module:SVGTransformList.SVGEditTransformList * @property {Integer} numberOfItems unsigned long */ /** * @function module:SVGTransformList.SVGEditTransformList#clear * @returns {void} */ /** * @function module:SVGTransformList.SVGEditTransformList#initialize * @param {SVGTransform} newItem * @returns {SVGTransform} */ /** * DOES NOT THROW DOMException, INDEX_SIZE_ERR. * @function module:SVGTransformList.SVGEditTransformList#getItem * @param {Integer} index unsigned long * @returns {SVGTransform} */ /** * DOES NOT THROW DOMException, INDEX_SIZE_ERR. * @function module:SVGTransformList.SVGEditTransformList#insertItemBefore * @param {SVGTransform} newItem * @param {Integer} index unsigned long * @returns {SVGTransform} */ /** * DOES NOT THROW DOMException, INDEX_SIZE_ERR. * @function module:SVGTransformList.SVGEditTransformList#replaceItem * @param {SVGTransform} newItem * @param {Integer} index unsigned long * @returns {SVGTransform} */ /** * DOES NOT THROW DOMException, INDEX_SIZE_ERR. * @function module:SVGTransformList.SVGEditTransformList#removeItem * @param {Integer} index unsigned long * @returns {SVGTransform} */ /** * @function module:SVGTransformList.SVGEditTransformList#appendItem * @param {SVGTransform} newItem * @returns {SVGTransform} */ /** * NOT IMPLEMENTED. * @ignore * @function module:SVGTransformList.SVGEditTransformList#createSVGTransformFromMatrix * @param {SVGMatrix} matrix * @returns {SVGTransform} */ /** * NOT IMPLEMENTED. * @ignore * @function module:SVGTransformList.SVGEditTransformList#consolidate * @returns {SVGTransform} */ /** * SVGTransformList implementation for Webkit. * These methods do not currently raise any exceptions. * These methods also do not check that transforms are being inserted. This is basically * implementing as much of SVGTransformList that we need to get the job done. * @implements {module:SVGTransformList.SVGEditTransformList} */ var SVGTransformList = /*#__PURE__*/function () { // eslint-disable-line no-shadow /** * @param {Element} elem * @returns {SVGTransformList} */ function SVGTransformList(elem) { _classCallCheck(this, SVGTransformList); this._elem = elem || null; this._xforms = []; // TODO: how do we capture the undo-ability in the changed transform list? this._update = function () { var tstr = ''; // /* const concatMatrix = */ svgroot.createSVGMatrix(); for (var i = 0; i < this.numberOfItems; ++i) { var xform = this._list.getItem(i); tstr += transformToString(xform) + ' '; } this._elem.setAttribute('transform', tstr); }; this._list = this; this._init = function () { var _this = this; // Transform attribute parser var str = this._elem.getAttribute('transform'); if (!str) { return; } // TODO: Add skew support in future var re = /\s*((scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/; // const re = /\s*(?(?:scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/; var m = true; while (m) { m = str.match(re); str = str.replace(re, ''); if (m && m[1]) { (function () { var x = m[1]; var bits = x.split(/\s*\(/); var name = bits[0]; var valBits = bits[1].match(/\s*(.*?)\s*\)/); valBits[1] = valBits[1].replace(/(\d)-/g, '$1 -'); var valArr = valBits[1].split(/[, ]+/); var letters = 'abcdef'.split(''); /* if (m && m.groups.xform) { const x = m.groups.xform; const [name, bits] = x.split(/\s*\(/); const valBits = bits.match(/\s*(?.*?)\s*\)/); valBits.groups.nonWhitespace = valBits.groups.nonWhitespace.replace( /(?\d)-/g, '$ -' ); const valArr = valBits.groups.nonWhitespace.split(/[, ]+/); const letters = [...'abcdef']; */ var mtx = svgroot.createSVGMatrix(); Object.values(valArr).forEach(function (item, i) { valArr[i] = Number.parseFloat(item); if (name === 'matrix') { mtx[letters[i]] = valArr[i]; } }); var xform = svgroot.createSVGTransform(); var fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1); var values = name === 'matrix' ? [mtx] : valArr; if (name === 'scale' && values.length === 1) { values.push(values[0]); } else if (name === 'translate' && values.length === 1) { values.push(0); } else if (name === 'rotate' && values.length === 1) { values.push(0, 0); } xform[fname].apply(xform, _toConsumableArray(values)); _this._list.appendItem(xform); })(); } } }; this._removeFromOtherLists = function (item) { if (item) { // Check if this transform is already in a transformlist, and // remove it if so. Object.values(listMap_).some(function (tl) { for (var i = 0, len = tl._xforms.length; i < len; ++i) { if (tl._xforms[i] === item) { tl.removeItem(i); return true; } } return false; }); } }; this.numberOfItems = 0; } /** * @returns {void} */ _createClass(SVGTransformList, [{ key: "clear", value: function clear() { this.numberOfItems = 0; this._xforms = []; } /** * @param {SVGTransform} newItem * @returns {void} */ }, { key: "initialize", value: function initialize(newItem) { this.numberOfItems = 1; this._removeFromOtherLists(newItem); this._xforms = [newItem]; } /** * @param {Integer} index unsigned long * @throws {Error} * @returns {SVGTransform} */ }, { key: "getItem", value: function getItem(index) { if (index < this.numberOfItems && index >= 0) { return this._xforms[index]; } var err = new Error('DOMException with code=INDEX_SIZE_ERR'); err.code = 1; throw err; } /** * @param {SVGTransform} newItem * @param {Integer} index unsigned long * @returns {SVGTransform} */ }, { key: "insertItemBefore", value: function insertItemBefore(newItem, index) { var retValue = null; if (index >= 0) { if (index < this.numberOfItems) { this._removeFromOtherLists(newItem); var newxforms = new Array(this.numberOfItems + 1); // TODO: use array copying and slicing var i; for (i = 0; i < index; ++i) { newxforms[i] = this._xforms[i]; } newxforms[i] = newItem; for (var j = i + 1; i < this.numberOfItems; ++j, ++i) { newxforms[j] = this._xforms[i]; } this.numberOfItems++; this._xforms = newxforms; retValue = newItem; this._list._update(); } else { retValue = this._list.appendItem(newItem); } } return retValue; } /** * @param {SVGTransform} newItem * @param {Integer} index unsigned long * @returns {SVGTransform} */ }, { key: "replaceItem", value: function replaceItem(newItem, index) { var retValue = null; if (index < this.numberOfItems && index >= 0) { this._removeFromOtherLists(newItem); this._xforms[index] = newItem; retValue = newItem; this._list._update(); } return retValue; } /** * @param {Integer} index unsigned long * @throws {Error} * @returns {SVGTransform} */ }, { key: "removeItem", value: function removeItem(index) { if (index < this.numberOfItems && index >= 0) { var retValue = this._xforms[index]; var newxforms = new Array(this.numberOfItems - 1); var i; for (i = 0; i < index; ++i) { newxforms[i] = this._xforms[i]; } for (var j = i; j < this.numberOfItems - 1; ++j, ++i) { newxforms[j] = this._xforms[i + 1]; } this.numberOfItems--; this._xforms = newxforms; this._list._update(); return retValue; } var err = new Error('DOMException with code=INDEX_SIZE_ERR'); err.code = 1; throw err; } /** * @param {SVGTransform} newItem * @returns {SVGTransform} */ }, { key: "appendItem", value: function appendItem(newItem) { this._removeFromOtherLists(newItem); this._xforms.push(newItem); this.numberOfItems++; this._list._update(); return newItem; } }]); return SVGTransformList; }(); /** * @function module:SVGTransformList.resetListMap * @returns {void} */ var resetListMap = function resetListMap() { listMap_ = {}; }; /** * Removes transforms of the given element from the map. * @function module:SVGTransformList.removeElementFromListMap * @param {Element} elem - a DOM Element * @returns {void} */ var removeElementFromListMap = function removeElementFromListMap(elem) { // eslint-disable-line import/no-mutable-exports if (elem.id && listMap_[elem.id]) { delete listMap_[elem.id]; } }; /** * Returns an object that behaves like a `SVGTransformList` for the given DOM element. * @function module:SVGTransformList.getTransformList * @param {Element} elem - DOM element to get a transformlist from * @todo The polyfill should have `SVGAnimatedTransformList` and this should use it * @returns {SVGAnimatedTransformList|SVGTransformList} */ var getTransformList = function getTransformList(elem) { if (!supportsNativeTransformLists()) { var id = elem.id || 'temp'; var t = listMap_[id]; if (!t || id === 'temp') { listMap_[id] = new SVGTransformList(elem); listMap_[id]._init(); t = listMap_[id]; } return t; } if (elem.transform) { return elem.transform.baseVal; } if (elem.gradientTransform) { return elem.gradientTransform.baseVal; } if (elem.patternTransform) { return elem.patternTransform.baseVal; } return null; }; /** * Tools for working with units. * @module units * @license MIT * * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller */ var wAttrs = ['x', 'x1', 'cx', 'rx', 'width']; var hAttrs = ['y', 'y1', 'cy', 'ry', 'height']; var unitAttrs = ['r', 'radius'].concat(wAttrs, hAttrs); // unused /* const unitNumMap = { '%': 2, em: 3, ex: 4, px: 5, cm: 6, mm: 7, in: 8, pt: 9, pc: 10 }; */ // Container of elements. var elementContainer_; // Stores mapping of unit type to user coordinates. var typeMap_ = {}; /** * @interface module:units.ElementContainer */ /** * @function module:units.ElementContainer#getBaseUnit * @returns {string} The base unit type of the container ('em') */ /** * @function module:units.ElementContainer#getElement * @returns {?Element} An element in the container given an id */ /** * @function module:units.ElementContainer#getHeight * @returns {Float} The container's height */ /** * @function module:units.ElementContainer#getWidth * @returns {Float} The container's width */ /** * @function module:units.ElementContainer#getRoundDigits * @returns {Integer} The number of digits number should be rounded to */ /* eslint-disable jsdoc/valid-types */ /** * @typedef {PlainObject} module:units.TypeMap * @property {Float} em * @property {Float} ex * @property {Float} in * @property {Float} cm * @property {Float} mm * @property {Float} pt * @property {Float} pc * @property {Integer} px * @property {0} % */ /* eslint-enable jsdoc/valid-types */ /** * Initializes this module. * * @function module:units.init * @param {module:units.ElementContainer} elementContainer - An object implementing the ElementContainer interface. * @returns {void} */ var init = function init(elementContainer) { elementContainer_ = elementContainer; // Get correct em/ex values by creating a temporary SVG. var svg = document.createElementNS(NS.SVG, 'svg'); document.body.append(svg); var rect = document.createElementNS(NS.SVG, 'rect'); rect.setAttribute('width', '1em'); rect.setAttribute('height', '1ex'); rect.setAttribute('x', '1in'); svg.append(rect); var bb = rect.getBBox(); svg.remove(); var inch = bb.x; typeMap_ = { em: bb.width, ex: bb.height, "in": inch, cm: inch / 2.54, mm: inch / 25.4, pt: inch / 72, pc: inch / 6, px: 1, '%': 0 }; }; /** * Group: Unit conversion functions. */ /** * @function module:units.getTypeMap * @returns {module:units.TypeMap} The unit object with values for each unit */ var getTypeMap = function getTypeMap() { return typeMap_; }; /** * @typedef {GenericArray} module:units.CompareNumbers * @property {Integer} length 2 * @property {Float} 0 * @property {Float} 1 */ /** * Rounds a given value to a float with number of digits defined in * `round_digits` of `saveOptions` * * @function module:units.shortFloat * @param {string|Float|module:units.CompareNumbers} val - The value (or Array of two numbers) to be rounded * @returns {Float|string} If a string/number was given, returns a Float. If an array, return a string * with comma-separated floats */ var shortFloat = function shortFloat(val) { var digits = elementContainer_.getRoundDigits(); if (!isNaN(val)) { return Number(Number(val).toFixed(digits)); } if (Array.isArray(val)) { return shortFloat(val[0]) + ',' + shortFloat(val[1]); } return Number.parseFloat(val).toFixed(digits) - 0; }; /** * Converts the number to given unit or baseUnit. * @function module:units.convertUnit * @param {string|Float} val * @param {"em"|"ex"|"in"|"cm"|"mm"|"pt"|"pc"|"px"|"%"} [unit] * @returns {Float} */ var convertUnit = function convertUnit(val, unit) { unit = unit || elementContainer_.getBaseUnit(); // baseVal.convertToSpecifiedUnits(unitNumMap[unit]); // const val = baseVal.valueInSpecifiedUnits; // baseVal.convertToSpecifiedUnits(1); return shortFloat(val / typeMap_[unit]); }; /** * Sets an element's attribute based on the unit in its current value. * * @function module:units.setUnitAttr * @param {Element} elem - DOM element to be changed * @param {string} attr - Name of the attribute associated with the value * @param {string} val - Attribute value to convert * @returns {void} */ var setUnitAttr = function setUnitAttr(elem, attr, val) { // if (!isNaN(val)) { // New value is a number, so check currently used unit // const oldVal = elem.getAttribute(attr); // Enable this for alternate mode // if (oldVal !== null && (isNaN(oldVal) || elementContainer_.getBaseUnit() !== 'px')) { // // Old value was a number, so get unit, then convert // let unit; // if (oldVal.substr(-1) === '%') { // const res = getResolution(); // unit = '%'; // val *= 100; // if (wAttrs.includes(attr)) { // val = val / res.w; // } else if (hAttrs.includes(attr)) { // val = val / res.h; // } else { // return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2); // } // } else { // if (elementContainer_.getBaseUnit() !== 'px') { // unit = elementContainer_.getBaseUnit(); // } else { // unit = oldVal.substr(-2); // } // val = val / typeMap_[unit]; // } // // val += unit; // } // } elem.setAttribute(attr, val); }; /** * Converts given values to numbers. Attributes must be supplied in * case a percentage is given. * * @function module:units.convertToNum * @param {string} attr - Name of the attribute associated with the value * @param {string} val - Attribute value to convert * @returns {Float} The converted number */ var convertToNum = function convertToNum(attr, val) { // Return a number if that's what it already is if (!isNaN(val)) { return val - 0; } if (val.substr(-1) === '%') { // Deal with percentage, depends on attribute var _num = val.substr(0, val.length - 1) / 100; var width = elementContainer_.getWidth(); var height = elementContainer_.getHeight(); if (wAttrs.includes(attr)) { return _num * width; } if (hAttrs.includes(attr)) { return _num * height; } return _num * Math.sqrt(width * width + height * height) / Math.sqrt(2); } var unit = val.substr(-2); var num = val.substr(0, val.length - 2); // Note that this multiplication turns the string into a number return num * typeMap_[unit]; }; /** * Check if an attribute's value is in a valid format. * @function module:units.isValidUnit * @param {string} attr - The name of the attribute associated with the value * @param {string} val - The attribute value to check * @param {Element} selectedElement * @returns {boolean} Whether the unit is valid */ var isValidUnit = function isValidUnit(attr, val, selectedElement) { if (unitAttrs.includes(attr)) { // True if it's just a number if (!isNaN(val)) { return true; } // Not a number, check if it has a valid unit val = val.toLowerCase(); return Object.keys(typeMap_).some(function (unit) { var re = new RegExp('^-?[\\d\\.]+' + unit + '$'); return re.test(val); }); } if (attr === 'id') { // if we're trying to change the id, make sure it's not already present in the doc // and the id value is valid. var result = false; // because getElem() can throw an exception in the case of an invalid id // (according to https://www.w3.org/TR/xml-id/ IDs must be a NCName) // we wrap it in an exception and only return true if the ID was valid and // not already present try { var elem = elementContainer_.getElement(val); result = !elem || elem === selectedElement; } catch (e) {} return result; } return true; }; /** * Mathematical utilities. * @module math * @license MIT * * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller */ var NEAR_ZERO = 1e-14; // Throw away SVGSVGElement used for creating matrices/transforms. var svg$1 = document.createElementNS(NS.SVG, 'svg'); /** * A (hopefully) quicker function to transform a point by a matrix * (this function avoids any DOM calls and just does the math). * @function module:math.transformPoint * @param {Float} x - Float representing the x coordinate * @param {Float} y - Float representing the y coordinate * @param {SVGMatrix} m - Matrix object to transform the point with * @returns {module:math.XYObject} An x, y object representing the transformed point */ var transformPoint = function transformPoint(x, y, m) { return { x: m.a * x + m.c * y + m.e, y: m.b * x + m.d * y + m.f }; }; /** * Helper function to check if the matrix performs no actual transform * (i.e. exists for identity purposes). * @function module:math.isIdentity * @param {SVGMatrix} m - The matrix object to check * @returns {boolean} Indicates whether or not the matrix is 1,0,0,1,0,0 */ var isIdentity = function isIdentity(m) { return m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && m.e === 0 && m.f === 0; }; /** * This function tries to return a `SVGMatrix` that is the multiplication `m1 * m2`. * We also round to zero when it's near zero. * @function module:math.matrixMultiply * @param {...SVGMatrix} args - Matrix objects to multiply * @returns {SVGMatrix} The matrix object resulting from the calculation */ var matrixMultiply = function matrixMultiply() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var m = args.reduceRight(function (prev, m1) { return m1.multiply(prev); }); if (Math.abs(m.a) < NEAR_ZERO) { m.a = 0; } if (Math.abs(m.b) < NEAR_ZERO) { m.b = 0; } if (Math.abs(m.c) < NEAR_ZERO) { m.c = 0; } if (Math.abs(m.d) < NEAR_ZERO) { m.d = 0; } if (Math.abs(m.e) < NEAR_ZERO) { m.e = 0; } if (Math.abs(m.f) < NEAR_ZERO) { m.f = 0; } return m; }; /** * See if the given transformlist includes a non-indentity matrix transform. * @function module:math.hasMatrixTransform * @param {SVGTransformList} [tlist] - The transformlist to check * @returns {boolean} Whether or not a matrix transform was found */ var hasMatrixTransform = function hasMatrixTransform(tlist) { if (!tlist) { return false; } var num = tlist.numberOfItems; while (num--) { var xform = tlist.getItem(num); if (xform.type === 1 && !isIdentity(xform.matrix)) { return true; } } return false; }; /** * @typedef {PlainObject} module:math.TransformedBox An object with the following values * @property {module:math.XYObject} tl - The top left coordinate * @property {module:math.XYObject} tr - The top right coordinate * @property {module:math.XYObject} bl - The bottom left coordinate * @property {module:math.XYObject} br - The bottom right coordinate * @property {PlainObject} aabox - Object with the following values: * @property {Float} aabox.x - Float with the axis-aligned x coordinate * @property {Float} aabox.y - Float with the axis-aligned y coordinate * @property {Float} aabox.width - Float with the axis-aligned width coordinate * @property {Float} aabox.height - Float with the axis-aligned height coordinate */ /** * Transforms a rectangle based on the given matrix. * @function module:math.transformBox * @param {Float} l - Float with the box's left coordinate * @param {Float} t - Float with the box's top coordinate * @param {Float} w - Float with the box width * @param {Float} h - Float with the box height * @param {SVGMatrix} m - Matrix object to transform the box by * @returns {module:math.TransformedBox} */ var transformBox = function transformBox(l, t, w, h, m) { var tl = transformPoint(l, t, m), tr = transformPoint(l + w, t, m), bl = transformPoint(l, t + h, m), br = transformPoint(l + w, t + h, m), minx = Math.min(tl.x, tr.x, bl.x, br.x), maxx = Math.max(tl.x, tr.x, bl.x, br.x), miny = Math.min(tl.y, tr.y, bl.y, br.y), maxy = Math.max(tl.y, tr.y, bl.y, br.y); return { tl: tl, tr: tr, bl: bl, br: br, aabox: { x: minx, y: miny, width: maxx - minx, height: maxy - miny } }; }; /** * This returns a single matrix Transform for a given Transform List * (this is the equivalent of `SVGTransformList.consolidate()` but unlike * that method, this one does not modify the actual `SVGTransformList`). * This function is very liberal with its `min`, `max` arguments. * @function module:math.transformListToTransform * @param {SVGTransformList} tlist - The transformlist object * @param {Integer} [min=0] - Optional integer indicating start transform position * @param {Integer} [max] - Optional integer indicating end transform position; * defaults to one less than the tlist's `numberOfItems` * @returns {SVGTransform} A single matrix transform object */ var transformListToTransform = function transformListToTransform(tlist, min, max) { if (!tlist) { // Or should tlist = null have been prevented before this? return svg$1.createSVGTransformFromMatrix(svg$1.createSVGMatrix()); } min = min || 0; max = max || tlist.numberOfItems - 1; min = Number.parseInt(min); max = Number.parseInt(max); if (min > max) { var temp = max; max = min; min = temp; } var m = svg$1.createSVGMatrix(); for (var i = min; i <= max; ++i) { // if our indices are out of range, just use a harmless identity matrix var mtom = i >= 0 && i < tlist.numberOfItems ? tlist.getItem(i).matrix : svg$1.createSVGMatrix(); m = matrixMultiply(m, mtom); } return svg$1.createSVGTransformFromMatrix(m); }; /** * Get the matrix object for a given element. * @function module:math.getMatrix * @param {Element} elem - The DOM element to check * @returns {SVGMatrix} The matrix object associated with the element's transformlist */ var getMatrix = function getMatrix(elem) { var tlist = getTransformList(elem); return transformListToTransform(tlist).matrix; }; /** * Returns a 45 degree angle coordinate associated with the two given * coordinates. * @function module:math.snapToAngle * @param {Integer} x1 - First coordinate's x value * @param {Integer} y1 - First coordinate's y value * @param {Integer} x2 - Second coordinate's x value * @param {Integer} y2 - Second coordinate's y value * @returns {module:math.AngleCoord45} */ var snapToAngle = function snapToAngle(x1, y1, x2, y2) { var snap = Math.PI / 4; // 45 degrees var dx = x2 - x1; var dy = y2 - y1; var angle = Math.atan2(dy, dx); var dist = Math.sqrt(dx * dx + dy * dy); var snapangle = Math.round(angle / snap) * snap; return { x: x1 + dist * Math.cos(snapangle), y: y1 + dist * Math.sin(snapangle), a: snapangle }; }; /** * Check if two rectangles (BBoxes objects) intersect each other. * @function module:math.rectsIntersect * @param {SVGRect} r1 - The first BBox-like object * @param {SVGRect} r2 - The second BBox-like object * @returns {boolean} True if rectangles intersect */ var rectsIntersect = function rectsIntersect(r1, r2) { return r2.x < r1.x + r1.width && r2.x + r2.width > r1.x && r2.y < r1.y + r1.height && r2.y + r2.height > r1.y; }; var $$1 = jQueryPluginSVG(jQuery); // String used to encode base64. var KEYSTR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; // Much faster than running getBBox() every time var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use,clipPath'; var visElemsArr = visElems.split(','); // const hidElems = 'defs,desc,feGaussianBlur,filter,linearGradient,marker,mask,metadata,pattern,radialGradient,stop,switch,symbol,title,textPath'; var editorContext_ = null; var domdoc_ = null; var domcontainer_ = null; var svgroot_ = null; /** * Object with the following keys/values. * @typedef {PlainObject} module:utilities.SVGElementJSON * @property {string} element - Tag name of the SVG element to create * @property {PlainObject} attr - Has key-value attributes to assign to the new element. An `id` should be set so that {@link module:utilities.EditorContext#addSVGElementFromJson} can later re-identify the element for modification or replacement. * @property {boolean} [curStyles=false] - Indicates whether current style attributes should be applied first * @property {module:utilities.SVGElementJSON[]} [children] - Data objects to be added recursively as children * @property {string} [namespace="http://www.w3.org/2000/svg"] - Indicate a (non-SVG) namespace */ /** * An object that creates SVG elements for the canvas. * * @interface module:utilities.EditorContext * @property {module:path.pathActions} pathActions */ /** * @function module:utilities.EditorContext#getSVGContent * @returns {SVGSVGElement} */ /** * Create a new SVG element based on the given object keys/values and add it * to the current layer. * The element will be run through `cleanupElement` before being returned. * @function module:utilities.EditorContext#addSVGElementFromJson * @param {module:utilities.SVGElementJSON} data * @returns {Element} The new element */ /** * @function module:utilities.EditorContext#getSelectedElements * @returns {Element[]} the array with selected DOM elements */ /** * @function module:utilities.EditorContext#getDOMDocument * @returns {HTMLDocument} */ /** * @function module:utilities.EditorContext#getDOMContainer * @returns {HTMLElement} */ /** * @function module:utilities.EditorContext#getSVGRoot * @returns {SVGSVGElement} */ /** * @function module:utilities.EditorContext#getBaseUnit * @returns {string} */ /** * @function module:utilities.EditorContext#getSnappingStep * @returns {Float|string} */ /** * @function module:utilities.init * @param {module:utilities.EditorContext} editorContext * @returns {void} */ var init$1 = function init(editorContext) { editorContext_ = editorContext; domdoc_ = editorContext.getDOMDocument(); domcontainer_ = editorContext.getDOMContainer(); svgroot_ = editorContext.getSVGRoot(); }; /** * Used to prevent the [Billion laughs attack]{@link https://en.wikipedia.org/wiki/Billion_laughs_attack}. * @function module:utilities.dropXMLInternalSubset * @param {string} str String to be processed * @returns {string} The string with entity declarations in the internal subset removed * @todo This might be needed in other places `parseFromString` is used even without LGTM flagging */ var dropXMLInternalSubset = function dropXMLInternalSubset(str) { return str.replace(/()/, '$1$2'); // return str.replace(/(?\?\]>)/, '$$'); }; /** * Converts characters in a string to XML-friendly entities. * @function module:utilities.toXml * @example `&` becomes `&` * @param {string} str - The string to be converted * @returns {string} The converted string */ var toXml = function toXml(str) { // ' is ok in XML, but not HTML // > does not normally need escaping, though it can if within a CDATA expression (and preceded by "]]") return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); // Note: `'` is XML only }; // public domain. It would be nice if you left this header intact. // Base64 code from Tyler Akins -- http://rumkin.com // schiller: Removed string concatenation in favour of Array.join() optimization, // also precalculate the size of the array needed. /** * Converts a string to base64. * @function module:utilities.encode64 * @param {string} input * @returns {string} Base64 output */ function encode64(input) { // base64 strings are 4/3 larger than the original string input = encodeUTF8(input); // convert non-ASCII characters // input = convertToXMLReferences(input); if (window.btoa) { return window.btoa(input); // Use native if available } var output = new Array(Math.floor((input.length + 2) / 3) * 4); var i = 0, p = 0; do { var chr1 = input.charCodeAt(i++); var chr2 = input.charCodeAt(i++); var chr3 = input.charCodeAt(i++); /* eslint-disable no-bitwise */ var enc1 = chr1 >> 2; var enc2 = (chr1 & 3) << 4 | chr2 >> 4; var enc3 = (chr2 & 15) << 2 | chr3 >> 6; var enc4 = chr3 & 63; /* eslint-enable no-bitwise */ if (Number.isNaN(chr2)) { enc3 = 64; enc4 = 64; } else if (Number.isNaN(chr3)) { enc4 = 64; } output[p++] = KEYSTR.charAt(enc1); output[p++] = KEYSTR.charAt(enc2); output[p++] = KEYSTR.charAt(enc3); output[p++] = KEYSTR.charAt(enc4); } while (i < input.length); return output.join(''); } /** * Converts a string from base64. * @function module:utilities.decode64 * @param {string} input Base64-encoded input * @returns {string} Decoded output */ function decode64(input) { if (window.atob) { return decodeUTF8(window.atob(input)); } // remove all characters that are not A-Z, a-z, 0-9, +, /, or = input = input.replace(/[^A-Za-z\d+/=]/g, ''); var output = ''; var i = 0; do { var enc1 = KEYSTR.indexOf(input.charAt(i++)); var enc2 = KEYSTR.indexOf(input.charAt(i++)); var enc3 = KEYSTR.indexOf(input.charAt(i++)); var enc4 = KEYSTR.indexOf(input.charAt(i++)); /* eslint-disable no-bitwise */ var chr1 = enc1 << 2 | enc2 >> 4; var chr2 = (enc2 & 15) << 4 | enc3 >> 2; var chr3 = (enc3 & 3) << 6 | enc4; /* eslint-enable no-bitwise */ output += String.fromCharCode(chr1); if (enc3 !== 64) { output += String.fromCharCode(chr2); } if (enc4 !== 64) { output += String.fromCharCode(chr3); } } while (i < input.length); return decodeUTF8(output); } /** * @function module:utilities.decodeUTF8 * @param {string} argString * @returns {string} */ function decodeUTF8(argString) { return decodeURIComponent(escape(argString)); } // codedread:does not seem to work with webkit-based browsers on OSX // Brettz9: please test again as function upgraded /** * @function module:utilities.encodeUTF8 * @param {string} argString * @returns {string} */ var encodeUTF8 = function encodeUTF8(argString) { return unescape(encodeURIComponent(argString)); }; /** * Convert dataURL to object URL. * @function module:utilities.dataURLToObjectURL * @param {string} dataurl * @returns {string} object URL or empty string */ var dataURLToObjectURL = function dataURLToObjectURL(dataurl) { if (typeof Uint8Array === 'undefined' || typeof Blob === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) { return ''; } var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]); /* const [prefix, suffix] = dataurl.split(','), {groups: {mime}} = prefix.match(/:(?.*?);/), bstr = atob(suffix); */ var n = bstr.length; var u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } var blob = new Blob([u8arr], { type: mime }); return URL.createObjectURL(blob); }; /** * Get object URL for a blob object. * @function module:utilities.createObjectURL * @param {Blob} blob A Blob object or File object * @returns {string} object URL or empty string */ var createObjectURL = function createObjectURL(blob) { if (!blob || typeof URL === 'undefined' || !URL.createObjectURL) { return ''; } return URL.createObjectURL(blob); }; /** * @property {string} blankPageObjectURL */ var blankPageObjectURL = function () { if (typeof Blob === 'undefined') { return ''; } var blob = new Blob(['SVG-edit '], { type: 'text/html' }); return createObjectURL(blob); }(); /** * Cross-browser compatible method of converting a string to an XML tree. * Found this function [here]{@link http://groups.google.com/group/jquery-dev/browse_thread/thread/c6d11387c580a77f}. * @function module:utilities.text2xml * @param {string} sXML * @throws {Error} * @returns {XMLDocument} */ var text2xml = function text2xml(sXML) { if (sXML.includes('` * - `` * - `` * @function module:utilities.getUrlFromAttr * @param {string} attrVal The attribute value as a string * @returns {string} String with just the URL, like "someFile.svg#foo" */ var getUrlFromAttr = function getUrlFromAttr(attrVal) { if (attrVal) { // url('#somegrad') if (attrVal.startsWith('url("')) { return attrVal.substring(5, attrVal.indexOf('"', 6)); } // url('#somegrad') if (attrVal.startsWith("url('")) { return attrVal.substring(5, attrVal.indexOf("'", 6)); } if (attrVal.startsWith('url(')) { return attrVal.substring(4, attrVal.indexOf(')')); } } return null; }; /** * @function module:utilities.getHref * @param {Element} elem * @returns {string} The given element's `xlink:href` value */ var getHref = function getHref(elem) { // eslint-disable-line import/no-mutable-exports return elem.getAttributeNS(NS.XLINK, 'href'); }; /** * Sets the given element's `xlink:href` value. * @function module:utilities.setHref * @param {Element} elem * @param {string} val * @returns {void} */ var setHref = function setHref(elem, val) { // eslint-disable-line import/no-mutable-exports elem.setAttributeNS(NS.XLINK, 'xlink:href', val); }; /** * @function module:utilities.findDefs * @returns {SVGDefsElement} The document's `` element, creating it first if necessary */ var findDefs = function findDefs() { var svgElement = editorContext_.getSVGContent(); var defs = svgElement.getElementsByTagNameNS(NS.SVG, 'defs'); if (defs.length > 0) { defs = defs[0]; } else { defs = svgElement.ownerDocument.createElementNS(NS.SVG, 'defs'); if (svgElement.firstChild) { // first child is a comment, so call nextSibling svgElement.insertBefore(defs, svgElement.firstChild.nextSibling); // svgElement.firstChild.nextSibling.before(defs); // Not safe } else { svgElement.append(defs); } } return defs; }; // TODO(codedread): Consider moving the next to functions to bbox.js /** * Get correct BBox for a path in Webkit. * Converted from code found [here]{@link http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html}. * @function module:utilities.getPathBBox * @param {SVGPathElement} path - The path DOM element to get the BBox for * @returns {module:utilities.BBoxObject} A BBox-like object */ var getPathBBox = function getPathBBox(path) { var seglist = path.pathSegList; var tot = seglist.numberOfItems; var bounds = [[], []]; var start = seglist.getItem(0); var P0 = [start.x, start.y]; var getCalc = function getCalc(j, P1, P2, P3) { return function (t) { return 1 - Math.pow(t, 3) * P0[j] + 3 * 1 - Math.pow(t, 2) * t * P1[j] + 3 * (1 - t) * Math.pow(t, 2) * P2[j] + Math.pow(t, 3) * P3[j]; }; }; for (var i = 0; i < tot; i++) { var seg = seglist.getItem(i); if (seg.x === undefined) { continue; } // Add actual points to limits bounds[0].push(P0[0]); bounds[1].push(P0[1]); if (seg.x1) { var P1 = [seg.x1, seg.y1], P2 = [seg.x2, seg.y2], P3 = [seg.x, seg.y]; for (var j = 0; j < 2; j++) { var calc = getCalc(j, P1, P2, P3); var b = 6 * P0[j] - 12 * P1[j] + 6 * P2[j]; var a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j]; var c = 3 * P1[j] - 3 * P0[j]; if (a === 0) { if (b === 0) { continue; } var t = -c / b; if (t > 0 && t < 1) { bounds[j].push(calc(t)); } continue; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) { continue; } var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (t1 > 0 && t1 < 1) { bounds[j].push(calc(t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (t2 > 0 && t2 < 1) { bounds[j].push(calc(t2)); } } P0 = P3; } else { bounds[0].push(seg.x); bounds[1].push(seg.y); } } var x = Math.min.apply(null, bounds[0]); var w = Math.max.apply(null, bounds[0]) - x; var y = Math.min.apply(null, bounds[1]); var h = Math.max.apply(null, bounds[1]) - y; return { x: x, y: y, width: w, height: h }; }; /** * Get the given/selected element's bounding box object, checking for * horizontal/vertical lines (see issue 717) * Note that performance is currently terrible, so some way to improve would * be great. * @param {Element} selected - Container or `` DOM element * @returns {DOMRect} Bounding box object */ function groupBBFix(selected) { if (supportsHVLineContainerBBox()) { try { return selected.getBBox(); } catch (e) {} } var ref = $$1.data(selected, 'ref'); var matched = null; var ret, copy; if (ref) { copy = $$1(ref).children().clone().attr('visibility', 'hidden'); $$1(svgroot_).append(copy); matched = copy.filter('line, path'); } else { matched = $$1(selected).find('line, path'); } var issue = false; if (matched.length) { matched.each(function () { var bb = this.getBBox(); if (!bb.width || !bb.height) { issue = true; } }); if (issue) { var elems = ref ? copy : $$1(selected).children(); ret = getStrokedBBox(elems); } else { ret = selected.getBBox(); } } else { ret = selected.getBBox(); } if (ref) { copy.remove(); } return ret; } /** * Get the given/selected element's bounding box object, convert it to be more * usable when necessary. * @function module:utilities.getBBox * @param {Element} elem - Optional DOM element to get the BBox for * @returns {module:utilities.BBoxObject} Bounding box object */ var getBBox = function getBBox(elem) { var selected = elem || editorContext_.geSelectedElements()[0]; if (elem.nodeType !== 1) { return null; } var elname = selected.nodeName; var ret = null; switch (elname) { case 'text': if (selected.textContent === '') { selected.textContent = 'a'; // Some character needed for the selector to use. ret = selected.getBBox(); selected.textContent = ''; } else if (selected.getBBox) { ret = selected.getBBox(); } break; case 'path': if (!supportsPathBBox()) { ret = getPathBBox(selected); } else if (selected.getBBox) { ret = selected.getBBox(); } break; case 'g': case 'a': ret = groupBBFix(selected); break; default: if (elname === 'use') { ret = groupBBFix(selected); // , true); } if (elname === 'use' || elname === 'foreignObject' && isWebkit()) { if (!ret) { ret = selected.getBBox(); } // This is resolved in later versions of webkit, perhaps we should // have a featured detection for correct 'use' behavior? // —————————— if (!isWebkit()) { var _ret = ret, x = _ret.x, y = _ret.y, width = _ret.width, height = _ret.height; var bb = { width: width, height: height, x: x + Number.parseFloat(selected.getAttribute('x') || 0), y: y + Number.parseFloat(selected.getAttribute('y') || 0) }; ret = bb; } } else if (visElemsArr.includes(elname)) { if (selected) { try { ret = selected.getBBox(); } catch (err) { // tspan (and textPath apparently) have no `getBBox` in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=937268 // Re: Chrome returning bbox for containing text element, see: https://bugs.chromium.org/p/chromium/issues/detail?id=349835 var extent = selected.getExtentOfChar(0); // pos+dimensions of the first glyph var _width = selected.getComputedTextLength(); // width of the tspan ret = { x: extent.x, y: extent.y, width: _width, height: extent.height }; } } else { // Check if element is child of a foreignObject var fo = $$1(selected).closest('foreignObject'); if (fo.length) { if (fo[0].getBBox) { ret = fo[0].getBBox(); } } } } } if (ret) { ret = bboxToObj(ret); } // get the bounding box from the DOM (which is in that element's coordinate system) return ret; }; /** * @typedef {GenericArray} module:utilities.PathSegmentArray * @property {Integer} length 2 * @property {"M"|"L"|"C"|"Z"} 0 * @property {Float[]} 1 */ /** * Create a path 'd' attribute from path segments. * Each segment is an array of the form: `[singleChar, [x,y, x,y, ...]]` * @function module:utilities.getPathDFromSegments * @param {module:utilities.PathSegmentArray[]} pathSegments - An array of path segments to be converted * @returns {string} The converted path d attribute. */ var getPathDFromSegments = function getPathDFromSegments(pathSegments) { var d = ''; $$1.each(pathSegments, function (j, _ref2) { var _ref3 = _slicedToArray(_ref2, 2), singleChar = _ref3[0], pts = _ref3[1]; d += singleChar; for (var i = 0; i < pts.length; i += 2) { d += pts[i] + ',' + pts[i + 1] + ' '; } }); return d; }; /** * Make a path 'd' attribute from a simple SVG element shape. * @function module:utilities.getPathDFromElement * @param {Element} elem - The element to be converted * @returns {string} The path d attribute or `undefined` if the element type is unknown. */ var getPathDFromElement = function getPathDFromElement(elem) { // Possibly the cubed root of 6, but 1.81 works best var num = 1.81; var d, a, rx, ry; switch (elem.tagName) { case 'ellipse': case 'circle': { a = $$1(elem).attr(['rx', 'ry', 'cx', 'cy']); var _a = a, cx = _a.cx, cy = _a.cy; var _a2 = a; rx = _a2.rx; ry = _a2.ry; if (elem.tagName === 'circle') { ry = $$1(elem).attr('r'); rx = ry; } d = getPathDFromSegments([['M', [cx - rx, cy]], ['C', [cx - rx, cy - ry / num, cx - rx / num, cy - ry, cx, cy - ry]], ['C', [cx + rx / num, cy - ry, cx + rx, cy - ry / num, cx + rx, cy]], ['C', [cx + rx, cy + ry / num, cx + rx / num, cy + ry, cx, cy + ry]], ['C', [cx - rx / num, cy + ry, cx - rx, cy + ry / num, cx - rx, cy]], ['Z', []]]); break; } case 'path': d = elem.getAttribute('d'); break; case 'line': a = $$1(elem).attr(['x1', 'y1', 'x2', 'y2']); d = 'M' + a.x1 + ',' + a.y1 + 'L' + a.x2 + ',' + a.y2; break; case 'polyline': d = 'M' + elem.getAttribute('points'); break; case 'polygon': d = 'M' + elem.getAttribute('points') + ' Z'; break; case 'rect': { var r = $$1(elem).attr(['rx', 'ry']); rx = r.rx; ry = r.ry; var b = elem.getBBox(); var x = b.x, y = b.y, w = b.width, h = b.height; num = 4 - num; // Why? Because! if (!rx && !ry) { // Regular rect d = getPathDFromSegments([['M', [x, y]], ['L', [x + w, y]], ['L', [x + w, y + h]], ['L', [x, y + h]], ['L', [x, y]], ['Z', []]]); } else { d = getPathDFromSegments([['M', [x, y + ry]], ['C', [x, y + ry / num, x + rx / num, y, x + rx, y]], ['L', [x + w - rx, y]], ['C', [x + w - rx / num, y, x + w, y + ry / num, x + w, y + ry]], ['L', [x + w, y + h - ry]], ['C', [x + w, y + h - ry / num, x + w - rx / num, y + h, x + w - rx, y + h]], ['L', [x + rx, y + h]], ['C', [x + rx / num, y + h, x, y + h - ry / num, x, y + h - ry]], ['L', [x, y + ry]], ['Z', []]]); } break; } } return d; }; /** * Get a set of attributes from an element that is useful for convertToPath. * @function module:utilities.getExtraAttributesForConvertToPath * @param {Element} elem - The element to be probed * @returns {PlainObject<"marker-start"|"marker-end"|"marker-mid"|"filter"|"clip-path", string>} An object with attributes. */ var getExtraAttributesForConvertToPath = function getExtraAttributesForConvertToPath(elem) { var attrs = {}; // TODO: make this list global so that we can properly maintain it // TODO: what about @transform, @clip-rule, @fill-rule, etc? $$1.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function () { var a = elem.getAttribute(this); if (a) { attrs[this] = a; } }); return attrs; }; /** * Get the BBox of an element-as-path. * @function module:utilities.getBBoxOfElementAsPath * @param {Element} elem - The DOM element to be probed * @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson * @param {module:path.pathActions} pathActions - If a transform exists, `pathActions.resetOrientation()` is used. See: canvas.pathActions. * @returns {DOMRect|false} The resulting path's bounding box object. */ var getBBoxOfElementAsPath = function getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions) { var path = addSVGElementFromJson({ element: 'path', attr: getExtraAttributesForConvertToPath(elem) }); var eltrans = elem.getAttribute('transform'); if (eltrans) { path.setAttribute('transform', eltrans); } var parentNode = elem.parentNode; if (elem.nextSibling) { elem.before(path); } else { parentNode.append(path); } var d = getPathDFromElement(elem); if (d) { path.setAttribute('d', d); } else { path.remove(); } // Get the correct BBox of the new path, then discard it pathActions.resetOrientation(path); var bb = false; try { bb = path.getBBox(); } catch (e) {// Firefox fails } path.remove(); return bb; }; /** * Convert selected element to a path. * @function module:utilities.convertToPath * @param {Element} elem - The DOM element to be converted * @param {module:utilities.SVGElementJSON} attrs - Apply attributes to new path. see canvas.convertToPath * @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson * @param {module:path.pathActions} pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions. * @param {module:draw.DrawCanvasInit#clearSelection|module:path.EditorContext#clearSelection} clearSelection - see [canvas.clearSelection]{@link module:svgcanvas.SvgCanvas#clearSelection} * @param {module:path.EditorContext#addToSelection} addToSelection - see [canvas.addToSelection]{@link module:svgcanvas.SvgCanvas#addToSelection} * @param {module:history} hstry - see history module * @param {module:path.EditorContext#addCommandToHistory|module:draw.DrawCanvasInit#addCommandToHistory} addCommandToHistory - see [canvas.addCommandToHistory]{@link module:svgcanvas~addCommandToHistory} * @returns {SVGPathElement|null} The converted path element or null if the DOM element was not recognized. */ var convertToPath = function convertToPath(elem, attrs, addSVGElementFromJson, pathActions, clearSelection, addToSelection, hstry, addCommandToHistory) { var batchCmd = new hstry.BatchCommand('Convert element to Path'); // Any attribute on the element not covered by the passed-in attributes attrs = $$1.extend({}, attrs, getExtraAttributesForConvertToPath(elem)); var path = addSVGElementFromJson({ element: 'path', attr: attrs }); var eltrans = elem.getAttribute('transform'); if (eltrans) { path.setAttribute('transform', eltrans); } var id = elem.id; var parentNode = elem.parentNode; if (elem.nextSibling) { elem.before(path); } else { parentNode.append(path); } var d = getPathDFromElement(elem); if (d) { path.setAttribute('d', d); // Replace the current element with the converted one // Reorient if it has a matrix if (eltrans) { var tlist = getTransformList(path); if (hasMatrixTransform(tlist)) { pathActions.resetOrientation(path); } } var nextSibling = elem.nextSibling; batchCmd.addSubCommand(new hstry.RemoveElementCommand(elem, nextSibling, parent)); batchCmd.addSubCommand(new hstry.InsertElementCommand(path)); clearSelection(); elem.remove(); path.setAttribute('id', id); path.removeAttribute('visibility'); addToSelection([path], true); addCommandToHistory(batchCmd); return path; } // the elem.tagName was not recognized, so no "d" attribute. Remove it, so we've haven't changed anything. path.remove(); return null; }; /** * Can the bbox be optimized over the native getBBox? The optimized bbox is the same as the native getBBox when * the rotation angle is a multiple of 90 degrees and there are no complex transforms. * Getting an optimized bbox can be dramatically slower, so we want to make sure it's worth it. * * The best example for this is a circle rotate 45 degrees. The circle doesn't get wider or taller when rotated * about it's center. * * The standard, unoptimized technique gets the native bbox of the circle, rotates the box 45 degrees, uses * that width and height, and applies any transforms to get the final bbox. This means the calculated bbox * is much wider than the original circle. If the angle had been 0, 90, 180, etc. both techniques render the * same bbox. * * The optimization is not needed if the rotation is a multiple 90 degrees. The default technique is to call * getBBox then apply the angle and any transforms. * * @param {Float} angle - The rotation angle in degrees * @param {boolean} hasAMatrixTransform - True if there is a matrix transform * @returns {boolean} True if the bbox can be optimized. */ function bBoxCanBeOptimizedOverNativeGetBBox(angle, hasAMatrixTransform) { var angleModulo90 = angle % 90; var closeTo90 = angleModulo90 < -89.99 || angleModulo90 > 89.99; var closeTo0 = angleModulo90 > -0.001 && angleModulo90 < 0.001; return hasAMatrixTransform || !(closeTo0 || closeTo90); } /** * Get bounding box that includes any transforms. * @function module:utilities.getBBoxWithTransform * @param {Element} elem - The DOM element to be converted * @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson * @param {module:path.pathActions} pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions. * @returns {module:utilities.BBoxObject|module:math.TransformedBox|DOMRect} A single bounding box object */ var getBBoxWithTransform = function getBBoxWithTransform(elem, addSVGElementFromJson, pathActions) { // TODO: Fix issue with rotated groups. Currently they work // fine in FF, but not in other browsers (same problem mentioned // in Issue 339 comment #2). var bb = getBBox(elem); if (!bb) { return null; } var tlist = getTransformList(elem); var angle = getRotationAngleFromTransformList(tlist); var hasMatrixXForm = hasMatrixTransform(tlist); if (angle || hasMatrixXForm) { var goodBb = false; if (bBoxCanBeOptimizedOverNativeGetBBox(angle, hasMatrixXForm)) { // Get the BBox from the raw path for these elements // TODO: why ellipse and not circle var elemNames = ['ellipse', 'path', 'line', 'polyline', 'polygon']; if (elemNames.includes(elem.tagName)) { goodBb = getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions); bb = goodBb; } else if (elem.tagName === 'rect') { // Look for radius var rx = elem.getAttribute('rx'); var ry = elem.getAttribute('ry'); if (rx || ry) { goodBb = getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions); bb = goodBb; } } } if (!goodBb) { var _transformListToTrans = transformListToTransform(tlist), matrix = _transformListToTrans.matrix; bb = transformBox(bb.x, bb.y, bb.width, bb.height, matrix).aabox; // Old technique that was exceedingly slow with large documents. // // Accurate way to get BBox of rotated element in Firefox: // Put element in group and get its BBox // // Must use clone else FF freaks out // const clone = elem.cloneNode(true); // const g = document.createElementNS(NS.SVG, 'g'); // const parent = elem.parentNode; // parent.append(g); // g.append(clone); // const bb2 = bboxToObj(g.getBBox()); // g.remove(); } } return bb; }; /** * @param {Element} elem * @returns {Float} * @todo This is problematic with large stroke-width and, for example, a single * horizontal line. The calculated BBox extends way beyond left and right sides. */ function getStrokeOffsetForBBox(elem) { var sw = elem.getAttribute('stroke-width'); return !isNaN(sw) && elem.getAttribute('stroke') !== 'none' ? sw / 2 : 0; } /** * @typedef {PlainObject} BBox * @property {Integer} x The x value * @property {Integer} y The y value * @property {Float} width * @property {Float} height */ /** * Get the bounding box for one or more stroked and/or transformed elements. * @function module:utilities.getStrokedBBox * @param {Element[]} elems - Array with DOM elements to check * @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson * @param {module:path.pathActions} pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions. * @returns {module:utilities.BBoxObject|module:math.TransformedBox|DOMRect} A single bounding box object */ var getStrokedBBox = function getStrokedBBox(elems, addSVGElementFromJson, pathActions) { if (!elems || !elems.length) { return false; } var fullBb; $$1.each(elems, function () { if (fullBb) { return; } if (!this.parentNode) { return; } fullBb = getBBoxWithTransform(this, addSVGElementFromJson, pathActions); }); // This shouldn't ever happen... if (fullBb === undefined) { return null; } // fullBb doesn't include the stoke, so this does no good! // if (elems.length == 1) return fullBb; var maxX = fullBb.x + fullBb.width; var maxY = fullBb.y + fullBb.height; var minX = fullBb.x; var minY = fullBb.y; // If only one elem, don't call the potentially slow getBBoxWithTransform method again. if (elems.length === 1) { var offset = getStrokeOffsetForBBox(elems[0]); minX -= offset; minY -= offset; maxX += offset; maxY += offset; } else { $$1.each(elems, function (i, elem) { var curBb = getBBoxWithTransform(elem, addSVGElementFromJson, pathActions); if (curBb) { var _offset = getStrokeOffsetForBBox(elem); minX = Math.min(minX, curBb.x - _offset); minY = Math.min(minY, curBb.y - _offset); // TODO: The old code had this test for max, but not min. I suspect this test should be for both min and max if (elem.nodeType === 1) { maxX = Math.max(maxX, curBb.x + curBb.width + _offset); maxY = Math.max(maxY, curBb.y + curBb.height + _offset); } } }); } fullBb.x = minX; fullBb.y = minY; fullBb.width = maxX - minX; fullBb.height = maxY - minY; return fullBb; }; /** * Get all elements that have a BBox (excludes ``, ``, etc). * Note that 0-opacity, off-screen etc elements are still considered "visible" * for this function. * @function module:utilities.getVisibleElements * @param {Element} parentElement - The parent DOM element to search within * @returns {Element[]} All "visible" elements. */ var getVisibleElements = function getVisibleElements(parentElement) { if (!parentElement) { parentElement = $$1(editorContext_.getSVGContent()).children(); // Prevent layers from being included } var contentElems = []; $$1(parentElement).children().each(function (i, elem) { if (elem.getBBox) { contentElems.push(elem); } }); return contentElems.reverse(); }; /** * Get the bounding box for one or more stroked and/or transformed elements. * @function module:utilities.getStrokedBBoxDefaultVisible * @param {Element[]} elems - Array with DOM elements to check * @returns {module:utilities.BBoxObject} A single bounding box object */ var getStrokedBBoxDefaultVisible = function getStrokedBBoxDefaultVisible(elems) { if (!elems) { elems = getVisibleElements(); } return getStrokedBBox(elems, editorContext_.addSVGElementFromJson, editorContext_.pathActions); }; /** * Get the rotation angle of the given transform list. * @function module:utilities.getRotationAngleFromTransformList * @param {SVGTransformList} tlist - List of transforms * @param {boolean} toRad - When true returns the value in radians rather than degrees * @returns {Float} The angle in degrees or radians */ var getRotationAngleFromTransformList = function getRotationAngleFromTransformList(tlist, toRad) { if (!tlist) { return 0; } // <svg> elements have no tlist var N = tlist.numberOfItems; for (var i = 0; i < N; ++i) { var xform = tlist.getItem(i); if (xform.type === 4) { return toRad ? xform.angle * Math.PI / 180.0 : xform.angle; } } return 0.0; }; /** * Get the rotation angle of the given/selected DOM element. * @function module:utilities.getRotationAngle * @param {Element} [elem] - DOM element to get the angle for. Default to first of selected elements. * @param {boolean} [toRad=false] - When true returns the value in radians rather than degrees * @returns {Float} The angle in degrees or radians */ var getRotationAngle = function getRotationAngle(elem, toRad) { // eslint-disable-line import/no-mutable-exports var selected = elem || editorContext_.getSelectedElements()[0]; // find the rotation transform (if any) and set it var tlist = getTransformList(selected); return getRotationAngleFromTransformList(tlist, toRad); }; /** * Get the reference element associated with the given attribute value. * @function module:utilities.getRefElem * @param {string} attrVal - The attribute value as a string * @returns {Element} Reference element */ var getRefElem = function getRefElem(attrVal) { return getElem(getUrlFromAttr(attrVal).substr(1)); }; /** * Get a DOM element by ID within the SVG root element. * @function module:utilities.getElem * @param {string} id - String with the element's new ID * @returns {?Element} */ var getElem = supportsSelectors() ? function (id) { // querySelector lookup return svgroot_.querySelector('#' + id); } : supportsXpath() ? function (id) { // xpath lookup return domdoc_.evaluate('svg:svg[@id="svgroot"]//svg:*[@id="' + id + '"]', domcontainer_, function () { return NS.SVG; }, 9, null).singleNodeValue; } : function (id) { // jQuery lookup: twice as slow as xpath in FF return $$1(svgroot_).find("[id=".concat(id, "]"))[0]; }; /** * Assigns multiple attributes to an element. * @function module:utilities.assignAttributes * @param {Element} elem - DOM element to apply new attribute values to * @param {PlainObject<string, string>} attrs - Object with attribute keys/values * @param {Integer} [suspendLength] - Milliseconds to suspend redraw * @param {boolean} [unitCheck=false] - Boolean to indicate the need to use units.setUnitAttr * @returns {void} */ var assignAttributes = function assignAttributes(elem, attrs, suspendLength, unitCheck) { for (var _i = 0, _Object$entries = Object.entries(attrs); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], value = _Object$entries$_i[1]; var ns = key.substr(0, 4) === 'xml:' ? NS.XML : key.substr(0, 6) === 'xlink:' ? NS.XLINK : null; if (isNullish(value)) { if (ns) { elem.removeAttributeNS(ns, key); } else { elem.removeAttribute(key); } continue; } if (ns) { elem.setAttributeNS(ns, key, value); } else if (!unitCheck) { elem.setAttribute(key, value); } else { setUnitAttr(elem, key, value); } } }; /** * Remove unneeded (default) attributes, making resulting SVG smaller. * @function module:utilities.cleanupElement * @param {Element} element - DOM element to clean up * @returns {void} */ var cleanupElement = function cleanupElement(element) { var defaults = { 'fill-opacity': 1, 'stop-opacity': 1, opacity: 1, stroke: 'none', 'stroke-dasharray': 'none', 'stroke-linejoin': 'miter', 'stroke-linecap': 'butt', 'stroke-opacity': 1, 'stroke-width': 1, rx: 0, ry: 0 }; if (element.nodeName === 'ellipse') { // Ellipse elements require rx and ry attributes delete defaults.rx; delete defaults.ry; } Object.entries(defaults).forEach(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 2), attr = _ref5[0], val = _ref5[1]; if (element.getAttribute(attr) === String(val)) { element.removeAttribute(attr); } }); }; /** * Round value to for snapping. * @function module:utilities.snapToGrid * @param {Float} value * @returns {Integer} */ var snapToGrid = function snapToGrid(value) { var unit = editorContext_.getBaseUnit(); var stepSize = editorContext_.getSnappingStep(); if (unit !== 'px') { stepSize *= getTypeMap()[unit]; } value = Math.round(value / stepSize) * stepSize; return value; }; /** * Escapes special characters in a regular expression. * @function module:utilities.regexEscape * @param {string} str * @returns {string} */ var regexEscape = function regexEscape(str) { // Originally from: http://phpjs.org/functions return String(str).replace(/[.\\+*?[^\]$(){}=!<>|:-]/g, '\\$&'); }; /** * Prevents default browser click behaviour on the given element. * @function module:utilities.preventClickDefault * @param {Element} img - The DOM element to prevent the click on * @returns {void} */ var preventClickDefault = function preventClickDefault(img) { $$1(img).click(function (e) { e.preventDefault(); }); }; /** * @callback module:utilities.GetNextID * @returns {string} The ID */ /** * Whether a value is `null` or `undefined`. * @param {any} val * @returns {boolean} */ var isNullish = function isNullish(val) { return val === null || val === undefined; }; var $q = function $q(sel) { return document.querySelector(sel); }; /* globals jQuery */ /** * Adds context menu functionality. * @module contextmenu * @license Apache-2.0 * @author Adam Bender */ // Dependencies: // 1) jQuery (for dom injection of context menus) var $$2 = jQuery; var contextMenuExtensions = {}; /** * @function module:contextmenu.hasCustomHandler * @param {string} handlerKey * @returns {boolean} */ var hasCustomHandler = function hasCustomHandler(handlerKey) { return Boolean(contextMenuExtensions[handlerKey]); }; /** * @function module:contextmenu.getCustomHandler * @param {string} handlerKey * @returns {module:contextmenu.MenuItemAction} */ var getCustomHandler = function getCustomHandler(handlerKey) { return contextMenuExtensions[handlerKey].action; }; /** * @param {module:contextmenu.MenuItem} menuItem * @returns {void} */ var injectExtendedContextMenuItemIntoDom = function injectExtendedContextMenuItemIntoDom(menuItem) { if (!Object.keys(contextMenuExtensions).length) { // all menuItems appear at the bottom of the menu in their own container. // if this is the first extension menu we need to add the separator. $$2('#cmenu_canvas').append("<li class='separator'>"); } var shortcut = menuItem.shortcut || ''; $$2('#cmenu_canvas').append("<li class='disabled'><a href='#" + menuItem.id + "'>" + menuItem.label + "<span class='shortcut'>" + shortcut + '</span></a></li>'); }; /** * @function module:contextmenu.injectExtendedContextMenuItemsIntoDom * @returns {void} */ var injectExtendedContextMenuItemsIntoDom = function injectExtendedContextMenuItemsIntoDom() { Object.values(contextMenuExtensions).forEach(function (menuItem) { injectExtendedContextMenuItemIntoDom(menuItem); }); }; /** * Created by alexey2baranov on 28.01.17. */ /* An extraction of the deparam method from Ben Alman's jQuery BBQ http://benalman.com/projects/jquery-bbq-plugin/ */ var coerce_types = { 'true': !0, 'false': !1, 'null': null }; function deparam(params, coerce) { // console.log(params) var obj = {}; // Iterate over all name=value pairs. params.replace(/\+/g, ' ').split('&').forEach(function (v) { var param = v.split('='); var key = decodeURIComponent(param[0]), // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it // into its component parts. keys = key.split(']['), keys_last = keys.length - 1; // If the first keys part contains [ and the last ends with ], then [] // are correctly balanced. if (/\[/.test(keys[0]) && /\]$/.test(keys[keys_last])) { // Remove the trailing ] from the last keys part. keys[keys_last] = keys[keys_last].replace(/\]$/, ''); // Split first keys part into two parts on the [ and add them back onto // the beginning of the keys array. keys = keys.shift().split('[').concat(keys); keys_last = keys.length - 1; } else { // Basic 'foo' style key. keys_last = 0; } // Are we dealing with a name=value pair, or just a name? if (param.length >= 2) { var val = decodeURIComponent(param.slice(1).join('=')); // Coerce values. if (coerce) { val = val && !isNaN(val) ? +val // number : val === 'undefined' ? undefined // undefined : coerce_types[val] !== undefined ? coerce_types[val] // true, false, null : val; // string } if (keys_last) { var cur = obj; // Complex key, build deep object structure based on a few rules: // * The 'cur' pointer starts at the object top-level. // * [] = array push (n is set to array length), [n] = array if n is // numeric, otherwise object. // * If at the last keys part, set the value. // * For each keys part, if the current level is undefined create an // object or array based on the type of the next keys part. // * Move the 'cur' pointer to the next level. // * Rinse & repeat. for (var i = 0; i <= keys_last; i++) { key = keys[i] === '' ? cur.length : keys[i]; cur = cur[key] = i < keys_last ? cur[key] || (keys[i + 1] && isNaN(keys[i + 1]) ? {} : []) : val; } } else { // Simple key, even simpler rules, since only scalars and shallow // arrays are allowed. if (Array.isArray(obj[key])) { // val is already an array, so push on the next value. obj[key].push(val); } else if (obj[key] !== undefined) { // val isn't an array, but since a second value has been specified, // convert val into an array. obj[key] = [obj[key], val]; } else { // val is a scalar. obj[key] = val; } } } else if (key) { // No value was defined, so set something meaningful. obj[key] = coerce ? undefined : ''; } }); return obj; } var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; /** @license * * jsPDF - PDF Document creation from JavaScript * Version 2.1.0 Built on 2020-08-25T16:02:38.141Z * CommitID 00000000 * * Copyright (c) 2010-2020 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF * 2015-2020 yWorks GmbH, http://www.yworks.com * 2015-2020 Lukas Holländer <lukas.hollaender@yworks.com>, https://github.com/HackbrettXXX * 2016-2018 Aras Abbasi <aras.abbasi@gmail.com> * 2010 Aaron Spike, https://github.com/acspike * 2012 Willow Systems Corporation, willow-systems.com * 2012 Pablo Hess, https://github.com/pablohess * 2012 Florian Jenett, https://github.com/fjenett * 2013 Warren Weckesser, https://github.com/warrenweckesser * 2013 Youssef Beddad, https://github.com/lifof * 2013 Lee Driscoll, https://github.com/lsdriscoll * 2013 Stefan Slonevskiy, https://github.com/stefslon * 2013 Jeremy Morel, https://github.com/jmorel * 2013 Christoph Hartmann, https://github.com/chris-rock * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria * 2014 James Makes, https://github.com/dollaruw * 2014 Diego Casorran, https://github.com/diegocr * 2014 Steven Spungin, https://github.com/Flamenco * 2014 Kenneth Glassey, https://github.com/Gavvers * * 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. * * Contributor(s): * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango, * kim3er, mfo, alnorth, Flamenco */ var t = function () { return "undefined" != typeof window ? window : "undefined" != typeof global$1 ? global$1 : "undefined" != typeof self ? self : this; }(); function e() { t.console && "function" == typeof t.console.log && t.console.log.apply(t.console, arguments); } var n = { log: e, warn: function warn(n) { t.console && ("function" == typeof t.console.warn ? t.console.warn.apply(t.console, arguments) : e.call(null, arguments)); }, error: function error(n) { t.console && ("function" == typeof t.console.error ? t.console.error.apply(t.console, arguments) : e(n)); } }; /** * @license * FileSaver.js * A saveAs() FileSaver implementation. * * By Eli Grey, http://eligrey.com * * License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT) * source : http://purl.eligrey.com/github/FileSaver.js */ function r(t, e, r) { var i = new XMLHttpRequest(); i.open("GET", t), i.responseType = "blob", i.onload = function () { u(i.response, e, r); }, i.onerror = function () { n.error("could not download file"); }, i.send(); } function i(t) { var e = new XMLHttpRequest(); e.open("HEAD", t, !1); try { e.send(); } catch (t) {} return e.status >= 200 && e.status <= 299; } function a(t) { try { t.dispatchEvent(new MouseEvent("click")); } catch (n) { var e = document.createEvent("MouseEvents"); e.initMouseEvent("click", !0, !0, window, 0, 0, 0, 80, 20, !1, !1, !1, !1, 0, null), t.dispatchEvent(e); } } var o, s, u = t.saveAs || ("object" != (typeof window === "undefined" ? "undefined" : _typeof(window)) || window !== t ? function () {} : "download" in HTMLAnchorElement.prototype ? function (e, n, o) { var s = t.URL || t.webkitURL, u = document.createElement("a"); n = n || e.name || "download", u.download = n, u.rel = "noopener", "string" == typeof e ? (u.href = e, u.origin !== location.origin ? i(u.href) ? r(e, n, o) : a(u, u.target = "_blank") : a(u)) : (u.href = s.createObjectURL(e), setTimeout(function () { s.revokeObjectURL(u.href); }, 4e4), setTimeout(function () { a(u); }, 0)); } : "msSaveOrOpenBlob" in navigator ? function (t, e, o) { if (e = e || t.name || "download", "string" == typeof t) { if (i(t)) r(t, e, o);else { var s = document.createElement("a"); s.href = t, s.target = "_blank", setTimeout(function () { a(s); }); } } else navigator.msSaveOrOpenBlob(function (t, e) { return void 0 === e ? e = { autoBom: !1 } : "object" != _typeof(e) && (n.warn("Deprecated: Expected third argument to be a object"), e = { autoBom: !e }), e.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type) ? new Blob([String.fromCharCode(65279), t], { type: t.type }) : t; }(t, o), e); } : function (e, n, i, a) { if ((a = a || open("", "_blank")) && (a.document.title = a.document.body.innerText = "downloading..."), "string" == typeof e) return r(e, n, i); var o = "application/octet-stream" === e.type, s = /constructor/i.test(t.HTMLElement) || t.safari, u = /CriOS\/[\d]+/.test(navigator.userAgent); if ((u || o && s) && "object" == (typeof FileReader === "undefined" ? "undefined" : _typeof(FileReader))) { var c = new FileReader(); c.onloadend = function () { var t = c.result; t = u ? t : t.replace(/^data:[^;]*;/, "data:attachment/file;"), a ? a.location.href = t : location = t, a = null; }, c.readAsDataURL(e); } else { var h = t.URL || t.webkitURL, l = h.createObjectURL(e); a ? a.location = l : location.href = l, a = null, setTimeout(function () { h.revokeObjectURL(l); }, 4e4); } }); /** * A class to parse color values * @author Stoyan Stefanov <sstoo@gmail.com> * {@link http://www.phpied.com/rgb-color-parser-in-javascript/} * @license Use it if you like it */ function c(t) { var e; t = t || "", this.ok = !1, "#" == t.charAt(0) && (t = t.substr(1, 6)); t = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "00ffff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000000", blanchedalmond: "ffebcd", blue: "0000ff", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "00ffff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dodgerblue: "1e90ff", feldspar: "d19275", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "ff00ff", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgrey: "d3d3d3", lightgreen: "90ee90", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslateblue: "8470ff", lightslategray: "778899", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "00ff00", limegreen: "32cd32", linen: "faf0e6", magenta: "ff00ff", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370d8", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "d87093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", red: "ff0000", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", violetred: "d02090", wheat: "f5deb3", white: "ffffff", whitesmoke: "f5f5f5", yellow: "ffff00", yellowgreen: "9acd32" }[t = (t = t.replace(/ /g, "")).toLowerCase()] || t; for (var n = [{ re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, example: ["rgb(123, 234, 45)", "rgb(255,234,245)"], process: function process(t) { return [parseInt(t[1]), parseInt(t[2]), parseInt(t[3])]; } }, { re: /^(\w{2})(\w{2})(\w{2})$/, example: ["#00ff00", "336699"], process: function process(t) { return [parseInt(t[1], 16), parseInt(t[2], 16), parseInt(t[3], 16)]; } }, { re: /^(\w{1})(\w{1})(\w{1})$/, example: ["#fb0", "f0f"], process: function process(t) { return [parseInt(t[1] + t[1], 16), parseInt(t[2] + t[2], 16), parseInt(t[3] + t[3], 16)]; } }], r = 0; r < n.length; r++) { var i = n[r].re, a = n[r].process, o = i.exec(t); o && (e = a(o), this.r = e[0], this.g = e[1], this.b = e[2], this.ok = !0); } this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r, this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g, this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b, this.toRGB = function () { return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")"; }, this.toHex = function () { var t = this.r.toString(16), e = this.g.toString(16), n = this.b.toString(16); return 1 == t.length && (t = "0" + t), 1 == e.length && (e = "0" + e), 1 == n.length && (n = "0" + n), "#" + t + e + n; }; } function h(e) { if ("object" != _typeof(e)) throw new Error("Invalid Context passed to initialize PubSub (jsPDF-module)"); var r = {}; this.subscribe = function (t, e, n) { if (n = n || !1, "string" != typeof t || "function" != typeof e || "boolean" != typeof n) throw new Error("Invalid arguments passed to PubSub.subscribe (jsPDF-module)"); r.hasOwnProperty(t) || (r[t] = {}); var i = Math.random().toString(35); return r[t][i] = [e, !!n], i; }, this.unsubscribe = function (t) { for (var e in r) { if (r[e][t]) return delete r[e][t], 0 === Object.keys(r[e]).length && delete r[e], !0; } return !1; }, this.publish = function (i) { if (r.hasOwnProperty(i)) { var a = Array.prototype.slice.call(arguments, 1), o = []; for (var s in r[i]) { var u = r[i][s]; try { u[0].apply(e, a); } catch (e) { t.console && n.error("jsPDF PubSub Error", e.message, e); } u[1] && o.push(s); } o.length && o.forEach(this.unsubscribe); } }, this.getTopics = function () { return r; }; } function l(t) { if (!(this instanceof l)) return new l(t); var e = "opacity,stroke-opacity".split(","); for (var n in t) { t.hasOwnProperty(n) && e.indexOf(n) >= 0 && (this[n] = t[n]); } this.id = "", this.objectNumber = -1; } function f$8(t, e) { this.gState = t, this.matrix = e, this.id = "", this.objectNumber = -1; } function d(t, e, n, r, i) { if (!(this instanceof d)) return new d(t, e, n, r, i); this.type = "axial" === t ? 2 : 3, this.coords = e, this.colors = n, f$8.call(this, r, i); } function p(t, e, n, r, i) { if (!(this instanceof p)) return new p(t, e, n, r, i); this.boundingBox = t, this.xStep = e, this.yStep = n, this.stream = "", this.cloneIndex = 0, f$8.call(this, r, i); } function g(e) { var r, i = "string" == typeof arguments[0] ? arguments[0] : "p", a = arguments[1], o = arguments[2], f = arguments[3], m = [], v = 1, b = 16, y = "S"; "object" == _typeof(e = e || {}) && (i = e.orientation, a = e.unit || a, o = e.format || o, f = e.compress || e.compressPdf || f, v = "number" == typeof e.userUnit ? Math.abs(e.userUnit) : 1, void 0 !== e.precision && (r = e.precision), void 0 !== e.floatPrecision && (b = e.floatPrecision), y = e.defaultPathOperation || "S"), m = e.filters || (!0 === f ? ["FlateEncode"] : m), a = a || "mm", i = ("" + (i || "P")).toLowerCase(); var w = e.putOnlyUsedFonts || !1, N = {}, L = { internal: {}, __private__: {} }; L.__private__.PubSub = h; var x = "1.3", A = L.__private__.getPdfVersion = function () { return x; }; L.__private__.setPdfVersion = function (t) { x = t; }; var _ = { a0: [2383.94, 3370.39], a1: [1683.78, 2383.94], a2: [1190.55, 1683.78], a3: [841.89, 1190.55], a4: [595.28, 841.89], a5: [419.53, 595.28], a6: [297.64, 419.53], a7: [209.76, 297.64], a8: [147.4, 209.76], a9: [104.88, 147.4], a10: [73.7, 104.88], b0: [2834.65, 4008.19], b1: [2004.09, 2834.65], b2: [1417.32, 2004.09], b3: [1000.63, 1417.32], b4: [708.66, 1000.63], b5: [498.9, 708.66], b6: [354.33, 498.9], b7: [249.45, 354.33], b8: [175.75, 249.45], b9: [124.72, 175.75], b10: [87.87, 124.72], c0: [2599.37, 3676.54], c1: [1836.85, 2599.37], c2: [1298.27, 1836.85], c3: [918.43, 1298.27], c4: [649.13, 918.43], c5: [459.21, 649.13], c6: [323.15, 459.21], c7: [229.61, 323.15], c8: [161.57, 229.61], c9: [113.39, 161.57], c10: [79.37, 113.39], dl: [311.81, 623.62], letter: [612, 792], "government-letter": [576, 756], legal: [612, 1008], "junior-legal": [576, 360], ledger: [1224, 792], tabloid: [792, 1224], "credit-card": [153, 243] }; L.__private__.getPageFormats = function () { return _; }; var S = L.__private__.getPageFormat = function (t) { return _[t]; }; o = o || "a4"; var P = { COMPAT: "compat", ADVANCED: "advanced" }, k = P.COMPAT; function F() { this.saveGraphicsState(), ot(new Dt(Nt, 0, 0, -Nt, 0, Cn() * Nt).toString() + " cm"), this.setFontSize(this.getFontSize() / Nt), y = "n", k = P.ADVANCED; } function I() { this.restoreGraphicsState(), y = "S", k = P.COMPAT; } L.advancedAPI = function (t) { var e = k === P.COMPAT; return e && F.call(this), "function" != typeof t || (t(this), e && I.call(this)), this; }, L.compatAPI = function (t) { var e = k === P.ADVANCED; return e && I.call(this), "function" != typeof t || (t(this), e && F.call(this)), this; }, L.isAdvancedAPI = function () { return k === P.ADVANCED; }; var C, j = function j(t) { if (k !== P.ADVANCED) throw new Error(t + " is only available in 'advanced' API mode. You need to call advancedAPI() first."); }, B = L.roundToPrecision = L.__private__.roundToPrecision = function (t, e) { var n = r || e; if (isNaN(t) || isNaN(n)) throw new Error("Invalid argument passed to jsPDF.roundToPrecision"); return t.toFixed(n).replace(/0+$/, ""); }; C = L.hpf = L.__private__.hpf = "number" == typeof b ? function (t) { if (isNaN(t)) throw new Error("Invalid argument passed to jsPDF.hpf"); return B(t, b); } : "smart" === b ? function (t) { if (isNaN(t)) throw new Error("Invalid argument passed to jsPDF.hpf"); return B(t, t > -1 && t < 1 ? 16 : 5); } : function (t) { if (isNaN(t)) throw new Error("Invalid argument passed to jsPDF.hpf"); return B(t, 16); }; var O = L.f2 = L.__private__.f2 = function (t) { if (isNaN(t)) throw new Error("Invalid argument passed to jsPDF.f2"); return B(t, 2); }, M = L.__private__.f3 = function (t) { if (isNaN(t)) throw new Error("Invalid argument passed to jsPDF.f3"); return B(t, 3); }, E = L.scale = L.__private__.scale = function (t) { if (isNaN(t)) throw new Error("Invalid argument passed to jsPDF.scale"); return k === P.COMPAT ? t * Nt : k === P.ADVANCED ? t : void 0; }, q = function q(t) { return k === P.COMPAT ? Cn() - t : k === P.ADVANCED ? t : void 0; }, R = function R(t) { return E(q(t)); }; L.__private__.setPrecision = L.setPrecision = function (t) { "number" == typeof parseInt(t, 10) && (r = parseInt(t, 10)); }; var T, D = "00000000000000000000000000000000", U = L.__private__.getFileId = function () { return D; }, z = L.__private__.setFileId = function (t) { return D = void 0 !== t && /^[a-fA-F0-9]{32}$/.test(t) ? t.toUpperCase() : D.split("").map(function () { return "ABCDEF0123456789".charAt(Math.floor(16 * Math.random())); }).join(""); }; L.setFileId = function (t) { return z(t), this; }, L.getFileId = function () { return U(); }; var H = L.__private__.convertDateToPDFDate = function (t) { var e = t.getTimezoneOffset(), n = e < 0 ? "+" : "-", r = Math.floor(Math.abs(e / 60)), i = Math.abs(e % 60), a = [n, J(r), "'", J(i), "'"].join(""); return ["D:", t.getFullYear(), J(t.getMonth() + 1), J(t.getDate()), J(t.getHours()), J(t.getMinutes()), J(t.getSeconds()), a].join(""); }, W = L.__private__.convertPDFDateToDate = function (t) { var e = parseInt(t.substr(2, 4), 10), n = parseInt(t.substr(6, 2), 10) - 1, r = parseInt(t.substr(8, 2), 10), i = parseInt(t.substr(10, 2), 10), a = parseInt(t.substr(12, 2), 10), o = parseInt(t.substr(14, 2), 10); return new Date(e, n, r, i, a, o, 0); }, V = L.__private__.setCreationDate = function (t) { var e; if (void 0 === t && (t = new Date()), t instanceof Date) e = H(t);else { if (!/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/.test(t)) throw new Error("Invalid argument passed to jsPDF.setCreationDate"); e = t; } return T = e; }, G = L.__private__.getCreationDate = function (t) { var e = T; return "jsDate" === t && (e = W(T)), e; }; L.setCreationDate = function (t) { return V(t), this; }, L.getCreationDate = function (t) { return G(t); }; var Y, J = L.__private__.padd2 = function (t) { return ("0" + parseInt(t)).slice(-2); }, X = L.__private__.padd2Hex = function (t) { return ("00" + (t = t.toString())).substr(t.length); }, K = 0, Z = [], $ = [], Q = 0, tt = [], et = [], nt = !1, rt = $, it = function it() { K = 0, Q = 0, $ = [], Z = [], tt = [], Jt = Vt(), Xt = Vt(); }; L.__private__.setCustomOutputDestination = function (t) { nt = !0, rt = t; }; var at = function at(t) { nt || (rt = t); }; L.__private__.resetCustomOutputDestination = function () { nt = !1, rt = $; }; var ot = L.__private__.out = function (t) { return t = t.toString(), Q += t.length + 1, rt.push(t), rt; }, st = L.__private__.write = function (t) { return ot(1 === arguments.length ? t.toString() : Array.prototype.join.call(arguments, " ")); }, ut = L.__private__.getArrayBuffer = function (t) { for (var e = t.length, n = new ArrayBuffer(e), r = new Uint8Array(n); e--;) { r[e] = t.charCodeAt(e); } return n; }, ct = [["Helvetica", "helvetica", "normal", "WinAnsiEncoding"], ["Helvetica-Bold", "helvetica", "bold", "WinAnsiEncoding"], ["Helvetica-Oblique", "helvetica", "italic", "WinAnsiEncoding"], ["Helvetica-BoldOblique", "helvetica", "bolditalic", "WinAnsiEncoding"], ["Courier", "courier", "normal", "WinAnsiEncoding"], ["Courier-Bold", "courier", "bold", "WinAnsiEncoding"], ["Courier-Oblique", "courier", "italic", "WinAnsiEncoding"], ["Courier-BoldOblique", "courier", "bolditalic", "WinAnsiEncoding"], ["Times-Roman", "times", "normal", "WinAnsiEncoding"], ["Times-Bold", "times", "bold", "WinAnsiEncoding"], ["Times-Italic", "times", "italic", "WinAnsiEncoding"], ["Times-BoldItalic", "times", "bolditalic", "WinAnsiEncoding"], ["ZapfDingbats", "zapfdingbats", "normal", null], ["Symbol", "symbol", "normal", null]]; L.__private__.getStandardFonts = function () { return ct; }; var ht = e.fontSize || 16; L.__private__.setFontSize = L.setFontSize = function (t) { return ht = k === P.ADVANCED ? t / Nt : t, this; }; var lt, ft = L.__private__.getFontSize = L.getFontSize = function () { return k === P.COMPAT ? ht : ht * Nt; }, dt = e.R2L || !1; L.__private__.setR2L = L.setR2L = function (t) { return dt = t, this; }, L.__private__.getR2L = L.getR2L = function () { return dt; }; var pt, gt = L.__private__.setZoomMode = function (t) { var e = [void 0, null, "fullwidth", "fullheight", "fullpage", "original"]; if (/^\d*\.?\d*%$/.test(t)) lt = t;else if (isNaN(t)) { if (-1 === e.indexOf(t)) throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "' + t + '" is not recognized.'); lt = t; } else lt = parseInt(t, 10); }; L.__private__.getZoomMode = function () { return lt; }; var mt, vt = L.__private__.setPageMode = function (t) { if (-1 == [void 0, null, "UseNone", "UseOutlines", "UseThumbs", "FullScreen"].indexOf(t)) throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + t + '" is not recognized.'); pt = t; }; L.__private__.getPageMode = function () { return pt; }; var bt = L.__private__.setLayoutMode = function (t) { if (-1 == [void 0, null, "continuous", "single", "twoleft", "tworight", "two"].indexOf(t)) throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "' + t + '" is not recognized.'); mt = t; }; L.__private__.getLayoutMode = function () { return mt; }, L.__private__.setDisplayMode = L.setDisplayMode = function (t, e, n) { return gt(t), bt(e), vt(n), this; }; var yt = { title: "", subject: "", author: "", keywords: "", creator: "" }; L.__private__.getDocumentProperty = function (t) { if (-1 === Object.keys(yt).indexOf(t)) throw new Error("Invalid argument passed to jsPDF.getDocumentProperty"); return yt[t]; }, L.__private__.getDocumentProperties = function () { return yt; }, L.__private__.setDocumentProperties = L.setProperties = L.setDocumentProperties = function (t) { for (var e in yt) { yt.hasOwnProperty(e) && t[e] && (yt[e] = t[e]); } return this; }, L.__private__.setDocumentProperty = function (t, e) { if (-1 === Object.keys(yt).indexOf(t)) throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty"); return yt[t] = e; }; var wt, Nt, Lt, xt, At, _t = {}, St = {}, Pt = [], kt = {}, Ft = {}, It = {}, Ct = {}, jt = null, Bt = 0, Ot = [], Mt = new h(L), Et = e.hotfixes || [], qt = {}, Rt = {}, Tt = [], Dt = function Dt(t, e, n, r, i, a) { if (!(this instanceof Dt)) return new Dt(t, e, n, r, i, a); isNaN(t) && (t = 1), isNaN(e) && (e = 0), isNaN(n) && (n = 0), isNaN(r) && (r = 1), isNaN(i) && (i = 0), isNaN(a) && (a = 0), this._matrix = [t, e, n, r, i, a]; }; Object.defineProperty(Dt.prototype, "sx", { get: function get() { return this._matrix[0]; }, set: function set(t) { this._matrix[0] = t; } }), Object.defineProperty(Dt.prototype, "shy", { get: function get() { return this._matrix[1]; }, set: function set(t) { this._matrix[1] = t; } }), Object.defineProperty(Dt.prototype, "shx", { get: function get() { return this._matrix[2]; }, set: function set(t) { this._matrix[2] = t; } }), Object.defineProperty(Dt.prototype, "sy", { get: function get() { return this._matrix[3]; }, set: function set(t) { this._matrix[3] = t; } }), Object.defineProperty(Dt.prototype, "tx", { get: function get() { return this._matrix[4]; }, set: function set(t) { this._matrix[4] = t; } }), Object.defineProperty(Dt.prototype, "ty", { get: function get() { return this._matrix[5]; }, set: function set(t) { this._matrix[5] = t; } }), Object.defineProperty(Dt.prototype, "a", { get: function get() { return this._matrix[0]; }, set: function set(t) { this._matrix[0] = t; } }), Object.defineProperty(Dt.prototype, "b", { get: function get() { return this._matrix[1]; }, set: function set(t) { this._matrix[1] = t; } }), Object.defineProperty(Dt.prototype, "c", { get: function get() { return this._matrix[2]; }, set: function set(t) { this._matrix[2] = t; } }), Object.defineProperty(Dt.prototype, "d", { get: function get() { return this._matrix[3]; }, set: function set(t) { this._matrix[3] = t; } }), Object.defineProperty(Dt.prototype, "e", { get: function get() { return this._matrix[4]; }, set: function set(t) { this._matrix[4] = t; } }), Object.defineProperty(Dt.prototype, "f", { get: function get() { return this._matrix[5]; }, set: function set(t) { this._matrix[5] = t; } }), Object.defineProperty(Dt.prototype, "rotation", { get: function get() { return Math.atan2(this.shx, this.sx); } }), Object.defineProperty(Dt.prototype, "scaleX", { get: function get() { return this.decompose().scale.sx; } }), Object.defineProperty(Dt.prototype, "scaleY", { get: function get() { return this.decompose().scale.sy; } }), Object.defineProperty(Dt.prototype, "isIdentity", { get: function get() { return 1 === this.sx && 0 === this.shy && 0 === this.shx && 1 === this.sy && 0 === this.tx && 0 === this.ty; } }), Dt.prototype.join = function (t) { return [this.sx, this.shy, this.shx, this.sy, this.tx, this.ty].map(C).join(t); }, Dt.prototype.multiply = function (t) { var e = t.sx * this.sx + t.shy * this.shx, n = t.sx * this.shy + t.shy * this.sy, r = t.shx * this.sx + t.sy * this.shx, i = t.shx * this.shy + t.sy * this.sy, a = t.tx * this.sx + t.ty * this.shx + this.tx, o = t.tx * this.shy + t.ty * this.sy + this.ty; return new Dt(e, n, r, i, a, o); }, Dt.prototype.decompose = function () { var t = this.sx, e = this.shy, n = this.shx, r = this.sy, i = this.tx, a = this.ty, o = Math.sqrt(t * t + e * e), s = (t /= o) * n + (e /= o) * r; n -= t * s, r -= e * s; var u = Math.sqrt(n * n + r * r); return s /= u, t * (r /= u) < e * (n /= u) && (t = -t, e = -e, s = -s, o = -o), { scale: new Dt(o, 0, 0, u, 0, 0), translate: new Dt(1, 0, 0, 1, i, a), rotate: new Dt(t, e, -e, t, 0, 0), skew: new Dt(1, 0, s, 1, 0, 0) }; }, Dt.prototype.toString = function (t) { return this.join(" "); }, Dt.prototype.inversed = function () { var t = this.sx, e = this.shy, n = this.shx, r = this.sy, i = this.tx, a = this.ty, o = 1 / (t * r - e * n), s = r * o, u = -e * o, c = -n * o, h = t * o; return new Dt(s, u, c, h, -s * i - c * a, -u * i - h * a); }, Dt.prototype.applyToPoint = function (t) { var e = t.x * this.sx + t.y * this.shx + this.tx, n = t.x * this.shy + t.y * this.sy + this.ty; return new xn(e, n); }, Dt.prototype.applyToRectangle = function (t) { var e = this.applyToPoint(t), n = this.applyToPoint(new xn(t.x + t.w, t.y + t.h)); return new An(e.x, e.y, n.x - e.x, n.y - e.y); }, Dt.prototype.clone = function () { var t = this.sx, e = this.shy, n = this.shx, r = this.sy, i = this.tx, a = this.ty; return new Dt(t, e, n, r, i, a); }, L.Matrix = Dt; var Ut = L.matrixMult = function (t, e) { return e.multiply(t); }, zt = new Dt(1, 0, 0, 1, 0, 0); L.unitMatrix = L.identityMatrix = zt; var Ht = function Ht(t, e) { if (!Ft[t]) { var n = (e instanceof d ? "Sh" : "P") + (Object.keys(kt).length + 1).toString(10); e.id = n, Ft[t] = n, kt[n] = e, Mt.publish("addPattern", e); } }; L.ShadingPattern = d, L.TilingPattern = p, L.addShadingPattern = function (t, e) { return j("addShadingPattern()"), Ht(t, e), this; }, L.beginTilingPattern = function (t) { j("beginTilingPattern()"), Sn(t.boundingBox[0], t.boundingBox[1], t.boundingBox[2] - t.boundingBox[0], t.boundingBox[3] - t.boundingBox[1], t.matrix); }, L.endTilingPattern = function (t, e) { j("endTilingPattern()"), e.stream = et[Y].join("\n"), Ht(t, e), Mt.publish("endTilingPattern", e), Tt.pop().restore(); }; var Wt = L.__private__.newObject = function () { var t = Vt(); return Gt(t, !0), t; }, Vt = L.__private__.newObjectDeferred = function () { return K++, Z[K] = function () { return Q; }, K; }, Gt = function Gt(t, e) { return e = "boolean" == typeof e && e, Z[t] = Q, e && ot(t + " 0 obj"), t; }, Yt = L.__private__.newAdditionalObject = function () { var t = { objId: Vt(), content: "" }; return tt.push(t), t; }, Jt = Vt(), Xt = Vt(), Kt = L.__private__.decodeColorString = function (t) { var e = t.split(" "); if (2 !== e.length || "g" !== e[1] && "G" !== e[1]) { if (5 === e.length && ("k" === e[4] || "K" === e[4])) { e = [(1 - e[0]) * (1 - e[3]), (1 - e[1]) * (1 - e[3]), (1 - e[2]) * (1 - e[3]), "r"]; } } else { var n = parseFloat(e[0]); e = [n, n, n, "r"]; } for (var r = "#", i = 0; i < 3; i++) { r += ("0" + Math.floor(255 * parseFloat(e[i])).toString(16)).slice(-2); } return r; }, Zt = L.__private__.encodeColorString = function (t) { var e; "string" == typeof t && (t = { ch1: t }); var n = t.ch1, r = t.ch2, i = t.ch3, a = t.ch4, o = "draw" === t.pdfColorType ? ["G", "RG", "K"] : ["g", "rg", "k"]; if ("string" == typeof n && "#" !== n.charAt(0)) { var s = new c(n); if (s.ok) n = s.toHex();else if (!/^\d*\.?\d*$/.test(n)) throw new Error('Invalid color "' + n + '" passed to jsPDF.encodeColorString.'); } if ("string" == typeof n && /^#[0-9A-Fa-f]{3}$/.test(n) && (n = "#" + n[1] + n[1] + n[2] + n[2] + n[3] + n[3]), "string" == typeof n && /^#[0-9A-Fa-f]{6}$/.test(n)) { var u = parseInt(n.substr(1), 16); n = u >> 16 & 255, r = u >> 8 & 255, i = 255 & u; } if (void 0 === r || void 0 === a && n === r && r === i) { if ("string" == typeof n) e = n + " " + o[0];else switch (t.precision) { case 2: e = O(n / 255) + " " + o[0]; break; case 3: default: e = M(n / 255) + " " + o[0]; } } else if (void 0 === a || "object" == _typeof(a)) { if (a && !isNaN(a.a) && 0 === a.a) return e = ["1.", "1.", "1.", o[1]].join(" "); if ("string" == typeof n) e = [n, r, i, o[1]].join(" ");else switch (t.precision) { case 2: e = [O(n / 255), O(r / 255), O(i / 255), o[1]].join(" "); break; default: case 3: e = [M(n / 255), M(r / 255), M(i / 255), o[1]].join(" "); } } else if ("string" == typeof n) e = [n, r, i, a, o[2]].join(" ");else switch (t.precision) { case 2: e = [O(n), O(r), O(i), O(a), o[2]].join(" "); break; case 3: default: e = [M(n), M(r), M(i), M(a), o[2]].join(" "); } return e; }, $t = L.__private__.getFilters = function () { return m; }, Qt = L.__private__.putStream = function (t) { var e = (t = t || {}).data || "", n = t.filters || $t(), r = t.alreadyAppliedFilters || [], i = t.addLength1 || !1, a = e.length, o = {}; !0 === n && (n = ["FlateEncode"]); var s = t.additionalKeyValues || [], u = (o = void 0 !== g.API.processDataByFilters ? g.API.processDataByFilters(e, n) : { data: e, reverseChain: [] }).reverseChain + (Array.isArray(r) ? r.join(" ") : r.toString()); if (0 !== o.data.length && (s.push({ key: "Length", value: o.data.length }), !0 === i && s.push({ key: "Length1", value: a })), 0 != u.length) if (u.split("/").length - 1 == 1) s.push({ key: "Filter", value: u });else { s.push({ key: "Filter", value: "[" + u + "]" }); for (var c = 0; c < s.length; c += 1) { if ("DecodeParms" === s[c].key) { for (var h = [], l = 0; l < o.reverseChain.split("/").length - 1; l += 1) { h.push("null"); } h.push(s[c].value), s[c].value = "[" + h.join(" ") + "]"; } } } ot("<<"); for (var f = 0; f < s.length; f++) { ot("/" + s[f].key + " " + s[f].value); } ot(">>"), 0 !== o.data.length && (ot("stream"), ot(o.data), ot("endstream")); }, te = L.__private__.putPage = function (t) { var e = t.number, n = t.data, r = t.objId, i = t.contentsObjId; Gt(r, !0), ot("<</Type /Page"), ot("/Parent " + t.rootDictionaryObjId + " 0 R"), ot("/Resources " + t.resourceDictionaryObjId + " 0 R"), ot("/MediaBox [" + parseFloat(C(t.mediaBox.bottomLeftX)) + " " + parseFloat(C(t.mediaBox.bottomLeftY)) + " " + C(t.mediaBox.topRightX) + " " + C(t.mediaBox.topRightY) + "]"), null !== t.cropBox && ot("/CropBox [" + C(t.cropBox.bottomLeftX) + " " + C(t.cropBox.bottomLeftY) + " " + C(t.cropBox.topRightX) + " " + C(t.cropBox.topRightY) + "]"), null !== t.bleedBox && ot("/BleedBox [" + C(t.bleedBox.bottomLeftX) + " " + C(t.bleedBox.bottomLeftY) + " " + C(t.bleedBox.topRightX) + " " + C(t.bleedBox.topRightY) + "]"), null !== t.trimBox && ot("/TrimBox [" + C(t.trimBox.bottomLeftX) + " " + C(t.trimBox.bottomLeftY) + " " + C(t.trimBox.topRightX) + " " + C(t.trimBox.topRightY) + "]"), null !== t.artBox && ot("/ArtBox [" + C(t.artBox.bottomLeftX) + " " + C(t.artBox.bottomLeftY) + " " + C(t.artBox.topRightX) + " " + C(t.artBox.topRightY) + "]"), "number" == typeof t.userUnit && 1 !== t.userUnit && ot("/UserUnit " + t.userUnit), Mt.publish("putPage", { objId: r, pageContext: Ot[e], pageNumber: e, page: n }), ot("/Contents " + i + " 0 R"), ot(">>"), ot("endobj"); var a = n.join("\n"); return k === P.ADVANCED && (a += "\nQ"), Gt(i, !0), Qt({ data: a, filters: $t() }), ot("endobj"), r; }, ee = L.__private__.putPages = function () { var t, e, n = []; for (t = 1; t <= Bt; t++) { Ot[t].objId = Vt(), Ot[t].contentsObjId = Vt(); } for (t = 1; t <= Bt; t++) { n.push(te({ number: t, data: et[t], objId: Ot[t].objId, contentsObjId: Ot[t].contentsObjId, mediaBox: Ot[t].mediaBox, cropBox: Ot[t].cropBox, bleedBox: Ot[t].bleedBox, trimBox: Ot[t].trimBox, artBox: Ot[t].artBox, userUnit: Ot[t].userUnit, rootDictionaryObjId: Jt, resourceDictionaryObjId: Xt })); } Gt(Jt, !0), ot("<</Type /Pages"); var r = "/Kids ["; for (e = 0; e < Bt; e++) { r += n[e] + " 0 R "; } ot(r + "]"), ot("/Count " + Bt), ot(">>"), ot("endobj"), Mt.publish("postPutPages"); }, ne = function ne(t) { var e = function e(t, _e2) { return -1 !== t.indexOf(" ") ? "(" + _e(t, _e2) + ")" : _e(t, _e2); }; Mt.publish("putFont", { font: t, out: ot, newObject: Wt, putStream: Qt, pdfEscapeWithNeededParanthesis: e }), !0 !== t.isAlreadyPutted && (t.objectNumber = Wt(), ot("<<"), ot("/Type /Font"), ot("/BaseFont /" + e(t.postScriptName)), ot("/Subtype /Type1"), "string" == typeof t.encoding && ot("/Encoding /" + t.encoding), ot("/FirstChar 32"), ot("/LastChar 255"), ot(">>"), ot("endobj")); }, re = function re() { for (var t in _t) { _t.hasOwnProperty(t) && (!1 === w || !0 === w && N.hasOwnProperty(t)) && ne(_t[t]); } }, ie = function ie(t) { t.objectNumber = Wt(); var e = []; e.push({ key: "Type", value: "/XObject" }), e.push({ key: "Subtype", value: "/Form" }), e.push({ key: "BBox", value: "[" + [C(t.x), C(t.y), C(t.x + t.width), C(t.y + t.height)].join(" ") + "]" }), e.push({ key: "Matrix", value: "[" + t.matrix.toString() + "]" }); var n = t.pages[1].join("\n"); Qt({ data: n, additionalKeyValues: e }), ot("endobj"); }, ae = function ae() { for (var t in qt) { qt.hasOwnProperty(t) && ie(qt[t]); } }, oe = function oe(t, e) { var n, r = [], i = 1 / (e - 1); for (n = 0; n < 1; n += i) { r.push(n); } if (r.push(1), 0 != t[0].offset) { var a = { offset: 0, color: t[0].color }; t.unshift(a); } if (1 != t[t.length - 1].offset) { var o = { offset: 1, color: t[t.length - 1].color }; t.push(o); } for (var s = "", u = 0, c = 0; c < r.length; c++) { for (n = r[c]; n > t[u + 1].offset;) { u++; } var h = t[u].offset, l = (n - h) / (t[u + 1].offset - h), f = t[u].color, d = t[u + 1].color; s += X(Math.round((1 - l) * f[0] + l * d[0]).toString(16)) + X(Math.round((1 - l) * f[1] + l * d[1]).toString(16)) + X(Math.round((1 - l) * f[2] + l * d[2]).toString(16)); } return s.trim(); }, se = function se(t, e) { e || (e = 21); var n = Wt(), r = oe(t.colors, e), i = []; i.push({ key: "FunctionType", value: "0" }), i.push({ key: "Domain", value: "[0.0 1.0]" }), i.push({ key: "Size", value: "[" + e + "]" }), i.push({ key: "BitsPerSample", value: "8" }), i.push({ key: "Range", value: "[0.0 1.0 0.0 1.0 0.0 1.0]" }), i.push({ key: "Decode", value: "[0.0 1.0 0.0 1.0 0.0 1.0]" }), Qt({ data: r, additionalKeyValues: i, alreadyAppliedFilters: ["/ASCIIHexDecode"] }), ot("endobj"), t.objectNumber = Wt(), ot("<< /ShadingType " + t.type), ot("/ColorSpace /DeviceRGB"); var a = "/Coords [" + C(parseFloat(t.coords[0])) + " " + C(parseFloat(t.coords[1])) + " "; 2 === t.type ? a += C(parseFloat(t.coords[2])) + " " + C(parseFloat(t.coords[3])) : a += C(parseFloat(t.coords[2])) + " " + C(parseFloat(t.coords[3])) + " " + C(parseFloat(t.coords[4])) + " " + C(parseFloat(t.coords[5])), ot(a += "]"), t.matrix && ot("/Matrix [" + t.matrix.toString() + "]"), ot("/Function " + n + " 0 R"), ot("/Extend [true true]"), ot(">>"), ot("endobj"); }, ue = function ue(t, e) { var n = Vt(), r = Wt(); e.push({ resourcesOid: n, objectOid: r }), t.objectNumber = r; var i = []; i.push({ key: "Type", value: "/Pattern" }), i.push({ key: "PatternType", value: "1" }), i.push({ key: "PaintType", value: "1" }), i.push({ key: "TilingType", value: "1" }), i.push({ key: "BBox", value: "[" + t.boundingBox.map(C).join(" ") + "]" }), i.push({ key: "XStep", value: C(t.xStep) }), i.push({ key: "YStep", value: C(t.yStep) }), i.push({ key: "Resources", value: n + " 0 R" }), t.matrix && i.push({ key: "Matrix", value: "[" + t.matrix.toString() + "]" }), Qt({ data: t.stream, additionalKeyValues: i }), ot("endobj"); }, ce = function ce(t) { var e; for (e in kt) { kt.hasOwnProperty(e) && (kt[e] instanceof d ? se(kt[e]) : kt[e] instanceof p && ue(kt[e], t)); } }, he = function he(t) { for (var e in t.objectNumber = Wt(), ot("<<"), t) { switch (e) { case "opacity": ot("/ca " + O(t[e])); break; case "stroke-opacity": ot("/CA " + O(t[e])); } } ot(">>"), ot("endobj"); }, le = function le() { var t; for (t in It) { It.hasOwnProperty(t) && he(It[t]); } }, fe = function fe() { for (var t in ot("/XObject <<"), qt) { qt.hasOwnProperty(t) && qt[t].objectNumber >= 0 && ot("/" + t + " " + qt[t].objectNumber + " 0 R"); } Mt.publish("putXobjectDict"), ot(">>"); }, de = function de() { for (var t in ot("/Font <<"), _t) { _t.hasOwnProperty(t) && (!1 === w || !0 === w && N.hasOwnProperty(t)) && ot("/" + t + " " + _t[t].objectNumber + " 0 R"); } ot(">>"); }, pe = function pe() { if (Object.keys(kt).length > 0) { for (var t in ot("/Shading <<"), kt) { kt.hasOwnProperty(t) && kt[t] instanceof d && kt[t].objectNumber >= 0 && ot("/" + t + " " + kt[t].objectNumber + " 0 R"); } Mt.publish("putShadingPatternDict"), ot(">>"); } }, ge = function ge(t) { if (Object.keys(kt).length > 0) { for (var e in ot("/Pattern <<"), kt) { kt.hasOwnProperty(e) && kt[e] instanceof L.TilingPattern && kt[e].objectNumber >= 0 && kt[e].objectNumber < t && ot("/" + e + " " + kt[e].objectNumber + " 0 R"); } Mt.publish("putTilingPatternDict"), ot(">>"); } }, me = function me() { if (Object.keys(It).length > 0) { var t; for (t in ot("/ExtGState <<"), It) { It.hasOwnProperty(t) && It[t].objectNumber >= 0 && ot("/" + t + " " + It[t].objectNumber + " 0 R"); } Mt.publish("putGStateDict"), ot(">>"); } }, ve = function ve(t) { Gt(t.resourcesOid, !0), ot("<<"), ot("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"), de(), pe(), ge(t.objectOid), me(), fe(), ot(">>"), ot("endobj"); }, be = function be() { var t = []; re(), le(), ae(), ce(t), Mt.publish("putResources"), t.forEach(ve), ve({ resourcesOid: Xt, objectOid: Number.MAX_SAFE_INTEGER }), Mt.publish("postPutResources"); }, ye = function ye() { Mt.publish("putAdditionalObjects"); for (var t = 0; t < tt.length; t++) { var e = tt[t]; Gt(e.objId, !0), ot(e.content), ot("endobj"); } Mt.publish("postPutAdditionalObjects"); }, we = function we(t) { St[t.fontName] = St[t.fontName] || {}, St[t.fontName][t.fontStyle] = t.id; }, Ne = function Ne(t, e, n, r, i) { var a = { id: "F" + (Object.keys(_t).length + 1).toString(10), postScriptName: t, fontName: e, fontStyle: n, encoding: r, isStandardFont: i || !1, metadata: {} }; return Mt.publish("addFont", { font: a, instance: this }), _t[a.id] = a, we(a), a.id; }, Le = function Le(t) { for (var e = 0, n = ct.length; e < n; e++) { var r = Ne.call(this, t[e][0], t[e][1], t[e][2], ct[e][3], !0); !1 === w && (N[r] = !0); var i = t[e][0].split("-"); we({ id: r, fontName: i[0], fontStyle: i[1] || "" }); } Mt.publish("addFonts", { fonts: _t, dictionary: St }); }, xe = function xe(e) { return e.foo = function () { try { return e.apply(this, arguments); } catch (e) { var n = e.stack || ""; ~n.indexOf(" at ") && (n = n.split(" at ")[1]); var r = "Error in function " + n.split("\n")[0].split("<")[0] + ": " + e.message; if (!t.console) throw new Error(r); t.console.error(r, e), t.alert && alert(r); } }, e.foo.bar = e, e.foo; }, Ae = function Ae(t, e) { var n, r, i, a, o, s, u, c, h; if (i = (e = e || {}).sourceEncoding || "Unicode", o = e.outputEncoding, (e.autoencode || o) && _t[wt].metadata && _t[wt].metadata[i] && _t[wt].metadata[i].encoding && (a = _t[wt].metadata[i].encoding, !o && _t[wt].encoding && (o = _t[wt].encoding), !o && a.codePages && (o = a.codePages[0]), "string" == typeof o && (o = a[o]), o)) { for (u = !1, s = [], n = 0, r = t.length; n < r; n++) { (c = o[t.charCodeAt(n)]) ? s.push(String.fromCharCode(c)) : s.push(t[n]), s[n].charCodeAt(0) >> 8 && (u = !0); } t = s.join(""); } for (n = t.length; void 0 === u && 0 !== n;) { t.charCodeAt(n - 1) >> 8 && (u = !0), n--; } if (!u) return t; for (s = e.noBOM ? [] : [254, 255], n = 0, r = t.length; n < r; n++) { if ((h = (c = t.charCodeAt(n)) >> 8) >> 8) throw new Error("Character at position " + n + " of string '" + t + "' exceeds 16bits. Cannot be encoded into UCS-2 BE"); s.push(h), s.push(c - (h << 8)); } return String.fromCharCode.apply(void 0, s); }, _e = L.__private__.pdfEscape = L.pdfEscape = function (t, e) { return Ae(t, e).replace(/\\/g, "\\\\").replace(/\(/g, "\\(").replace(/\)/g, "\\)"); }, Se = L.__private__.beginPage = function (t) { et[++Bt] = [], Ot[Bt] = { objId: 0, contentsObjId: 0, userUnit: Number(v), artBox: null, bleedBox: null, cropBox: null, trimBox: null, mediaBox: { bottomLeftX: 0, bottomLeftY: 0, topRightX: Number(t[0]), topRightY: Number(t[1]) } }, Fe(Bt), at(et[Y]); }, Pe = function Pe(t, e) { var r, a, s; switch (i = e || i, "string" == typeof t && (r = S(t.toLowerCase()), Array.isArray(r) && (a = r[0], s = r[1])), Array.isArray(t) && (a = t[0] * Nt, s = t[1] * Nt), isNaN(a) && (a = o[0], s = o[1]), (a > 14400 || s > 14400) && (n.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"), a = Math.min(14400, a), s = Math.min(14400, s)), o = [a, s], i.substr(0, 1)) { case "l": s > a && (o = [s, a]); break; case "p": a > s && (o = [s, a]); } Se(o), on(an), ot(pn), 0 !== wn && ot(wn + " J"), 0 !== Nn && ot(Nn + " j"), Mt.publish("addPage", { pageNumber: Bt }); }, ke = function ke(t) { t > 0 && t <= Bt && (et.splice(t, 1), Ot.splice(t, 1), Bt--, Y > Bt && (Y = Bt), this.setPage(Y)); }, Fe = function Fe(t) { t > 0 && t <= Bt && (Y = t); }, Ie = L.__private__.getNumberOfPages = L.getNumberOfPages = function () { return et.length - 1; }, Ce = function Ce(t, e, r) { var i, a = void 0; return r = r || {}, t = void 0 !== t ? t : _t[wt].fontName, e = void 0 !== e ? e : _t[wt].fontStyle, i = t.toLowerCase(), void 0 !== St[i] && void 0 !== St[i][e] ? a = St[i][e] : void 0 !== St[t] && void 0 !== St[t][e] ? a = St[t][e] : !1 === r.disableWarning && n.warn("Unable to look up font label for font '" + t + "', '" + e + "'. Refer to getFontList() for available fonts."), a || r.noFallback || null == (a = St.times[e]) && (a = St.times.normal), a; }, je = L.__private__.putInfo = function () { for (var t in Wt(), ot("<<"), ot("/Producer (jsPDF " + g.version + ")"), yt) { yt.hasOwnProperty(t) && yt[t] && ot("/" + t.substr(0, 1).toUpperCase() + t.substr(1) + " (" + _e(yt[t]) + ")"); } ot("/CreationDate (" + T + ")"), ot(">>"), ot("endobj"); }, Be = L.__private__.putCatalog = function (t) { var e = (t = t || {}).rootDictionaryObjId || Jt; switch (Wt(), ot("<<"), ot("/Type /Catalog"), ot("/Pages " + e + " 0 R"), lt || (lt = "fullwidth"), lt) { case "fullwidth": ot("/OpenAction [3 0 R /FitH null]"); break; case "fullheight": ot("/OpenAction [3 0 R /FitV null]"); break; case "fullpage": ot("/OpenAction [3 0 R /Fit]"); break; case "original": ot("/OpenAction [3 0 R /XYZ null null 1]"); break; default: var n = "" + lt; "%" === n.substr(n.length - 1) && (lt = parseInt(lt) / 100), "number" == typeof lt && ot("/OpenAction [3 0 R /XYZ null null " + O(lt) + "]"); } switch (mt || (mt = "continuous"), mt) { case "continuous": ot("/PageLayout /OneColumn"); break; case "single": ot("/PageLayout /SinglePage"); break; case "two": case "twoleft": ot("/PageLayout /TwoColumnLeft"); break; case "tworight": ot("/PageLayout /TwoColumnRight"); } pt && ot("/PageMode /" + pt), Mt.publish("putCatalog"), ot(">>"), ot("endobj"); }, Oe = L.__private__.putTrailer = function () { ot("trailer"), ot("<<"), ot("/Size " + (K + 1)), ot("/Root " + K + " 0 R"), ot("/Info " + (K - 1) + " 0 R"), ot("/ID [ <" + D + "> <" + D + "> ]"), ot(">>"); }, Me = L.__private__.putHeader = function () { ot("%PDF-" + x), ot("%ºß¬à"); }, Ee = L.__private__.putXRef = function () { var t = "0000000000"; ot("xref"), ot("0 " + (K + 1)), ot("0000000000 65535 f "); for (var e = 1; e <= K; e++) { "function" == typeof Z[e] ? ot((t + Z[e]()).slice(-10) + " 00000 n ") : void 0 !== Z[e] ? ot((t + Z[e]).slice(-10) + " 00000 n ") : ot("0000000000 00000 n "); } }, qe = L.__private__.buildDocument = function () { it(), at($), Mt.publish("buildDocument"), Me(), ee(), ye(), be(), je(), Be(); var t = Q; return Ee(), Oe(), ot("startxref"), ot("" + t), ot("%%EOF"), at(et[Y]), $.join("\n"); }, Re = L.__private__.getBlob = function (t) { return new Blob([ut(t)], { type: "application/pdf" }); }, Te = L.output = L.__private__.output = xe(function (e, r) { switch ("string" == typeof (r = r || {}) ? r = { filename: r } : r.filename = r.filename || "generated.pdf", e) { case void 0: return qe(); case "save": L.save(r.filename); break; case "arraybuffer": return ut(qe()); case "blob": return Re(qe()); case "bloburi": case "bloburl": if (void 0 !== t.URL && "function" == typeof t.URL.createObjectURL) return t.URL && t.URL.createObjectURL(Re(qe())) || void 0; n.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser."); break; case "datauristring": case "dataurlstring": var i = "", a = qe(); try { i = s(a); } catch (t) { i = s(unescape(encodeURIComponent(a))); } return "data:application/pdf;filename=" + r.filename + ";base64," + i; case "pdfobjectnewwindow": if ("[object Window]" === Object.prototype.toString.call(t)) { var o = '<html><style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style><body><script src="' + (r.pdfObjectUrl || "https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js") + '"><\/script><script >PDFObject.embed("' + this.output("dataurlstring") + '", ' + JSON.stringify(r) + ");<\/script></body></html>", u = t.open(); return null !== u && u.document.write(o), u; } throw new Error("The option pdfobjectnewwindow just works in a browser-environment."); case "pdfjsnewwindow": if ("[object Window]" === Object.prototype.toString.call(t)) { var c = '<html><style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style><body><iframe id="pdfViewer" src="' + (r.pdfJsUrl || "examples/PDF.js/web/viewer.html") + "?file=&downloadName=" + r.filename + '" width="500px" height="400px" /></body></html>', h = t.open(); if (null !== h) { h.document.write(c); var l = this; h.document.documentElement.querySelector("#pdfViewer").onload = function () { h.document.title = r.filename, h.document.documentElement.querySelector("#pdfViewer").contentWindow.PDFViewerApplication.open(l.output("bloburl")); }; } return h; } throw new Error("The option pdfjsnewwindow just works in a browser-environment."); case "dataurlnewwindow": if ("[object Window]" !== Object.prototype.toString.call(t)) throw new Error("The option dataurlnewwindow just works in a browser-environment."); var f = '<html><style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style><body><iframe src="' + this.output("datauristring", r) + '"></iframe></body></html>', d = t.open(); if (null !== d && (d.document.write(f), d.document.title = r.filename), d || "undefined" == typeof safari) return d; break; case "datauri": case "dataurl": return t.document.location.href = this.output("datauristring", r); default: return null; } }), De = function De(t) { return !0 === Array.isArray(Et) && Et.indexOf(t) > -1; }; switch (a) { case "pt": Nt = 1; break; case "mm": Nt = 72 / 25.4; break; case "cm": Nt = 72 / 2.54; break; case "in": Nt = 72; break; case "px": Nt = 1 == De("px_scaling") ? .75 : 96 / 72; break; case "pc": case "em": Nt = 12; break; case "ex": Nt = 6; break; default: throw new Error("Invalid unit: " + a); } V(), z(); var Ue = L.__private__.getPageInfo = L.getPageInfo = function (t) { if (isNaN(t) || t % 1 != 0) throw new Error("Invalid argument passed to jsPDF.getPageInfo"); return { objId: Ot[t].objId, pageNumber: t, pageContext: Ot[t] }; }, ze = L.__private__.getPageInfoByObjId = function (t) { if (isNaN(t) || t % 1 != 0) throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId"); for (var e in Ot) { if (Ot[e].objId === t) break; } return Ue(e); }, He = L.__private__.getCurrentPageInfo = L.getCurrentPageInfo = function () { return { objId: Ot[Y].objId, pageNumber: Y, pageContext: Ot[Y] }; }; L.addPage = function () { return Pe.apply(this, arguments), this; }, L.setPage = function () { return Fe.apply(this, arguments), at.call(this, et[Y]), this; }, L.insertPage = function (t) { return this.addPage(), this.movePage(Y, t), this; }, L.movePage = function (t, e) { var n, r; if (t > e) { n = et[t], r = Ot[t]; for (var i = t; i > e; i--) { et[i] = et[i - 1], Ot[i] = Ot[i - 1]; } et[e] = n, Ot[e] = r, this.setPage(e); } else if (t < e) { n = et[t], r = Ot[t]; for (var a = t; a < e; a++) { et[a] = et[a + 1], Ot[a] = Ot[a + 1]; } et[e] = n, Ot[e] = r, this.setPage(e); } return this; }, L.deletePage = function () { return ke.apply(this, arguments), this; }, L.__private__.text = L.text = function (t, e, n, r, i) { var a, o, s, u, c, h, l, f, d = (r = r || {}).scope || this; if ("number" == typeof t && "number" == typeof e && ("string" == typeof n || Array.isArray(n))) { var p = n; n = e, e = t, t = p; } if (arguments[3] instanceof Dt == !1 ? (s = arguments[4], u = arguments[5], "object" == _typeof(l = arguments[3]) && null !== l || ("string" == typeof s && (u = s, s = null), "string" == typeof l && (u = l, l = null), "number" == typeof l && (s = l, l = null), r = { flags: l, angle: s, align: u })) : (j("The transform parameter of text() with a Matrix value"), f = i), isNaN(e) || isNaN(n) || null == t) throw new Error("Invalid arguments passed to jsPDF.text"); if (0 === t.length) return d; var g = "", m = !1, v = "number" == typeof r.lineHeightFactor ? r.lineHeightFactor : rn, b = d.internal.scaleFactor; function y(t) { return t = t.split("\t").join(Array(r.TabLen || 9).join(" ")), _e(t, l); } function w(t) { for (var e, n = t.concat(), r = [], i = n.length; i--;) { "string" == typeof (e = n.shift()) ? r.push(e) : Array.isArray(t) && (1 === e.length || void 0 === e[1] && void 0 === e[2]) ? r.push(e[0]) : r.push([e[0], e[1], e[2]]); } return r; } function L(t, e) { var n; if ("string" == typeof t) n = e(t)[0];else if (Array.isArray(t)) { for (var r, i, a = t.concat(), o = [], s = a.length; s--;) { "string" == typeof (r = a.shift()) ? o.push(e(r)[0]) : Array.isArray(r) && "string" == typeof r[0] && (i = e(r[0], r[1], r[2]), o.push([i[0], i[1], i[2]])); } n = o; } return n; } var x = !1, A = !0; if ("string" == typeof t) x = !0;else if (Array.isArray(t)) { var _ = t.concat(); o = []; for (var S, F = _.length; F--;) { ("string" != typeof (S = _.shift()) || Array.isArray(S) && "string" != typeof S[0]) && (A = !1); } x = A; } if (!1 === x) throw new Error('Type of text must be string or Array. "' + t + '" is not recognized.'); "string" == typeof t && (t = t.match(/[\r?\n]/) ? t.split(/\r\n|\r|\n/g) : [t]); var I = ht / d.internal.scaleFactor, B = I * (rn - 1); switch (r.baseline) { case "bottom": n -= B; break; case "top": n += I - B; break; case "hanging": n += I - 2 * B; break; case "middle": n += I / 2 - B; } if ((h = r.maxWidth || 0) > 0 && ("string" == typeof t ? t = d.splitTextToSize(t, h) : "[object Array]" === Object.prototype.toString.call(t) && (t = d.splitTextToSize(t.join(" "), h))), a = { text: t, x: e, y: n, options: r, mutex: { pdfEscape: _e, activeFontKey: wt, fonts: _t, activeFontSize: ht } }, Mt.publish("preProcessText", a), t = a.text, s = (r = a.options).angle, f instanceof Dt == !1 && s && "number" == typeof s) { s *= Math.PI / 180, 0 === r.rotationDirection && (s = -s), k === P.ADVANCED && (s = -s); var O = Math.cos(s), M = Math.sin(s); f = new Dt(O, M, -M, O, 0, 0); } else s && s instanceof Dt && (f = s); k !== P.ADVANCED || f || (f = zt), void 0 !== (c = r.charSpace || bn) && (g += C(E(c)) + " Tc\n", this.setCharSpace(this.getCharSpace() || 0)); r.lang; var q = -1, R = void 0 !== r.renderingMode ? r.renderingMode : r.stroke, T = d.internal.getCurrentPageInfo().pageContext; switch (R) { case 0: case !1: case "fill": q = 0; break; case 1: case !0: case "stroke": q = 1; break; case 2: case "fillThenStroke": q = 2; break; case 3: case "invisible": q = 3; break; case 4: case "fillAndAddForClipping": q = 4; break; case 5: case "strokeAndAddPathForClipping": q = 5; break; case 6: case "fillThenStrokeAndAddToPathForClipping": q = 6; break; case 7: case "addToPathForClipping": q = 7; } var D = void 0 !== T.usedRenderingMode ? T.usedRenderingMode : -1; -1 !== q ? g += q + " Tr\n" : -1 !== D && (g += "0 Tr\n"), -1 !== q && (T.usedRenderingMode = q), u = r.align || "left"; var U, z = ht * v, H = d.internal.pageSize.getWidth(), W = _t[wt]; c = r.charSpace || bn, h = r.maxWidth || 0, l = {}; var V = []; if ("[object Array]" === Object.prototype.toString.call(t)) { var G; o = w(t), "left" !== u && (U = o.map(function (t) { return d.getStringUnitWidth(t, { font: W, charSpace: c, fontSize: ht, doKerning: !1 }) * ht / b; })); var Y, J = 0; if ("right" === u) { e -= U[0], t = [], F = o.length; for (var X = 0; X < F; X++) { 0 === X ? (Y = hn(e), G = ln(n)) : (Y = E(J - U[X]), G = -z), t.push([o[X], Y, G]), J = U[X]; } } else if ("center" === u) { e -= U[0] / 2, t = [], F = o.length; for (var K = 0; K < F; K++) { 0 === K ? (Y = hn(e), G = ln(n)) : (Y = E((J - U[K]) / 2), G = -z), t.push([o[K], Y, G]), J = U[K]; } } else if ("left" === u) { t = [], F = o.length; for (var Z = 0; Z < F; Z++) { t.push(o[Z]); } } else { if ("justify" !== u) throw new Error('Unrecognized alignment option, use "left", "center", "right" or "justify".'); t = [], F = o.length, h = 0 !== h ? h : H; for (var $ = 0; $ < F; $++) { G = 0 === $ ? ln(n) : -z, Y = 0 === $ ? hn(e) : 0, $ < F - 1 && V.push(C(E((h - U[$]) / (o[$].split(" ").length - 1)))), t.push([o[$], Y, G]); } } } var Q = "boolean" == typeof r.R2L ? r.R2L : dt; !0 === Q && (t = L(t, function (t, e, n) { return [t.split("").reverse().join(""), e, n]; })), a = { text: t, x: e, y: n, options: r, mutex: { pdfEscape: _e, activeFontKey: wt, fonts: _t, activeFontSize: ht } }, Mt.publish("postProcessText", a), t = a.text, m = a.mutex.isHex || !1; var tt = _t[wt].encoding; "WinAnsiEncoding" !== tt && "StandardEncoding" !== tt || (t = L(t, function (t, e, n) { return [y(t), e, n]; })), o = w(t), t = []; for (var et, nt, rt, it = 0, at = 1, st = Array.isArray(o[0]) ? at : it, ut = "", ct = function ct(t, e, n) { var i = ""; return n instanceof Dt ? (n = "number" == typeof r.angle ? Ut(n, new Dt(1, 0, 0, 1, t, e)) : Ut(new Dt(1, 0, 0, 1, t, e), n), k === P.ADVANCED && (n = Ut(new Dt(1, 0, 0, -1, 0, 0), n)), i = n.join(" ") + " Tm\n") : i = C(t) + " " + C(e) + " Td\n", i; }, lt = 0; lt < o.length; lt++) { switch (ut = "", st) { case at: rt = (m ? "<" : "(") + o[lt][0] + (m ? ">" : ")"), et = parseFloat(o[lt][1]), nt = parseFloat(o[lt][2]); break; case it: rt = (m ? "<" : "(") + o[lt] + (m ? ">" : ")"), et = hn(e), nt = ln(n); } void 0 !== V && void 0 !== V[lt] && (ut = V[lt] + " Tw\n"), 0 === lt ? t.push(ut + ct(et, nt, f) + rt) : st === it ? t.push(ut + rt) : st === at && t.push(ut + ct(et, nt, f) + rt); } t = st === it ? t.join(" Tj\nT* ") : t.join(" Tj\n"), t += " Tj\n"; var ft = "BT\n/"; return ft += wt + " " + ht + " Tf\n", ft += C(ht * v) + " TL\n", ft += mn + "\n", ft += g, ft += t, ot(ft += "ET"), N[wt] = !0, d; }; var We = L.__private__.clip = L.clip = function (t) { return ot("evenodd" === t ? "W*" : "W"), this; }; L.clipEvenOdd = function () { return We("evenodd"); }, L.__private__.discardPath = L.discardPath = function () { return ot("n"), this; }; var Ve = L.__private__.isValidStyle = function (t) { var e = !1; return -1 !== [void 0, null, "S", "D", "F", "DF", "FD", "f", "f*", "B", "B*", "n"].indexOf(t) && (e = !0), e; }; L.__private__.setDefaultPathOperation = L.setDefaultPathOperation = function (t) { return Ve(t) && (y = t), this; }; var Ge = L.__private__.getStyle = L.getStyle = function (t) { var e = y; switch (t) { case "D": case "S": e = "S"; break; case "F": e = "f"; break; case "FD": case "DF": e = "B"; break; case "f": case "f*": case "B": case "B*": e = t; } return e; }, Ye = L.close = function () { return ot("h"), this; }; L.stroke = function () { return ot("S"), this; }, L.fill = function (t) { return Je("f", t), this; }, L.fillEvenOdd = function (t) { return Je("f*", t), this; }, L.fillStroke = function (t) { return Je("B", t), this; }, L.fillStrokeEvenOdd = function (t) { return Je("B*", t), this; }; var Je = function Je(t, e) { "object" == _typeof(e) ? Ze(e, t) : ot(t); }, Xe = function Xe(t) { null === t || k === P.ADVANCED && void 0 === t || (t = Ge(t), ot(t)); }; function Ke(t, e, n, r, i) { var a = new p(e || this.boundingBox, n || this.xStep, r || this.yStep, this.gState, i || this.matrix); a.stream = this.stream; var o = t + "$$" + this.cloneIndex++ + "$$"; return Ht(o, a), a; } var Ze = function Ze(t, e) { var n = Ft[t.key], r = kt[n]; if (r instanceof d) ot("q"), ot($e(e)), r.gState && L.setGState(r.gState), ot(t.matrix.toString() + " cm"), ot("/" + n + " sh"), ot("Q");else if (r instanceof p) { var i = new Dt(1, 0, 0, -1, 0, Cn()); t.matrix && (i = i.multiply(t.matrix || zt), n = Ke.call(r, t.key, t.boundingBox, t.xStep, t.yStep, i).id), ot("q"), ot("/Pattern cs"), ot("/" + n + " scn"), r.gState && L.setGState(r.gState), ot(e), ot("Q"); } }, $e = function $e(t) { switch (t) { case "f": case "F": return "W n"; case "f*": return "W* n"; case "B": return "W S"; case "B*": return "W* S"; case "S": return "W S"; case "n": return "W n"; } }, Qe = L.moveTo = function (t, e) { return ot(C(E(t)) + " " + C(R(e)) + " m"), this; }, tn = L.lineTo = function (t, e) { return ot(C(E(t)) + " " + C(R(e)) + " l"), this; }, en = L.curveTo = function (t, e, n, r, i, a) { return ot([C(E(t)), C(R(e)), C(E(n)), C(R(r)), C(E(i)), C(R(a)), "c"].join(" ")), this; }; L.__private__.line = L.line = function (t, e, n, r, i) { if (isNaN(t) || isNaN(e) || isNaN(n) || isNaN(r) || !Ve(i)) throw new Error("Invalid arguments passed to jsPDF.line"); return k === P.COMPAT ? this.lines([[n - t, r - e]], t, e, [1, 1], i || "S") : this.lines([[n - t, r - e]], t, e, [1, 1]).stroke(); }, L.__private__.lines = L.lines = function (t, e, n, r, i, a) { var o, s, u, c, h, l, f, d, p, g, m, v; if ("number" == typeof t && (v = n, n = e, e = t, t = v), r = r || [1, 1], a = a || !1, isNaN(e) || isNaN(n) || !Array.isArray(t) || !Array.isArray(r) || !Ve(i) || "boolean" != typeof a) throw new Error("Invalid arguments passed to jsPDF.lines"); for (Qe(e, n), o = r[0], s = r[1], c = t.length, g = e, m = n, u = 0; u < c; u++) { 2 === (h = t[u]).length ? (g = h[0] * o + g, m = h[1] * s + m, tn(g, m)) : (l = h[0] * o + g, f = h[1] * s + m, d = h[2] * o + g, p = h[3] * s + m, g = h[4] * o + g, m = h[5] * s + m, en(l, f, d, p, g, m)); } return a && Ye(), Xe(i), this; }, L.path = function (t) { for (var e = 0; e < t.length; e++) { var n = t[e], r = n.c; switch (n.op) { case "m": Qe(r[0], r[1]); break; case "l": tn(r[0], r[1]); break; case "c": en.apply(this, r); break; case "h": Ye(); } } return this; }, L.__private__.rect = L.rect = function (t, e, n, r, i) { if (isNaN(t) || isNaN(e) || isNaN(n) || isNaN(r) || !Ve(i)) throw new Error("Invalid arguments passed to jsPDF.rect"); return k === P.COMPAT && (r = -r), ot([C(E(t)), C(R(e)), C(E(n)), C(E(r)), "re"].join(" ")), Xe(i), this; }, L.__private__.triangle = L.triangle = function (t, e, n, r, i, a, o) { if (isNaN(t) || isNaN(e) || isNaN(n) || isNaN(r) || isNaN(i) || isNaN(a) || !Ve(o)) throw new Error("Invalid arguments passed to jsPDF.triangle"); return this.lines([[n - t, r - e], [i - n, a - r], [t - i, e - a]], t, e, [1, 1], o, !0), this; }, L.__private__.roundedRect = L.roundedRect = function (t, e, n, r, i, a, o) { if (isNaN(t) || isNaN(e) || isNaN(n) || isNaN(r) || isNaN(i) || isNaN(a) || !Ve(o)) throw new Error("Invalid arguments passed to jsPDF.roundedRect"); var s = 4 / 3 * (Math.SQRT2 - 1); return i = Math.min(i, .5 * n), a = Math.min(a, .5 * r), this.lines([[n - 2 * i, 0], [i * s, 0, i, a - a * s, i, a], [0, r - 2 * a], [0, a * s, -i * s, a, -i, a], [2 * i - n, 0], [-i * s, 0, -i, -a * s, -i, -a], [0, 2 * a - r], [0, -a * s, i * s, -a, i, -a]], t + i, e, [1, 1], o, !0), this; }, L.__private__.ellipse = L.ellipse = function (t, e, n, r, i) { if (isNaN(t) || isNaN(e) || isNaN(n) || isNaN(r) || !Ve(i)) throw new Error("Invalid arguments passed to jsPDF.ellipse"); var a = 4 / 3 * (Math.SQRT2 - 1) * n, o = 4 / 3 * (Math.SQRT2 - 1) * r; return Qe(t + n, e), en(t + n, e - o, t + a, e - r, t, e - r), en(t - a, e - r, t - n, e - o, t - n, e), en(t - n, e + o, t - a, e + r, t, e + r), en(t + a, e + r, t + n, e + o, t + n, e), Xe(i), this; }, L.__private__.circle = L.circle = function (t, e, n, r) { if (isNaN(t) || isNaN(e) || isNaN(n) || !Ve(r)) throw new Error("Invalid arguments passed to jsPDF.circle"); return this.ellipse(t, e, n, n, r); }, L.setFont = function (t, e) { return wt = Ce(t, e, { disableWarning: !1 }), this; }; var nn = L.__private__.getFont = L.getFont = function () { return _t[Ce.apply(L, arguments)]; }; L.__private__.getFontList = L.getFontList = function () { var t, e, n = {}; for (t in St) { if (St.hasOwnProperty(t)) for (e in n[t] = [], St[t]) { St[t].hasOwnProperty(e) && n[t].push(e); } } return n; }, L.addFont = function (t, e, n, r) { return r = r || "Identity-H", Ne.call(this, t, e, n, r); }; var rn, an = e.lineWidth || .200025, on = L.__private__.setLineWidth = L.setLineWidth = function (t) { return ot(C(E(t)) + " w"), this; }; L.__private__.setLineDash = g.API.setLineDash = g.API.setLineDashPattern = function (t, e) { if (t = t || [], e = e || 0, isNaN(e) || !Array.isArray(t)) throw new Error("Invalid arguments passed to jsPDF.setLineDash"); return t = t.map(function (t) { return C(E(t)); }).join(" "), e = C(E(e)), ot("[" + t + "] " + e + " d"), this; }; var sn = L.__private__.getLineHeight = L.getLineHeight = function () { return ht * rn; }; L.__private__.getLineHeight = L.getLineHeight = function () { return ht * rn; }; var un = L.__private__.setLineHeightFactor = L.setLineHeightFactor = function (t) { return "number" == typeof (t = t || 1.15) && (rn = t), this; }, cn = L.__private__.getLineHeightFactor = L.getLineHeightFactor = function () { return rn; }; un(e.lineHeight); var hn = L.__private__.getHorizontalCoordinate = function (t) { return E(t); }, ln = L.__private__.getVerticalCoordinate = function (t) { return k === P.ADVANCED ? t : Ot[Y].mediaBox.topRightY - Ot[Y].mediaBox.bottomLeftY - E(t); }, fn = L.__private__.getHorizontalCoordinateString = L.getHorizontalCoordinateString = function (t) { return C(hn(t)); }, dn = L.__private__.getVerticalCoordinateString = L.getVerticalCoordinateString = function (t) { return C(ln(t)); }, pn = e.strokeColor || "0 G"; L.__private__.getStrokeColor = L.getDrawColor = function () { return Kt(pn); }, L.__private__.setStrokeColor = L.setDrawColor = function (t, e, n, r) { return pn = Zt({ ch1: t, ch2: e, ch3: n, ch4: r, pdfColorType: "draw", precision: 2 }), ot(pn), this; }; var gn = e.fillColor || "0 g"; L.__private__.getFillColor = L.getFillColor = function () { return Kt(gn); }, L.__private__.setFillColor = L.setFillColor = function (t, e, n, r) { return gn = Zt({ ch1: t, ch2: e, ch3: n, ch4: r, pdfColorType: "fill", precision: 2 }), ot(gn), this; }; var mn = e.textColor || "0 g", vn = L.__private__.getTextColor = L.getTextColor = function () { return Kt(mn); }; L.__private__.setTextColor = L.setTextColor = function (t, e, n, r) { return mn = Zt({ ch1: t, ch2: e, ch3: n, ch4: r, pdfColorType: "text", precision: 3 }), this; }; var bn = e.charSpace, yn = L.__private__.getCharSpace = L.getCharSpace = function () { return parseFloat(bn || 0); }; L.__private__.setCharSpace = L.setCharSpace = function (t) { if (isNaN(t)) throw new Error("Invalid argument passed to jsPDF.setCharSpace"); return bn = t, this; }; var wn = 0; L.CapJoinStyles = { 0: 0, butt: 0, but: 0, miter: 0, 1: 1, round: 1, rounded: 1, circle: 1, 2: 2, projecting: 2, project: 2, square: 2, bevel: 2 }, L.__private__.setLineCap = L.setLineCap = function (t) { var e = L.CapJoinStyles[t]; if (void 0 === e) throw new Error("Line cap style of '" + t + "' is not recognized. See or extend .CapJoinStyles property for valid styles"); return wn = e, ot(e + " J"), this; }; var Nn = 0; L.__private__.setLineJoin = L.setLineJoin = function (t) { var e = L.CapJoinStyles[t]; if (void 0 === e) throw new Error("Line join style of '" + t + "' is not recognized. See or extend .CapJoinStyles property for valid styles"); return Nn = e, ot(e + " j"), this; }, L.__private__.setLineMiterLimit = L.__private__.setMiterLimit = L.setLineMiterLimit = L.setMiterLimit = function (t) { if (t = t || 0, isNaN(t)) throw new Error("Invalid argument passed to jsPDF.setLineMiterLimit"); return ot(C(E(t)) + " M"), this; }, L.GState = l, L.setGState = function (t) { (t = "string" == typeof t ? It[Ct[t]] : Ln(null, t)).equals(jt) || (ot("/" + t.id + " gs"), jt = t); }; var Ln = function Ln(t, e) { if (!t || !Ct[t]) { var n = !1; for (var r in It) { if (It.hasOwnProperty(r) && It[r].equals(e)) { n = !0; break; } } if (n) e = It[r];else { var i = "GS" + (Object.keys(It).length + 1).toString(10); It[i] = e, e.id = i; } return t && (Ct[t] = e.id), Mt.publish("addGState", e), e; } }; L.addGState = function (t, e) { return Ln(t, e), this; }, L.saveGraphicsState = function () { return ot("q"), Pt.push({ key: wt, size: ht, color: mn }), this; }, L.restoreGraphicsState = function () { ot("Q"); var t = Pt.pop(); return wt = t.key, ht = t.size, mn = t.color, jt = null, this; }, L.setCurrentTransformationMatrix = function (t) { return ot(t.toString() + " cm"), this; }, L.comment = function (t) { return ot("#" + t), this; }; var xn = function xn(t, e) { var n = t || 0; Object.defineProperty(this, "x", { enumerable: !0, get: function get() { return n; }, set: function set(t) { isNaN(t) || (n = parseFloat(t)); } }); var r = e || 0; Object.defineProperty(this, "y", { enumerable: !0, get: function get() { return r; }, set: function set(t) { isNaN(t) || (r = parseFloat(t)); } }); var i = "pt"; return Object.defineProperty(this, "type", { enumerable: !0, get: function get() { return i; }, set: function set(t) { i = t.toString(); } }), this; }, An = function An(t, e, n, r) { xn.call(this, t, e), this.type = "rect"; var i = n || 0; Object.defineProperty(this, "w", { enumerable: !0, get: function get() { return i; }, set: function set(t) { isNaN(t) || (i = parseFloat(t)); } }); var a = r || 0; return Object.defineProperty(this, "h", { enumerable: !0, get: function get() { return a; }, set: function set(t) { isNaN(t) || (a = parseFloat(t)); } }), this; }, _n = function _n() { this.page = Bt, this.currentPage = Y, this.pages = et.slice(0), this.pagesContext = Ot.slice(0), this.x = Lt, this.y = xt, this.matrix = At, this.width = Fn(Y), this.height = Cn(Y), this.outputDestination = rt, this.id = "", this.objectNumber = -1; }; _n.prototype.restore = function () { Bt = this.page, Y = this.currentPage, Ot = this.pagesContext, et = this.pages, Lt = this.x, xt = this.y, At = this.matrix, In(Y, this.width), jn(Y, this.height), rt = this.outputDestination; }; var Sn = function Sn(t, e, n, r, i) { Tt.push(new _n()), Bt = Y = 0, et = [], Lt = t, xt = e, At = i, Se([n, r]); }, Pn = function Pn(t) { if (!Rt[t]) { var e = new _n(), n = "Xo" + (Object.keys(qt).length + 1).toString(10); e.id = n, Rt[t] = n, qt[n] = e, Mt.publish("addFormObject", e), Tt.pop().restore(); } }; for (var kn in L.beginFormObject = function (t, e, n, r, i) { return Sn(t, e, n, r, i), this; }, L.endFormObject = function (t) { return Pn(t), this; }, L.doFormObject = function (t, e) { var n = qt[Rt[t]]; return ot("q"), ot(e.toString() + " cm"), ot("/" + n.id + " Do"), ot("Q"), this; }, L.getFormObject = function (t) { var e = qt[Rt[t]]; return { x: e.x, y: e.y, width: e.width, height: e.height, matrix: e.matrix }; }, L.save = function (e, n) { return e = e || "generated.pdf", (n = n || {}).returnPromise = n.returnPromise || !1, !1 === n.returnPromise ? (u(Re(qe()), e), "function" == typeof u.unload && t.setTimeout && setTimeout(u.unload, 911), this) : new Promise(function (n, r) { try { var i = u(Re(qe()), e); "function" == typeof u.unload && t.setTimeout && setTimeout(u.unload, 911), n(i); } catch (t) { r(t.message); } }); }, g.API) { g.API.hasOwnProperty(kn) && ("events" === kn && g.API.events.length ? function (t, e) { var n, r, i; for (i = e.length - 1; -1 !== i; i--) { n = e[i][0], r = e[i][1], t.subscribe.apply(t, [n].concat("function" == typeof r ? [r] : r)); } }(Mt, g.API.events) : L[kn] = g.API[kn]); } var Fn = L.getPageWidth = function (t) { return (Ot[t = t || Y].mediaBox.topRightX - Ot[t].mediaBox.bottomLeftX) / Nt; }, In = L.setPageWidth = function (t, e) { Ot[t].mediaBox.topRightX = e * Nt + Ot[t].mediaBox.bottomLeftX; }, Cn = L.getPageHeight = function (t) { return (Ot[t = t || Y].mediaBox.topRightY - Ot[t].mediaBox.bottomLeftY) / Nt; }, jn = L.setPageHeight = function (t, e) { Ot[t].mediaBox.topRightY = e * Nt + Ot[t].mediaBox.bottomLeftY; }; return L.internal = { pdfEscape: _e, getStyle: Ge, getFont: nn, getFontSize: ft, getCharSpace: yn, getTextColor: vn, getLineHeight: sn, getLineHeightFactor: cn, write: st, getHorizontalCoordinate: hn, getVerticalCoordinate: ln, getCoordinateString: fn, getVerticalCoordinateString: dn, collections: {}, newObject: Wt, newAdditionalObject: Yt, newObjectDeferred: Vt, newObjectDeferredBegin: Gt, getFilters: $t, putStream: Qt, events: Mt, scaleFactor: Nt, pageSize: { getWidth: function getWidth() { return Fn(Y); }, setWidth: function setWidth(t) { In(Y, t); }, getHeight: function getHeight() { return Cn(Y); }, setHeight: function setHeight(t) { jn(Y, t); } }, output: Te, getNumberOfPages: Ie, pages: et, out: ot, f2: O, f3: M, getPageInfo: Ue, getPageInfoByObjId: ze, getCurrentPageInfo: He, getPDFVersion: A, Point: xn, Rectangle: An, Matrix: Dt, hasHotfix: De }, Object.defineProperty(L.internal.pageSize, "width", { get: function get() { return Fn(Y); }, set: function set(t) { In(Y, t); }, enumerable: !0, configurable: !0 }), Object.defineProperty(L.internal.pageSize, "height", { get: function get() { return Cn(Y); }, set: function set(t) { jn(Y, t); }, enumerable: !0, configurable: !0 }), Le.call(L, ct), wt = "F1", Pe(o, i), Mt.publish("initialized"), L; } o = t.atob, s = t.btoa, l.prototype.equals = function (t) { var e, n = "id,objectNumber,equals"; if (!t || _typeof(t) != _typeof(this)) return !1; var r = 0; for (e in this) { if (!(n.indexOf(e) >= 0)) { if (this.hasOwnProperty(e) && !t.hasOwnProperty(e)) return !1; if (this[e] !== t[e]) return !1; r++; } } for (e in t) { t.hasOwnProperty(e) && n.indexOf(e) < 0 && r--; } return 0 === r; }, g.API = { events: [] }, g.version = "2.1.0"; var m, v = g.API, b = 1, y = function y(t) { return t.replace(/\\/g, "\\\\").replace(/\(/g, "\\(").replace(/\)/g, "\\)"); }, w = function w(t) { return t.replace(/\\\\/g, "\\").replace(/\\\(/g, "(").replace(/\\\)/g, ")"); }, N = function N(t) { return t.toFixed(2); }, L = function L(t) { return t.toFixed(5); }; v.__acroform__ = {}; var x = function x(t, e) { t.prototype = Object.create(e.prototype), t.prototype.constructor = t; }, A = function A(t) { return t * b; }, _ = function _(t) { var e = new J(), n = ut.internal.getHeight(t) || 0, r = ut.internal.getWidth(t) || 0; return e.BBox = [0, 0, Number(N(r)), Number(N(n))], e; }, S = v.__acroform__.setBit = function (t, e) { if (t = t || 0, e = e || 0, isNaN(t) || isNaN(e)) throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBit"); return t |= 1 << e; }, P = v.__acroform__.clearBit = function (t, e) { if (t = t || 0, e = e || 0, isNaN(t) || isNaN(e)) throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.clearBit"); return t &= ~(1 << e); }, k = v.__acroform__.getBit = function (t, e) { if (isNaN(t) || isNaN(e)) throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.getBit"); return 0 == (t & 1 << e) ? 0 : 1; }, F = v.__acroform__.getBitForPdf = function (t, e) { if (isNaN(t) || isNaN(e)) throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.getBitForPdf"); return k(t, e - 1); }, I = v.__acroform__.setBitForPdf = function (t, e) { if (isNaN(t) || isNaN(e)) throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBitForPdf"); return S(t, e - 1); }, C = v.__acroform__.clearBitForPdf = function (t, e) { if (isNaN(t) || isNaN(e)) throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.clearBitForPdf"); return P(t, e - 1); }, j$2 = v.__acroform__.calculateCoordinates = function (t) { var e = this.internal.getHorizontalCoordinate, n = this.internal.getVerticalCoordinate, r = t[0], i = t[1], a = t[2], o = t[3], s = {}; return s.lowerLeft_X = e(r) || 0, s.lowerLeft_Y = n(i + o) || 0, s.upperRight_X = e(r + a) || 0, s.upperRight_Y = n(i) || 0, [Number(N(s.lowerLeft_X)), Number(N(s.lowerLeft_Y)), Number(N(s.upperRight_X)), Number(N(s.upperRight_Y))]; }, B = function B(t) { if (t.appearanceStreamContent) return t.appearanceStreamContent; if (t.V || t.DV) { var e = [], n = t.V || t.DV, r = O(t, n), i = m.internal.getFont(t.fontName, t.fontStyle).id; e.push("/Tx BMC"), e.push("q"), e.push("BT"), e.push(m.__private__.encodeColorString(t.color)), e.push("/" + i + " " + N(r.fontSize) + " Tf"), e.push("1 0 0 1 0 0 Tm"), e.push(r.text), e.push("ET"), e.push("Q"), e.push("EMC"); var a = new _(t); return a.stream = e.join("\n"), a; } }, O = function O(t, e) { var n = 0 === t.fontSize ? t.maxFontSize : t.fontSize, r = { text: "", fontSize: "" }, i = (e = ")" == (e = "(" == e.substr(0, 1) ? e.substr(1) : e).substr(e.length - 1) ? e.substr(0, e.length - 1) : e).split(" "), a = n, o = ut.internal.getHeight(t) || 0; o = o < 0 ? -o : o; var s = ut.internal.getWidth(t) || 0; s = s < 0 ? -s : s; var u = function u(e, n, r) { if (e + 1 < i.length) { var a = n + " " + i[e + 1]; return M(a, t, r).width <= s - 4; } return !1; }; a++; t: for (; a > 0;) { e = "", a--; var c, h, l = M("3", t, a).height, f = t.multiline ? o - a : (o - l) / 2, d = f += 2, p = 0, g = 0; if (a <= 0) { e = "(...) Tj\n", e += "% Width of Text: " + M(e, t, a = 12).width + ", FieldWidth:" + s + "\n"; break; } var m = "", v = 0; for (var b in i) { if (i.hasOwnProperty(b)) { m = " " == (m += i[b] + " ").substr(m.length - 1) ? m.substr(0, m.length - 1) : m; var w = parseInt(b), L = u(w, m, a), x = b >= i.length - 1; if (L && !x) { m += " "; continue; } if (L || x) { if (x) g = w;else if (t.multiline && (l + 2) * (v + 2) + 2 > o) continue t; } else { if (!t.multiline) continue t; if ((l + 2) * (v + 2) + 2 > o) continue t; g = w; } for (var A = "", _ = p; _ <= g; _++) { A += i[_] + " "; } switch (A = " " == A.substr(A.length - 1) ? A.substr(0, A.length - 1) : A, h = M(A, t, a).width, t.textAlign) { case "right": c = s - h - 2; break; case "center": c = (s - h) / 2; break; case "left": default: c = 2; } e += N(c) + " " + N(d) + " Td\n", e += "(" + y(A) + ") Tj\n", e += -N(c) + " 0 Td\n", d = -(a + 2), h = 0, p = g + 1, v++, m = ""; } } break; } return r.text = e, r.fontSize = a, r; }, M = function M(t, e, n) { var r = m.internal.getFont(e.fontName, e.fontStyle), i = m.getStringUnitWidth(t, { font: r, fontSize: parseFloat(n), charSpace: 0 }) * parseFloat(n); return { height: m.getStringUnitWidth("3", { font: r, fontSize: parseFloat(n), charSpace: 0 }) * parseFloat(n) * 1.5, width: i }; }, E$2 = { fields: [], xForms: [], acroFormDictionaryRoot: null, printedOut: !1, internal: null, isInitialized: !1 }, q = function q() { m.internal.acroformPlugin.acroFormDictionaryRoot.objId = void 0; var t = m.internal.acroformPlugin.acroFormDictionaryRoot.Fields; for (var e in t) { if (t.hasOwnProperty(e)) { var n = t[e]; n.objId = void 0, n.hasAnnotation && T.call(m, n); } } }, R = function R(t) { m.internal.acroformPlugin.printedOut && (m.internal.acroformPlugin.printedOut = !1, m.internal.acroformPlugin.acroFormDictionaryRoot = null), m.internal.acroformPlugin.acroFormDictionaryRoot || W.call(m), m.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(t); }, T = function T(t) { var e = { type: "reference", object: t }; void 0 === m.internal.getPageInfo(t.page).pageContext.annotations.find(function (t) { return t.type === e.type && t.object === e.object; }) && m.internal.getPageInfo(t.page).pageContext.annotations.push(e); }, D = function D() { if (void 0 === m.internal.acroformPlugin.acroFormDictionaryRoot) throw new Error("putCatalogCallback: Root missing."); m.internal.write("/AcroForm " + m.internal.acroformPlugin.acroFormDictionaryRoot.objId + " 0 R"); }, U = function U() { m.internal.events.unsubscribe(m.internal.acroformPlugin.acroFormDictionaryRoot._eventID), delete m.internal.acroformPlugin.acroFormDictionaryRoot._eventID, m.internal.acroformPlugin.printedOut = !0; }, z = function z(t) { var e = !t; for (var n in t || (m.internal.newObjectDeferredBegin(m.internal.acroformPlugin.acroFormDictionaryRoot.objId, !0), m.internal.acroformPlugin.acroFormDictionaryRoot.putStream()), t = t || m.internal.acroformPlugin.acroFormDictionaryRoot.Kids) { if (t.hasOwnProperty(n)) { var r = t[n], i = [], a = r.Rect; if (r.Rect && (r.Rect = j$2.call(this, r.Rect)), m.internal.newObjectDeferredBegin(r.objId, !0), r.DA = ut.createDefaultAppearanceStream(r), "object" == _typeof(r) && "function" == typeof r.getKeyValueListForStream && (i = r.getKeyValueListForStream()), r.Rect = a, r.hasAppearanceStream && !r.appearanceStreamContent) { var o = B.call(this, r); i.push({ key: "AP", value: "<</N " + o + ">>" }), m.internal.acroformPlugin.xForms.push(o); } if (r.appearanceStreamContent) { var s = ""; for (var u in r.appearanceStreamContent) { if (r.appearanceStreamContent.hasOwnProperty(u)) { var c = r.appearanceStreamContent[u]; if (s += "/" + u + " ", s += "<<", Object.keys(c).length >= 1 || Array.isArray(c)) { for (var n in c) { if (c.hasOwnProperty(n)) { var h = c[n]; "function" == typeof h && (h = h.call(this, r)), s += "/" + n + " " + h + " ", m.internal.acroformPlugin.xForms.indexOf(h) >= 0 || m.internal.acroformPlugin.xForms.push(h); } } } else "function" == typeof (h = c) && (h = h.call(this, r)), s += "/" + n + " " + h, m.internal.acroformPlugin.xForms.indexOf(h) >= 0 || m.internal.acroformPlugin.xForms.push(h); s += ">>"; } } i.push({ key: "AP", value: "<<\n" + s + ">>" }); } m.internal.putStream({ additionalKeyValues: i }), m.internal.out("endobj"); } } e && H.call(this, m.internal.acroformPlugin.xForms); }, H = function H(t) { for (var e in t) { if (t.hasOwnProperty(e)) { var n = e, r = t[e]; m.internal.newObjectDeferredBegin(r && r.objId, !0), "object" == _typeof(r) && "function" == typeof r.putStream && r.putStream(), delete t[n]; } } }, W = function W() { if (void 0 !== this.internal && (void 0 === this.internal.acroformPlugin || !1 === this.internal.acroformPlugin.isInitialized)) { if (m = this, K.FieldNum = 0, this.internal.acroformPlugin = JSON.parse(JSON.stringify(E$2)), this.internal.acroformPlugin.acroFormDictionaryRoot) throw new Error("Exception while creating AcroformDictionary"); b = m.internal.scaleFactor, m.internal.acroformPlugin.acroFormDictionaryRoot = new X(), m.internal.acroformPlugin.acroFormDictionaryRoot._eventID = m.internal.events.subscribe("postPutResources", U), m.internal.events.subscribe("buildDocument", q), m.internal.events.subscribe("putCatalog", D), m.internal.events.subscribe("postPutPages", z), m.internal.acroformPlugin.isInitialized = !0; } }, V = v.__acroform__.arrayToPdfArray = function (t) { if (Array.isArray(t)) { for (var e = "[", n = 0; n < t.length; n++) { switch (0 !== n && (e += " "), _typeof(t[n])) { case "boolean": case "number": case "object": e += t[n].toString(); break; case "string": "/" !== t[n].substr(0, 1) ? e += "(" + y(t[n].toString()) + ")" : e += t[n].toString(); } } return e += "]"; } throw new Error("Invalid argument passed to jsPDF.__acroform__.arrayToPdfArray"); }; var G = function G(t) { return (t = t || "").toString(), t = "(" + y(t) + ")"; }, Y = function Y() { var t; Object.defineProperty(this, "objId", { configurable: !0, get: function get() { return t || (t = m.internal.newObjectDeferred()), t; }, set: function set(e) { t = e; } }); }; Y.prototype.toString = function () { return this.objId + " 0 R"; }, Y.prototype.putStream = function () { var t = this.getKeyValueListForStream(); m.internal.putStream({ data: this.stream, additionalKeyValues: t }), m.internal.out("endobj"); }, Y.prototype.getKeyValueListForStream = function () { return function (t) { var e = [], n = Object.getOwnPropertyNames(t).filter(function (t) { return "content" != t && "appearanceStreamContent" != t && "_" != t.substring(0, 1); }); for (var r in n) { if (!1 === Object.getOwnPropertyDescriptor(t, n[r]).configurable) { var i = n[r], a = t[i]; a && (Array.isArray(a) ? e.push({ key: i, value: V(a) }) : a instanceof Y ? e.push({ key: i, value: a.objId + " 0 R" }) : "function" != typeof a && e.push({ key: i, value: a })); } } return e; }(this); }; var J = function J() { Y.call(this), Object.defineProperty(this, "Type", { value: "/XObject", configurable: !1, writeable: !0 }), Object.defineProperty(this, "Subtype", { value: "/Form", configurable: !1, writeable: !0 }), Object.defineProperty(this, "FormType", { value: 1, configurable: !1, writeable: !0 }); var t, e = []; Object.defineProperty(this, "BBox", { configurable: !1, writeable: !0, get: function get() { return e; }, set: function set(t) { e = t; } }), Object.defineProperty(this, "Resources", { value: "2 0 R", configurable: !1, writeable: !0 }), Object.defineProperty(this, "stream", { enumerable: !1, configurable: !0, set: function set(e) { t = e.trim(); }, get: function get() { return t || null; } }); }; x(J, Y); var X = function X() { Y.call(this); var t, e = []; Object.defineProperty(this, "Kids", { enumerable: !1, configurable: !0, get: function get() { return e.length > 0 ? e : void 0; } }), Object.defineProperty(this, "Fields", { enumerable: !1, configurable: !1, get: function get() { return e; } }), Object.defineProperty(this, "DA", { enumerable: !1, configurable: !1, get: function get() { if (t) return "(" + t + ")"; }, set: function set(e) { t = e; } }); }; x(X, Y); var K = function K() { Y.call(this); var t = 4; Object.defineProperty(this, "F", { enumerable: !1, configurable: !1, get: function get() { return t; }, set: function set(e) { if (isNaN(e)) throw new Error('Invalid value "' + e + '" for attribute F supplied.'); t = e; } }), Object.defineProperty(this, "showWhenPrinted", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(t, 3)); }, set: function set(e) { !0 === Boolean(e) ? this.F = I(t, 3) : this.F = C(t, 3); } }); var e = 0; Object.defineProperty(this, "Ff", { enumerable: !1, configurable: !1, get: function get() { return e; }, set: function set(t) { if (isNaN(t)) throw new Error('Invalid value "' + t + '" for attribute Ff supplied.'); e = t; } }); var n = []; Object.defineProperty(this, "Rect", { enumerable: !1, configurable: !1, get: function get() { if (0 !== n.length) return n; }, set: function set(t) { n = void 0 !== t ? t : []; } }), Object.defineProperty(this, "x", { enumerable: !0, configurable: !0, get: function get() { return !n || isNaN(n[0]) ? 0 : n[0]; }, set: function set(t) { n[0] = t; } }), Object.defineProperty(this, "y", { enumerable: !0, configurable: !0, get: function get() { return !n || isNaN(n[1]) ? 0 : n[1]; }, set: function set(t) { n[1] = t; } }), Object.defineProperty(this, "width", { enumerable: !0, configurable: !0, get: function get() { return !n || isNaN(n[2]) ? 0 : n[2]; }, set: function set(t) { n[2] = t; } }), Object.defineProperty(this, "height", { enumerable: !0, configurable: !0, get: function get() { return !n || isNaN(n[3]) ? 0 : n[3]; }, set: function set(t) { n[3] = t; } }); var r = ""; Object.defineProperty(this, "FT", { enumerable: !0, configurable: !1, get: function get() { return r; }, set: function set(t) { switch (t) { case "/Btn": case "/Tx": case "/Ch": case "/Sig": r = t; break; default: throw new Error('Invalid value "' + t + '" for attribute FT supplied.'); } } }); var i = null; Object.defineProperty(this, "T", { enumerable: !0, configurable: !1, get: function get() { if (!i || i.length < 1) { if (this instanceof it) return; i = "FieldObject" + K.FieldNum++; } return "(" + y(i) + ")"; }, set: function set(t) { i = t.toString(); } }), Object.defineProperty(this, "fieldName", { configurable: !0, enumerable: !0, get: function get() { return i; }, set: function set(t) { i = t; } }); var a = "helvetica"; Object.defineProperty(this, "fontName", { enumerable: !0, configurable: !0, get: function get() { return a; }, set: function set(t) { a = t; } }); var o = "normal"; Object.defineProperty(this, "fontStyle", { enumerable: !0, configurable: !0, get: function get() { return o; }, set: function set(t) { o = t; } }); var s = 0; Object.defineProperty(this, "fontSize", { enumerable: !0, configurable: !0, get: function get() { return s; }, set: function set(t) { s = t; } }); var u = void 0; Object.defineProperty(this, "maxFontSize", { enumerable: !0, configurable: !0, get: function get() { return void 0 === u ? 50 / b : u; }, set: function set(t) { u = t; } }); var c = "black"; Object.defineProperty(this, "color", { enumerable: !0, configurable: !0, get: function get() { return c; }, set: function set(t) { c = t; } }); var h = "/F1 0 Tf 0 g"; Object.defineProperty(this, "DA", { enumerable: !0, configurable: !1, get: function get() { if (!(!h || this instanceof it || this instanceof ot)) return G(h); }, set: function set(t) { t = t.toString(), h = t; } }); var l = null; Object.defineProperty(this, "DV", { enumerable: !1, configurable: !1, get: function get() { if (l) return this instanceof et == !1 ? G(l) : l; }, set: function set(t) { t = t.toString(), l = this instanceof et == !1 ? "(" === t.substr(0, 1) ? w(t.substr(1, t.length - 2)) : w(t) : t; } }), Object.defineProperty(this, "defaultValue", { enumerable: !0, configurable: !0, get: function get() { return this instanceof et == !0 ? w(l.substr(1, l.length - 1)) : l; }, set: function set(t) { t = t.toString(), l = this instanceof et == !0 ? "/" + t : t; } }); var f = null; Object.defineProperty(this, "V", { enumerable: !1, configurable: !1, get: function get() { if (f) return this instanceof et == !1 ? G(f) : f; }, set: function set(t) { t = t.toString(), f = this instanceof et == !1 ? "(" === t.substr(0, 1) ? w(t.substr(1, t.length - 2)) : w(t) : t; } }), Object.defineProperty(this, "value", { enumerable: !0, configurable: !0, get: function get() { return this instanceof et == !0 ? w(f.substr(1, f.length - 1)) : f; }, set: function set(t) { t = t.toString(), f = this instanceof et == !0 ? "/" + t : t; } }), Object.defineProperty(this, "hasAnnotation", { enumerable: !0, configurable: !0, get: function get() { return this.Rect; } }), Object.defineProperty(this, "Type", { enumerable: !0, configurable: !1, get: function get() { return this.hasAnnotation ? "/Annot" : null; } }), Object.defineProperty(this, "Subtype", { enumerable: !0, configurable: !1, get: function get() { return this.hasAnnotation ? "/Widget" : null; } }); var d, p = !1; Object.defineProperty(this, "hasAppearanceStream", { enumerable: !0, configurable: !0, writeable: !0, get: function get() { return p; }, set: function set(t) { t = Boolean(t), p = t; } }), Object.defineProperty(this, "page", { enumerable: !0, configurable: !0, writeable: !0, get: function get() { if (d) return d; }, set: function set(t) { d = t; } }), Object.defineProperty(this, "readOnly", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 1)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 1) : this.Ff = C(this.Ff, 1); } }), Object.defineProperty(this, "required", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 2)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 2) : this.Ff = C(this.Ff, 2); } }), Object.defineProperty(this, "noExport", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 3)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 3) : this.Ff = C(this.Ff, 3); } }); var g = null; Object.defineProperty(this, "Q", { enumerable: !0, configurable: !1, get: function get() { if (null !== g) return g; }, set: function set(t) { if (-1 === [0, 1, 2].indexOf(t)) throw new Error('Invalid value "' + t + '" for attribute Q supplied.'); g = t; } }), Object.defineProperty(this, "textAlign", { get: function get() { var t; switch (g) { case 0: default: t = "left"; break; case 1: t = "center"; break; case 2: t = "right"; } return t; }, configurable: !0, enumerable: !0, set: function set(t) { switch (t) { case "right": case 2: g = 2; break; case "center": case 1: g = 1; break; case "left": case 0: default: g = 0; } } }); }; x(K, Y); var Z = function Z() { K.call(this), this.FT = "/Ch", this.V = "()", this.fontName = "zapfdingbats"; var t = 0; Object.defineProperty(this, "TI", { enumerable: !0, configurable: !1, get: function get() { return t; }, set: function set(e) { t = e; } }), Object.defineProperty(this, "topIndex", { enumerable: !0, configurable: !0, get: function get() { return t; }, set: function set(e) { t = e; } }); var e = []; Object.defineProperty(this, "Opt", { enumerable: !0, configurable: !1, get: function get() { return V(e); }, set: function set(t) { var n, r; r = [], "string" == typeof (n = t) && (r = function (t, e, n) { n || (n = 1); for (var r, i = []; r = e.exec(t);) { i.push(r[n]); } return i; }(n, /\((.*?)\)/g)), e = r; } }), this.getOptions = function () { return e; }, this.setOptions = function (t) { e = t, this.sort && e.sort(); }, this.addOption = function (t) { t = (t = t || "").toString(), e.push(t), this.sort && e.sort(); }, this.removeOption = function (t, n) { for (n = n || !1, t = (t = t || "").toString(); -1 !== e.indexOf(t) && (e.splice(e.indexOf(t), 1), !1 !== n);) { } }, Object.defineProperty(this, "combo", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 18)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 18) : this.Ff = C(this.Ff, 18); } }), Object.defineProperty(this, "edit", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 19)); }, set: function set(t) { !0 === this.combo && (!0 === Boolean(t) ? this.Ff = I(this.Ff, 19) : this.Ff = C(this.Ff, 19)); } }), Object.defineProperty(this, "sort", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 20)); }, set: function set(t) { !0 === Boolean(t) ? (this.Ff = I(this.Ff, 20), e.sort()) : this.Ff = C(this.Ff, 20); } }), Object.defineProperty(this, "multiSelect", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 22)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 22) : this.Ff = C(this.Ff, 22); } }), Object.defineProperty(this, "doNotSpellCheck", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 23)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 23) : this.Ff = C(this.Ff, 23); } }), Object.defineProperty(this, "commitOnSelChange", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 27)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 27) : this.Ff = C(this.Ff, 27); } }), this.hasAppearanceStream = !1; }; x(Z, K); var $$3 = function $() { Z.call(this), this.fontName = "helvetica", this.combo = !1; }; x($$3, Z); var Q = function Q() { $$3.call(this), this.combo = !0; }; x(Q, $$3); var tt = function tt() { Q.call(this), this.edit = !0; }; x(tt, Q); var et = function et() { K.call(this), this.FT = "/Btn", Object.defineProperty(this, "noToggleToOff", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 15)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 15) : this.Ff = C(this.Ff, 15); } }), Object.defineProperty(this, "radio", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 16)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 16) : this.Ff = C(this.Ff, 16); } }), Object.defineProperty(this, "pushButton", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 17)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 17) : this.Ff = C(this.Ff, 17); } }), Object.defineProperty(this, "radioIsUnison", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 26)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 26) : this.Ff = C(this.Ff, 26); } }); var t, e = {}; Object.defineProperty(this, "MK", { enumerable: !1, configurable: !1, get: function get() { if (0 !== Object.keys(e).length) { var t, n = []; for (t in n.push("<<"), e) { n.push("/" + t + " (" + e[t] + ")"); } return n.push(">>"), n.join("\n"); } }, set: function set(t) { "object" == _typeof(t) && (e = t); } }), Object.defineProperty(this, "caption", { enumerable: !0, configurable: !0, get: function get() { return e.CA || ""; }, set: function set(t) { "string" == typeof t && (e.CA = t); } }), Object.defineProperty(this, "AS", { enumerable: !1, configurable: !1, get: function get() { return t; }, set: function set(e) { t = e; } }), Object.defineProperty(this, "appearanceState", { enumerable: !0, configurable: !0, get: function get() { return t.substr(1, t.length - 1); }, set: function set(e) { t = "/" + e; } }); }; x(et, K); var nt = function nt() { et.call(this), this.pushButton = !0; }; x(nt, et); var rt = function rt() { et.call(this), this.radio = !0, this.pushButton = !1; var t = []; Object.defineProperty(this, "Kids", { enumerable: !0, configurable: !1, get: function get() { return t; }, set: function set(e) { t = void 0 !== e ? e : []; } }); }; x(rt, et); var it = function it() { var t, e; K.call(this), Object.defineProperty(this, "Parent", { enumerable: !1, configurable: !1, get: function get() { return t; }, set: function set(e) { t = e; } }), Object.defineProperty(this, "optionName", { enumerable: !1, configurable: !0, get: function get() { return e; }, set: function set(t) { e = t; } }); var n, r = {}; Object.defineProperty(this, "MK", { enumerable: !1, configurable: !1, get: function get() { var t, e = []; for (t in e.push("<<"), r) { e.push("/" + t + " (" + r[t] + ")"); } return e.push(">>"), e.join("\n"); }, set: function set(t) { "object" == _typeof(t) && (r = t); } }), Object.defineProperty(this, "caption", { enumerable: !0, configurable: !0, get: function get() { return r.CA || ""; }, set: function set(t) { "string" == typeof t && (r.CA = t); } }), Object.defineProperty(this, "AS", { enumerable: !1, configurable: !1, get: function get() { return n; }, set: function set(t) { n = t; } }), Object.defineProperty(this, "appearanceState", { enumerable: !0, configurable: !0, get: function get() { return n.substr(1, n.length - 1); }, set: function set(t) { n = "/" + t; } }), this.caption = "l", this.appearanceState = "Off", this._AppearanceType = ut.RadioButton.Circle, this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(this.optionName); }; x(it, K), rt.prototype.setAppearance = function (t) { if (!("createAppearanceStream" in t) || !("getCA" in t)) throw new Error("Couldn't assign Appearance to RadioButton. Appearance was Invalid!"); for (var e in this.Kids) { if (this.Kids.hasOwnProperty(e)) { var n = this.Kids[e]; n.appearanceStreamContent = t.createAppearanceStream(n.optionName), n.caption = t.getCA(); } } }, rt.prototype.createOption = function (t) { var e = new it(); return e.Parent = this, e.optionName = t, this.Kids.push(e), ct.call(this, e), e; }; var at = function at() { et.call(this), this.fontName = "zapfdingbats", this.caption = "3", this.appearanceState = "On", this.value = "On", this.textAlign = "center", this.appearanceStreamContent = ut.CheckBox.createAppearanceStream(); }; x(at, et); var ot = function ot() { K.call(this), this.FT = "/Tx", Object.defineProperty(this, "multiline", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 13)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 13) : this.Ff = C(this.Ff, 13); } }), Object.defineProperty(this, "fileSelect", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 21)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 21) : this.Ff = C(this.Ff, 21); } }), Object.defineProperty(this, "doNotSpellCheck", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 23)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 23) : this.Ff = C(this.Ff, 23); } }), Object.defineProperty(this, "doNotScroll", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 24)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 24) : this.Ff = C(this.Ff, 24); } }), Object.defineProperty(this, "comb", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 25)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 25) : this.Ff = C(this.Ff, 25); } }), Object.defineProperty(this, "richText", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 26)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 26) : this.Ff = C(this.Ff, 26); } }); var t = null; Object.defineProperty(this, "MaxLen", { enumerable: !0, configurable: !1, get: function get() { return t; }, set: function set(e) { t = e; } }), Object.defineProperty(this, "maxLength", { enumerable: !0, configurable: !0, get: function get() { return t; }, set: function set(e) { Number.isInteger(e) && (t = e); } }), Object.defineProperty(this, "hasAppearanceStream", { enumerable: !0, configurable: !0, get: function get() { return this.V || this.DV; } }); }; x(ot, K); var st = function st() { ot.call(this), Object.defineProperty(this, "password", { enumerable: !0, configurable: !0, get: function get() { return Boolean(F(this.Ff, 14)); }, set: function set(t) { !0 === Boolean(t) ? this.Ff = I(this.Ff, 14) : this.Ff = C(this.Ff, 14); } }), this.password = !0; }; x(st, ot); var ut = { CheckBox: { createAppearanceStream: function createAppearanceStream() { return { N: { On: ut.CheckBox.YesNormal }, D: { On: ut.CheckBox.YesPushDown, Off: ut.CheckBox.OffPushDown } }; }, YesPushDown: function YesPushDown(t) { var e = new _(t), n = [], r = m.internal.getFont(t.fontName, t.fontStyle).id, i = m.__private__.encodeColorString(t.color), a = O(t, t.caption); return n.push("0.749023 g"), n.push("0 0 " + N(ut.internal.getWidth(t)) + " " + N(ut.internal.getHeight(t)) + " re"), n.push("f"), n.push("BMC"), n.push("q"), n.push("0 0 1 rg"), n.push("/" + r + " " + N(a.fontSize) + " Tf " + i), n.push("BT"), n.push(a.text), n.push("ET"), n.push("Q"), n.push("EMC"), e.stream = n.join("\n"), e; }, YesNormal: function YesNormal(t) { var e = new _(t), n = m.internal.getFont(t.fontName, t.fontStyle).id, r = m.__private__.encodeColorString(t.color), i = [], a = ut.internal.getHeight(t), o = ut.internal.getWidth(t), s = O(t, t.caption); return i.push("1 g"), i.push("0 0 " + N(o) + " " + N(a) + " re"), i.push("f"), i.push("q"), i.push("0 0 1 rg"), i.push("0 0 " + N(o - 1) + " " + N(a - 1) + " re"), i.push("W"), i.push("n"), i.push("0 g"), i.push("BT"), i.push("/" + n + " " + N(s.fontSize) + " Tf " + r), i.push(s.text), i.push("ET"), i.push("Q"), e.stream = i.join("\n"), e; }, OffPushDown: function OffPushDown(t) { var e = new _(t), n = []; return n.push("0.749023 g"), n.push("0 0 " + N(ut.internal.getWidth(t)) + " " + N(ut.internal.getHeight(t)) + " re"), n.push("f"), e.stream = n.join("\n"), e; } }, RadioButton: { Circle: { createAppearanceStream: function createAppearanceStream(t) { var e = { D: { Off: ut.RadioButton.Circle.OffPushDown }, N: {} }; return e.N[t] = ut.RadioButton.Circle.YesNormal, e.D[t] = ut.RadioButton.Circle.YesPushDown, e; }, getCA: function getCA() { return "l"; }, YesNormal: function YesNormal(t) { var e = new _(t), n = [], r = ut.internal.getWidth(t) <= ut.internal.getHeight(t) ? ut.internal.getWidth(t) / 4 : ut.internal.getHeight(t) / 4; r = Number((.9 * r).toFixed(5)); var i = ut.internal.Bezier_C, a = Number((r * i).toFixed(5)); return n.push("q"), n.push("1 0 0 1 " + L(ut.internal.getWidth(t) / 2) + " " + L(ut.internal.getHeight(t) / 2) + " cm"), n.push(r + " 0 m"), n.push(r + " " + a + " " + a + " " + r + " 0 " + r + " c"), n.push("-" + a + " " + r + " -" + r + " " + a + " -" + r + " 0 c"), n.push("-" + r + " -" + a + " -" + a + " -" + r + " 0 -" + r + " c"), n.push(a + " -" + r + " " + r + " -" + a + " " + r + " 0 c"), n.push("f"), n.push("Q"), e.stream = n.join("\n"), e; }, YesPushDown: function YesPushDown(t) { var e = new _(t), n = [], r = ut.internal.getWidth(t) <= ut.internal.getHeight(t) ? ut.internal.getWidth(t) / 4 : ut.internal.getHeight(t) / 4, i = (r = Number((.9 * r).toFixed(5)), Number((2 * r).toFixed(5))), a = Number((i * ut.internal.Bezier_C).toFixed(5)), o = Number((r * ut.internal.Bezier_C).toFixed(5)); return n.push("0.749023 g"), n.push("q"), n.push("1 0 0 1 " + L(ut.internal.getWidth(t) / 2) + " " + L(ut.internal.getHeight(t) / 2) + " cm"), n.push(i + " 0 m"), n.push(i + " " + a + " " + a + " " + i + " 0 " + i + " c"), n.push("-" + a + " " + i + " -" + i + " " + a + " -" + i + " 0 c"), n.push("-" + i + " -" + a + " -" + a + " -" + i + " 0 -" + i + " c"), n.push(a + " -" + i + " " + i + " -" + a + " " + i + " 0 c"), n.push("f"), n.push("Q"), n.push("0 g"), n.push("q"), n.push("1 0 0 1 " + L(ut.internal.getWidth(t) / 2) + " " + L(ut.internal.getHeight(t) / 2) + " cm"), n.push(r + " 0 m"), n.push(r + " " + o + " " + o + " " + r + " 0 " + r + " c"), n.push("-" + o + " " + r + " -" + r + " " + o + " -" + r + " 0 c"), n.push("-" + r + " -" + o + " -" + o + " -" + r + " 0 -" + r + " c"), n.push(o + " -" + r + " " + r + " -" + o + " " + r + " 0 c"), n.push("f"), n.push("Q"), e.stream = n.join("\n"), e; }, OffPushDown: function OffPushDown(t) { var e = new _(t), n = [], r = ut.internal.getWidth(t) <= ut.internal.getHeight(t) ? ut.internal.getWidth(t) / 4 : ut.internal.getHeight(t) / 4; r = Number((.9 * r).toFixed(5)); var i = Number((2 * r).toFixed(5)), a = Number((i * ut.internal.Bezier_C).toFixed(5)); return n.push("0.749023 g"), n.push("q"), n.push("1 0 0 1 " + L(ut.internal.getWidth(t) / 2) + " " + L(ut.internal.getHeight(t) / 2) + " cm"), n.push(i + " 0 m"), n.push(i + " " + a + " " + a + " " + i + " 0 " + i + " c"), n.push("-" + a + " " + i + " -" + i + " " + a + " -" + i + " 0 c"), n.push("-" + i + " -" + a + " -" + a + " -" + i + " 0 -" + i + " c"), n.push(a + " -" + i + " " + i + " -" + a + " " + i + " 0 c"), n.push("f"), n.push("Q"), e.stream = n.join("\n"), e; } }, Cross: { createAppearanceStream: function createAppearanceStream(t) { var e = { D: { Off: ut.RadioButton.Cross.OffPushDown }, N: {} }; return e.N[t] = ut.RadioButton.Cross.YesNormal, e.D[t] = ut.RadioButton.Cross.YesPushDown, e; }, getCA: function getCA() { return "8"; }, YesNormal: function YesNormal(t) { var e = new _(t), n = [], r = ut.internal.calculateCross(t); return n.push("q"), n.push("1 1 " + N(ut.internal.getWidth(t) - 2) + " " + N(ut.internal.getHeight(t) - 2) + " re"), n.push("W"), n.push("n"), n.push(N(r.x1.x) + " " + N(r.x1.y) + " m"), n.push(N(r.x2.x) + " " + N(r.x2.y) + " l"), n.push(N(r.x4.x) + " " + N(r.x4.y) + " m"), n.push(N(r.x3.x) + " " + N(r.x3.y) + " l"), n.push("s"), n.push("Q"), e.stream = n.join("\n"), e; }, YesPushDown: function YesPushDown(t) { var e = new _(t), n = ut.internal.calculateCross(t), r = []; return r.push("0.749023 g"), r.push("0 0 " + N(ut.internal.getWidth(t)) + " " + N(ut.internal.getHeight(t)) + " re"), r.push("f"), r.push("q"), r.push("1 1 " + N(ut.internal.getWidth(t) - 2) + " " + N(ut.internal.getHeight(t) - 2) + " re"), r.push("W"), r.push("n"), r.push(N(n.x1.x) + " " + N(n.x1.y) + " m"), r.push(N(n.x2.x) + " " + N(n.x2.y) + " l"), r.push(N(n.x4.x) + " " + N(n.x4.y) + " m"), r.push(N(n.x3.x) + " " + N(n.x3.y) + " l"), r.push("s"), r.push("Q"), e.stream = r.join("\n"), e; }, OffPushDown: function OffPushDown(t) { var e = new _(t), n = []; return n.push("0.749023 g"), n.push("0 0 " + N(ut.internal.getWidth(t)) + " " + N(ut.internal.getHeight(t)) + " re"), n.push("f"), e.stream = n.join("\n"), e; } } }, createDefaultAppearanceStream: function createDefaultAppearanceStream(t) { var e = m.internal.getFont(t.fontName, t.fontStyle).id, n = m.__private__.encodeColorString(t.color); return "/" + e + " " + t.fontSize + " Tf " + n; } }; ut.internal = { Bezier_C: .551915024494, calculateCross: function calculateCross(t) { var e = ut.internal.getWidth(t), n = ut.internal.getHeight(t), r = Math.min(e, n); return { x1: { x: (e - r) / 2, y: (n - r) / 2 + r }, x2: { x: (e - r) / 2 + r, y: (n - r) / 2 }, x3: { x: (e - r) / 2, y: (n - r) / 2 }, x4: { x: (e - r) / 2 + r, y: (n - r) / 2 + r } }; } }, ut.internal.getWidth = function (t) { var e = 0; return "object" == _typeof(t) && (e = A(t.Rect[2])), e; }, ut.internal.getHeight = function (t) { var e = 0; return "object" == _typeof(t) && (e = A(t.Rect[3])), e; }; var ct = v.addField = function (t) { if (W.call(this), !(t instanceof K)) throw new Error("Invalid argument passed to jsPDF.addField."); return R.call(this, t), t.page = m.internal.getCurrentPageInfo().pageNumber, this; }; v.AcroFormChoiceField = Z, v.AcroFormListBox = $$3, v.AcroFormComboBox = Q, v.AcroFormEditBox = tt, v.AcroFormButton = et, v.AcroFormPushButton = nt, v.AcroFormRadioButton = rt, v.AcroFormCheckBox = at, v.AcroFormTextField = ot, v.AcroFormPasswordField = st, v.AcroFormAppearance = ut, v.AcroForm = { ChoiceField: Z, ListBox: $$3, ComboBox: Q, EditBox: tt, Button: et, PushButton: nt, RadioButton: rt, CheckBox: at, TextField: ot, PasswordField: st, Appearance: ut }, g.AcroForm = { ChoiceField: Z, ListBox: $$3, ComboBox: Q, EditBox: tt, Button: et, PushButton: nt, RadioButton: rt, CheckBox: at, TextField: ot, PasswordField: st, Appearance: ut }; /** @license * jsPDF addImage plugin * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/ * 2013 Chris Dowling, https://github.com/gingerchris * 2013 Trinh Ho, https://github.com/ineedfat * 2013 Edwin Alejandro Perez, https://github.com/eaparango * 2013 Norah Smith, https://github.com/burnburnrocket * 2014 Diego Casorran, https://github.com/diegocr * 2014 James Robb, https://github.com/jamesbrobb * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ !function (t) { t.__addimage__ = {}; var e = "UNKNOWN", n = { PNG: [[137, 80, 78, 71]], TIFF: [[77, 77, 0, 42], [73, 73, 42, 0]], JPEG: [[255, 216, 255, 224, void 0, void 0, 74, 70, 73, 70, 0], [255, 216, 255, 225, void 0, void 0, 69, 120, 105, 102, 0, 0], [255, 216, 255, 219], [255, 216, 255, 238]], JPEG2000: [[0, 0, 0, 12, 106, 80, 32, 32]], GIF87a: [[71, 73, 70, 56, 55, 97]], GIF89a: [[71, 73, 70, 56, 57, 97]], WEBP: [[82, 73, 70, 70, void 0, void 0, void 0, void 0, 87, 69, 66, 80]], BMP: [[66, 77], [66, 65], [67, 73], [67, 80], [73, 67], [80, 84]] }, r = t.__addimage__.getImageFileTypeByImageData = function (t, r) { var i, a; r = r || e; var o, s, u, c = e; if (A(t)) for (u in n) { for (o = n[u], i = 0; i < o.length; i += 1) { for (s = !0, a = 0; a < o[i].length; a += 1) { if (void 0 !== o[i][a] && o[i][a] !== t[a]) { s = !1; break; } } if (!0 === s) { c = u; break; } } } else for (u in n) { for (o = n[u], i = 0; i < o.length; i += 1) { for (s = !0, a = 0; a < o[i].length; a += 1) { if (void 0 !== o[i][a] && o[i][a] !== t.charCodeAt(a)) { s = !1; break; } } if (!0 === s) { c = u; break; } } } return c === e && r !== e && (c = r), c; }, i = function i(t) { for (var e = this.internal.write, n = this.internal.putStream, r = (0, this.internal.getFilters)(); -1 !== r.indexOf("FlateEncode");) { r.splice(r.indexOf("FlateEncode"), 1); } t.objectId = this.internal.newObject(); var a = []; if (a.push({ key: "Type", value: "/XObject" }), a.push({ key: "Subtype", value: "/Image" }), a.push({ key: "Width", value: t.width }), a.push({ key: "Height", value: t.height }), t.colorSpace === b.INDEXED ? a.push({ key: "ColorSpace", value: "[/Indexed /DeviceRGB " + (t.palette.length / 3 - 1) + " " + ("sMask" in t && void 0 !== t.sMask ? t.objectId + 2 : t.objectId + 1) + " 0 R]" }) : (a.push({ key: "ColorSpace", value: "/" + t.colorSpace }), t.colorSpace === b.DEVICE_CMYK && a.push({ key: "Decode", value: "[1 0 1 0 1 0 1 0]" })), a.push({ key: "BitsPerComponent", value: t.bitsPerComponent }), "decodeParameters" in t && void 0 !== t.decodeParameters && a.push({ key: "DecodeParms", value: "<<" + t.decodeParameters + ">>" }), "transparency" in t && Array.isArray(t.transparency)) { for (var o = "", s = 0, u = t.transparency.length; s < u; s++) { o += t.transparency[s] + " " + t.transparency[s] + " "; } a.push({ key: "Mask", value: "[" + o + "]" }); } void 0 !== t.sMask && a.push({ key: "SMask", value: t.objectId + 1 + " 0 R" }); var c = void 0 !== t.filter ? ["/" + t.filter] : void 0; if (n({ data: t.data, additionalKeyValues: a, alreadyAppliedFilters: c }), e("endobj"), "sMask" in t && void 0 !== t.sMask) { var h = "/Predictor " + t.predictor + " /Colors 1 /BitsPerComponent " + t.bitsPerComponent + " /Columns " + t.width, l = { width: t.width, height: t.height, colorSpace: "DeviceGray", bitsPerComponent: t.bitsPerComponent, decodeParameters: h, data: t.sMask }; "filter" in t && (l.filter = t.filter), i.call(this, l); } t.colorSpace === b.INDEXED && (this.internal.newObject(), n({ data: S(new Uint8Array(t.palette)) }), e("endobj")); }, a = function a() { var t = this.internal.collections.addImage_images; for (var e in t) { i.call(this, t[e]); } }, u = function u() { var t, e = this.internal.collections.addImage_images, n = this.internal.write; for (var r in e) { n("/I" + (t = e[r]).index, t.objectId, "0", "R"); } }, c = function c() { this.internal.collections.addImage_images || (this.internal.collections.addImage_images = {}, this.internal.events.subscribe("putResources", a), this.internal.events.subscribe("putXobjectDict", u)); }, h = function h() { var t = this.internal.collections.addImage_images; return c.call(this), t; }, l = function l() { return Object.keys(this.internal.collections.addImage_images).length; }, f = function f(e) { return "function" == typeof t["process" + e.toUpperCase()]; }, d = function d(t) { return "object" == _typeof(t) && 1 === t.nodeType; }, p = function p(e, n) { if ("IMG" === e.nodeName && e.hasAttribute("src")) { var r = "" + e.getAttribute("src"); if (0 === r.indexOf("data:image/")) return o(unescape(r).split("base64,").pop()); var i = t.loadFile(r, !0); if (void 0 !== i) return i; } if ("CANVAS" === e.nodeName) { var a; switch (n) { case "PNG": a = "image/png"; break; case "WEBP": a = "image/webp"; break; case "JPEG": case "JPG": default: a = "image/jpeg"; } return o(e.toDataURL(a, 1).split("base64,").pop()); } }, g = function g(t) { var e = this.internal.collections.addImage_images; if (e) for (var n in e) { if (t === e[n].alias) return e[n]; } }, m = function m(t, e, n) { return t || e || (t = -96, e = -96), t < 0 && (t = -1 * n.width * 72 / t / this.internal.scaleFactor), e < 0 && (e = -1 * n.height * 72 / e / this.internal.scaleFactor), 0 === t && (t = e * n.width / n.height), 0 === e && (e = t * n.height / n.width), [t, e]; }, v = function v(t, e, n, r, i, a) { var o = m.call(this, n, r, i), s = this.internal.getCoordinateString, u = this.internal.getVerticalCoordinateString, c = h.call(this); if (n = o[0], r = o[1], c[i.index] = i, a) { a *= Math.PI / 180; var l = Math.cos(a), f = Math.sin(a), d = function d(t) { return t.toFixed(4); }, p = [d(l), d(f), d(-1 * f), d(l), 0, 0, "cm"]; } this.internal.write("q"), a ? (this.internal.write([1, "0", "0", 1, s(t), u(e + r), "cm"].join(" ")), this.internal.write(p.join(" ")), this.internal.write([s(n), "0", "0", s(r), "0", "0", "cm"].join(" "))) : this.internal.write([s(n), "0", "0", s(r), s(t), u(e + r), "cm"].join(" ")), this.isAdvancedAPI() && this.internal.write([1, 0, 0, -1, 0, 0, "cm"].join(" ")), this.internal.write("/I" + i.index + " Do"), this.internal.write("Q"); }, b = t.color_spaces = { DEVICE_RGB: "DeviceRGB", DEVICE_GRAY: "DeviceGray", DEVICE_CMYK: "DeviceCMYK", CAL_GREY: "CalGray", CAL_RGB: "CalRGB", LAB: "Lab", ICC_BASED: "ICCBased", INDEXED: "Indexed", PATTERN: "Pattern", SEPARATION: "Separation", DEVICE_N: "DeviceN" }; t.decode = { DCT_DECODE: "DCTDecode", FLATE_DECODE: "FlateDecode", LZW_DECODE: "LZWDecode", JPX_DECODE: "JPXDecode", JBIG2_DECODE: "JBIG2Decode", ASCII85_DECODE: "ASCII85Decode", ASCII_HEX_DECODE: "ASCIIHexDecode", RUN_LENGTH_DECODE: "RunLengthDecode", CCITT_FAX_DECODE: "CCITTFaxDecode" }; var y = t.image_compression = { NONE: "NONE", FAST: "FAST", MEDIUM: "MEDIUM", SLOW: "SLOW" }, w = t.__addimage__.sHashCode = function (t) { var e, n, r = 0; if ("string" == typeof t) for (n = t.length, e = 0; e < n; e++) { r = (r << 5) - r + t.charCodeAt(e), r |= 0; } else if (A(t)) for (n = t.byteLength / 2, e = 0; e < n; e++) { r = (r << 5) - r + t[e], r |= 0; } return r; }, N = t.__addimage__.validateStringAsBase64 = function (t) { (t = t || "").toString().trim(); var e = !0; return 0 === t.length && (e = !1), t.length % 4 != 0 && (e = !1), !1 === /^[A-Za-z0-9+/]+$/.test(t.substr(0, t.length - 2)) && (e = !1), !1 === /^[A-Za-z0-9/][A-Za-z0-9+/]|[A-Za-z0-9+/]=|==$/.test(t.substr(-2)) && (e = !1), e; }, L = t.__addimage__.extractImageFromDataUrl = function (t) { var e = (t = t || "").split("base64,"), n = null; if (2 === e.length) { var r = /^data:(\w*\/\w*);*(charset=[\w=-]*)*;*$/.exec(e[0]); Array.isArray(r) && (n = { mimeType: r[1], charset: r[2], data: e[1] }); } return n; }, x = t.__addimage__.supportsArrayBuffer = function () { return "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array; }; t.__addimage__.isArrayBuffer = function (t) { return x() && t instanceof ArrayBuffer; }; var A = t.__addimage__.isArrayBufferView = function (t) { return x() && "undefined" != typeof Uint32Array && (t instanceof Int8Array || t instanceof Uint8Array || "undefined" != typeof Uint8ClampedArray && t instanceof Uint8ClampedArray || t instanceof Int16Array || t instanceof Uint16Array || t instanceof Int32Array || t instanceof Uint32Array || t instanceof Float32Array || t instanceof Float64Array); }, _ = t.__addimage__.binaryStringToUint8Array = function (t) { for (var e = t.length, n = new Uint8Array(e), r = 0; r < e; r++) { n[r] = t.charCodeAt(r); } return n; }, S = t.__addimage__.arrayBufferToBinaryString = function (t) { try { return o(s(String.fromCharCode.apply(null, t))); } catch (e) { if ("undefined" != typeof Uint8Array && void 0 !== Uint8Array.prototype.reduce) return new Uint8Array(t).reduce(function (t, e) { return t.push(String.fromCharCode(e)), t; }, []).join(""); } }; t.addImage = function () { var t, n, r, i, a, o, s, u, h; if ("number" == typeof arguments[1] ? (n = e, r = arguments[1], i = arguments[2], a = arguments[3], o = arguments[4], s = arguments[5], u = arguments[6], h = arguments[7]) : (n = arguments[1], r = arguments[2], i = arguments[3], a = arguments[4], o = arguments[5], s = arguments[6], u = arguments[7], h = arguments[8]), "object" == _typeof(t = arguments[0]) && !d(t) && "imageData" in t) { var l = t; t = l.imageData, n = l.format || n || e, r = l.x || r || 0, i = l.y || i || 0, a = l.w || l.width || a, o = l.h || l.height || o, s = l.alias || s, u = l.compression || u, h = l.rotation || l.angle || h; } var f = this.internal.getFilters(); if (void 0 === u && -1 !== f.indexOf("FlateEncode") && (u = "SLOW"), isNaN(r) || isNaN(i)) throw new Error("Invalid coordinates passed to jsPDF.addImage"); c.call(this); var p = P.call(this, t, n, s, u); return v.call(this, r, i, a, o, p, h), this; }; var P = function P(n, i, a, o) { var s, u, c; if ("string" == typeof n && r(n) === e) { n = unescape(n); var h = k(n, !1); ("" !== h || void 0 !== (h = t.loadFile(n, !0))) && (n = h); } if (d(n) && (n = p(n, i)), i = r(n, i), !f(i)) throw new Error("addImage does not support files of type '" + i + "', please ensure that a plugin for '" + i + "' support is added."); if ((null == (c = a) || 0 === c.length) && (a = function (t) { return "string" == typeof t || A(t) ? w(t) : null; }(n)), (s = g.call(this, a)) || (x() && (n instanceof Uint8Array || (u = n, n = _(n))), s = this["process" + i.toUpperCase()](n, l.call(this), a, function (e) { return e && "string" == typeof e && (e = e.toUpperCase()), e in t.image_compression ? e : y.NONE; }(o), u)), !s) throw new Error("An unknown error occurred whilst processing the image."); return s; }, k = t.__addimage__.convertBase64ToBinaryString = function (t, e) { var n; e = "boolean" != typeof e || e; var r, i = ""; if ("string" == typeof t) { r = null !== (n = L(t)) ? n.data : t; try { i = o(r); } catch (t) { if (e) throw N(r) ? new Error("atob-Error in jsPDF.convertBase64ToBinaryString " + t.message) : new Error("Supplied Data is not a valid base64-String jsPDF.convertBase64ToBinaryString "); } } return i; }; t.getImageProperties = function (n) { var i, a, o = ""; if (d(n) && (n = p(n)), "string" == typeof n && r(n) === e && ("" === (o = k(n, !1)) && (o = t.loadFile(n) || ""), n = o), a = r(n), !f(a)) throw new Error("addImage does not support files of type '" + a + "', please ensure that a plugin for '" + a + "' support is added."); if (!x() || n instanceof Uint8Array || (n = _(n)), !(i = this["process" + a.toUpperCase()](n))) throw new Error("An unknown error occurred whilst processing the image"); return i.fileType = a, i; }; }(g.API), /** * @license * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { var e = function e(t) { if (void 0 !== t && "" != t) return !0; }; g.API.events.push(["addPage", function (t) { this.internal.getPageInfo(t.pageNumber).pageContext.annotations = []; }]), t.events.push(["putPage", function (t) { for (var n, r, i, a = this.internal.getCoordinateString, o = this.internal.getVerticalCoordinateString, s = this.internal.getPageInfoByObjId(t.objId), u = t.pageContext.annotations, c = !1, h = 0; h < u.length && !c; h++) { switch ((n = u[h]).type) { case "link": (e(n.options.url) || e(n.options.pageNumber)) && (c = !0); break; case "reference": case "text": case "freetext": c = !0; } } if (0 != c) { this.internal.write("/Annots ["); for (var l = 0; l < u.length; l++) { switch ((n = u[l]).type) { case "reference": this.internal.write(" " + n.object.objId + " 0 R "); break; case "text": var f = this.internal.newAdditionalObject(), d = this.internal.newAdditionalObject(), p = n.title || "Note"; i = "<</Type /Annot /Subtype /Text " + (r = "/Rect [" + a(n.bounds.x) + " " + o(n.bounds.y + n.bounds.h) + " " + a(n.bounds.x + n.bounds.w) + " " + o(n.bounds.y) + "] ") + "/Contents (" + n.contents + ")", i += " /Popup " + d.objId + " 0 R", i += " /P " + s.objId + " 0 R", i += " /T (" + p + ") >>", f.content = i; var g = f.objId + " 0 R"; i = "<</Type /Annot /Subtype /Popup " + (r = "/Rect [" + a(n.bounds.x + 30) + " " + o(n.bounds.y + n.bounds.h) + " " + a(n.bounds.x + n.bounds.w + 30) + " " + o(n.bounds.y) + "] ") + " /Parent " + g, n.open && (i += " /Open true"), i += " >>", d.content = i, this.internal.write(f.objId, "0 R", d.objId, "0 R"); break; case "freetext": r = "/Rect [" + a(n.bounds.x) + " " + o(n.bounds.y) + " " + a(n.bounds.x + n.bounds.w) + " " + o(n.bounds.y + n.bounds.h) + "] "; var m = n.color || "#000000"; i = "<</Type /Annot /Subtype /FreeText " + r + "/Contents (" + n.contents + ")", i += " /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#" + m + ")", i += " /Border [0 0 0]", i += " >>", this.internal.write(i); break; case "link": if (n.options.name) { var v = this.annotations._nameMap[n.options.name]; n.options.pageNumber = v.page, n.options.top = v.y; } else n.options.top || (n.options.top = 0); if (r = "/Rect [" + a(n.x) + " " + o(n.y) + " " + a(n.x + n.w) + " " + o(n.y + n.h) + "] ", i = "", n.options.url) i = "<</Type /Annot /Subtype /Link " + r + "/Border [0 0 0] /A <</S /URI /URI (" + n.options.url + ") >>";else if (n.options.pageNumber) { switch (i = "<</Type /Annot /Subtype /Link " + r + "/Border [0 0 0] /Dest [" + this.internal.getPageInfo(n.options.pageNumber).objId + " 0 R", n.options.magFactor = n.options.magFactor || "XYZ", n.options.magFactor) { case "Fit": i += " /Fit]"; break; case "FitH": i += " /FitH " + n.options.top + "]"; break; case "FitV": n.options.left = n.options.left || 0, i += " /FitV " + n.options.left + "]"; break; case "XYZ": default: var b = o(n.options.top); n.options.left = n.options.left || 0, void 0 === n.options.zoom && (n.options.zoom = 0), i += " /XYZ " + n.options.left + " " + b + " " + n.options.zoom + "]"; } } "" != i && (i += " >>", this.internal.write(i)); } } this.internal.write("]"); } }]), t.createAnnotation = function (t) { var e = this.internal.getCurrentPageInfo(); switch (t.type) { case "link": this.link(t.bounds.x, t.bounds.y, t.bounds.w, t.bounds.h, t); break; case "text": case "freetext": e.pageContext.annotations.push(t); } }, t.link = function (t, e, n, r, i) { this.internal.getCurrentPageInfo().pageContext.annotations.push({ x: t, y: e, w: n, h: r, options: i, type: "link" }); }, t.textWithLink = function (t, e, n, r) { var i = this.getTextWidth(t), a = this.internal.getLineHeight() / this.internal.scaleFactor; return this.text(t, e, n, r), n += .2 * a, this.link(e, n - a, i, a, r), i; }, t.getTextWidth = function (t) { var e = this.internal.getFontSize(); return this.getStringUnitWidth(t) * e / this.internal.scaleFactor; }; }(g.API), /** * @license * Copyright (c) 2017 Aras Abbasi * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { var e = { 1569: [65152], 1570: [65153, 65154], 1571: [65155, 65156], 1572: [65157, 65158], 1573: [65159, 65160], 1574: [65161, 65162, 65163, 65164], 1575: [65165, 65166], 1576: [65167, 65168, 65169, 65170], 1577: [65171, 65172], 1578: [65173, 65174, 65175, 65176], 1579: [65177, 65178, 65179, 65180], 1580: [65181, 65182, 65183, 65184], 1581: [65185, 65186, 65187, 65188], 1582: [65189, 65190, 65191, 65192], 1583: [65193, 65194], 1584: [65195, 65196], 1585: [65197, 65198], 1586: [65199, 65200], 1587: [65201, 65202, 65203, 65204], 1588: [65205, 65206, 65207, 65208], 1589: [65209, 65210, 65211, 65212], 1590: [65213, 65214, 65215, 65216], 1591: [65217, 65218, 65219, 65220], 1592: [65221, 65222, 65223, 65224], 1593: [65225, 65226, 65227, 65228], 1594: [65229, 65230, 65231, 65232], 1601: [65233, 65234, 65235, 65236], 1602: [65237, 65238, 65239, 65240], 1603: [65241, 65242, 65243, 65244], 1604: [65245, 65246, 65247, 65248], 1605: [65249, 65250, 65251, 65252], 1606: [65253, 65254, 65255, 65256], 1607: [65257, 65258, 65259, 65260], 1608: [65261, 65262], 1609: [65263, 65264, 64488, 64489], 1610: [65265, 65266, 65267, 65268], 1649: [64336, 64337], 1655: [64477], 1657: [64358, 64359, 64360, 64361], 1658: [64350, 64351, 64352, 64353], 1659: [64338, 64339, 64340, 64341], 1662: [64342, 64343, 64344, 64345], 1663: [64354, 64355, 64356, 64357], 1664: [64346, 64347, 64348, 64349], 1667: [64374, 64375, 64376, 64377], 1668: [64370, 64371, 64372, 64373], 1670: [64378, 64379, 64380, 64381], 1671: [64382, 64383, 64384, 64385], 1672: [64392, 64393], 1676: [64388, 64389], 1677: [64386, 64387], 1678: [64390, 64391], 1681: [64396, 64397], 1688: [64394, 64395], 1700: [64362, 64363, 64364, 64365], 1702: [64366, 64367, 64368, 64369], 1705: [64398, 64399, 64400, 64401], 1709: [64467, 64468, 64469, 64470], 1711: [64402, 64403, 64404, 64405], 1713: [64410, 64411, 64412, 64413], 1715: [64406, 64407, 64408, 64409], 1722: [64414, 64415], 1723: [64416, 64417, 64418, 64419], 1726: [64426, 64427, 64428, 64429], 1728: [64420, 64421], 1729: [64422, 64423, 64424, 64425], 1733: [64480, 64481], 1734: [64473, 64474], 1735: [64471, 64472], 1736: [64475, 64476], 1737: [64482, 64483], 1739: [64478, 64479], 1740: [64508, 64509, 64510, 64511], 1744: [64484, 64485, 64486, 64487], 1746: [64430, 64431], 1747: [64432, 64433] }, n = { 65247: { 65154: 65269, 65156: 65271, 65160: 65273, 65166: 65275 }, 65248: { 65154: 65270, 65156: 65272, 65160: 65274, 65166: 65276 }, 65165: { 65247: { 65248: { 65258: 65010 } } }, 1617: { 1612: 64606, 1613: 64607, 1614: 64608, 1615: 64609, 1616: 64610 } }, r = { 1612: 64606, 1613: 64607, 1614: 64608, 1615: 64609, 1616: 64610 }, i = [1570, 1571, 1573, 1575]; t.__arabicParser__ = {}; var a = t.__arabicParser__.isInArabicSubstitutionA = function (t) { return void 0 !== e[t.charCodeAt(0)]; }, o = t.__arabicParser__.isArabicLetter = function (t) { return "string" == typeof t && /^[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]+$/.test(t); }, s = t.__arabicParser__.isArabicEndLetter = function (t) { return o(t) && a(t) && e[t.charCodeAt(0)].length <= 2; }, u = t.__arabicParser__.isArabicAlfLetter = function (t) { return o(t) && i.indexOf(t.charCodeAt(0)) >= 0; }; t.__arabicParser__.arabicLetterHasIsolatedForm = function (t) { return o(t) && a(t) && e[t.charCodeAt(0)].length >= 1; }; var c = t.__arabicParser__.arabicLetterHasFinalForm = function (t) { return o(t) && a(t) && e[t.charCodeAt(0)].length >= 2; }; t.__arabicParser__.arabicLetterHasInitialForm = function (t) { return o(t) && a(t) && e[t.charCodeAt(0)].length >= 3; }; var h = t.__arabicParser__.arabicLetterHasMedialForm = function (t) { return o(t) && a(t) && 4 == e[t.charCodeAt(0)].length; }, l = t.__arabicParser__.resolveLigatures = function (t) { var e = 0, r = n, i = "", a = 0; for (e = 0; e < t.length; e += 1) { void 0 !== r[t.charCodeAt(e)] ? (a++, "number" == typeof (r = r[t.charCodeAt(e)]) && (i += String.fromCharCode(r), r = n, a = 0), e === t.length - 1 && (r = n, i += t.charAt(e - (a - 1)), e -= a - 1, a = 0)) : (r = n, i += t.charAt(e - a), e -= a, a = 0); } return i; }; t.__arabicParser__.isArabicDiacritic = function (t) { return void 0 !== t && void 0 !== r[t.charCodeAt(0)]; }; var f = t.__arabicParser__.getCorrectForm = function (t, e, n) { return o(t) ? !1 === a(t) ? -1 : !c(t) || !o(e) && !o(n) || !o(n) && s(e) || s(t) && !o(e) || s(t) && u(e) || s(t) && s(e) ? 0 : h(t) && o(e) && !s(e) && o(n) && c(n) ? 3 : s(t) || !o(n) ? 1 : 2 : -1; }, d = function d(t) { var n = 0, r = 0, i = 0, a = "", s = "", u = "", c = (t = t || "").split("\\s+"), h = []; for (n = 0; n < c.length; n += 1) { for (h.push(""), r = 0; r < c[n].length; r += 1) { a = c[n][r], s = c[n][r - 1], u = c[n][r + 1], o(a) ? (i = f(a, s, u), h[n] += -1 !== i ? String.fromCharCode(e[a.charCodeAt(0)][i]) : a) : h[n] += a; } h[n] = l(h[n]); } return h.join(" "); }, p = t.__arabicParser__.processArabic = t.processArabic = function () { var t, e = "string" == typeof arguments[0] ? arguments[0] : arguments[0].text, n = []; if (Array.isArray(e)) { var r = 0; for (n = [], r = 0; r < e.length; r += 1) { Array.isArray(e[r]) ? n.push([d(e[r][0]), e[r][1], e[r][2]]) : n.push([d(e[r])]); } t = n; } else t = d(e); return "string" == typeof arguments[0] ? t : (arguments[0].text = t, arguments[0]); }; t.events.push(["preProcessText", p]); }(g.API), g.API.autoPrint = function (t) { var e; switch ((t = t || {}).variant = t.variant || "non-conform", t.variant) { case "javascript": this.addJS("print({});"); break; case "non-conform": default: this.internal.events.subscribe("postPutResources", function () { e = this.internal.newObject(), this.internal.out("<<"), this.internal.out("/S /Named"), this.internal.out("/Type /Action"), this.internal.out("/N /Print"), this.internal.out(">>"), this.internal.out("endobj"); }), this.internal.events.subscribe("putCatalog", function () { this.internal.out("/OpenAction " + e + " 0 R"); }); } return this; }, /** * @license * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { var e = function e() { var t = void 0; Object.defineProperty(this, "pdf", { get: function get() { return t; }, set: function set(e) { t = e; } }); var e = 150; Object.defineProperty(this, "width", { get: function get() { return e; }, set: function set(t) { e = isNaN(t) || !1 === Number.isInteger(t) || t < 0 ? 150 : t, this.getContext("2d").pageWrapXEnabled && (this.getContext("2d").pageWrapX = e + 1); } }); var n = 300; Object.defineProperty(this, "height", { get: function get() { return n; }, set: function set(t) { n = isNaN(t) || !1 === Number.isInteger(t) || t < 0 ? 300 : t, this.getContext("2d").pageWrapYEnabled && (this.getContext("2d").pageWrapY = n + 1); } }); var r = []; Object.defineProperty(this, "childNodes", { get: function get() { return r; }, set: function set(t) { r = t; } }); var i = {}; Object.defineProperty(this, "style", { get: function get() { return i; }, set: function set(t) { i = t; } }), Object.defineProperty(this, "parentNode", {}); }; e.prototype.getContext = function (t, e) { var n; if ("2d" !== (t = t || "2d")) return null; for (n in e) { this.pdf.context2d.hasOwnProperty(n) && (this.pdf.context2d[n] = e[n]); } return this.pdf.context2d._canvas = this, this.pdf.context2d; }, e.prototype.toDataURL = function () { throw new Error("toDataURL is not implemented."); }, t.events.push(["initialized", function () { this.canvas = new e(), this.canvas.pdf = this; }]); }(g.API), /** * @license * ==================================================================== * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br * 2013 Lee Driscoll, https://github.com/lsdriscoll * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria * 2014 James Hall, james@parall.ax * 2014 Diego Casorran, https://github.com/diegocr * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ==================================================================== */ function (t) { var e = { left: 0, top: 0, bottom: 0, right: 0 }, n = !1, r = function r() { void 0 === this.internal.__cell__ && (this.internal.__cell__ = {}, this.internal.__cell__.padding = 3, this.internal.__cell__.headerFunction = void 0, this.internal.__cell__.margins = Object.assign({}, e), this.internal.__cell__.margins.width = this.getPageWidth(), i.call(this)); }, i = function i() { this.internal.__cell__.lastCell = new a(), this.internal.__cell__.pages = 1; }, a = function a() { var t = arguments[0]; Object.defineProperty(this, "x", { enumerable: !0, get: function get() { return t; }, set: function set(e) { t = e; } }); var e = arguments[1]; Object.defineProperty(this, "y", { enumerable: !0, get: function get() { return e; }, set: function set(t) { e = t; } }); var n = arguments[2]; Object.defineProperty(this, "width", { enumerable: !0, get: function get() { return n; }, set: function set(t) { n = t; } }); var r = arguments[3]; Object.defineProperty(this, "height", { enumerable: !0, get: function get() { return r; }, set: function set(t) { r = t; } }); var i = arguments[4]; Object.defineProperty(this, "text", { enumerable: !0, get: function get() { return i; }, set: function set(t) { i = t; } }); var a = arguments[5]; Object.defineProperty(this, "lineNumber", { enumerable: !0, get: function get() { return a; }, set: function set(t) { a = t; } }); var o = arguments[6]; return Object.defineProperty(this, "align", { enumerable: !0, get: function get() { return o; }, set: function set(t) { o = t; } }), this; }; a.prototype.clone = function () { return new a(this.x, this.y, this.width, this.height, this.text, this.lineNumber, this.align); }, a.prototype.toArray = function () { return [this.x, this.y, this.width, this.height, this.text, this.lineNumber, this.align]; }, t.setHeaderFunction = function (t) { return r.call(this), this.internal.__cell__.headerFunction = "function" == typeof t ? t : void 0, this; }, t.getTextDimensions = function (t, e) { r.call(this); var n = (e = e || {}).fontSize || this.getFontSize(), i = e.font || this.getFont(), a = e.scaleFactor || this.internal.scaleFactor, o = 0, s = 0, u = 0; if (!Array.isArray(t) && "string" != typeof t) { if ("number" != typeof t) throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings."); t = String(t); } var c = e.maxWidth; c > 0 ? "string" == typeof t ? t = this.splitTextToSize(t, c) : "[object Array]" === Object.prototype.toString.call(t) && (t = this.splitTextToSize(t.join(" "), c)) : t = Array.isArray(t) ? t : [t]; for (var h = 0; h < t.length; h++) { o < (u = this.getStringUnitWidth(t[h], { font: i }) * n) && (o = u); } return 0 !== o && (s = t.length), { w: o /= a, h: Math.max((s * n * this.getLineHeightFactor() - n * (this.getLineHeightFactor() - 1)) / a, 0) }; }, t.cellAddPage = function () { r.call(this), this.addPage(); var t = this.internal.__cell__.margins || e; return this.internal.__cell__.lastCell = new a(t.left, t.top, void 0, void 0), this.internal.__cell__.pages += 1, this; }; var o = t.cell = function () { var t; t = arguments[0] instanceof a ? arguments[0] : new a(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]), r.call(this); var i = this.internal.__cell__.lastCell, o = this.internal.__cell__.padding, s = this.internal.__cell__.margins || e, u = this.internal.__cell__.tableHeaderRow, c = this.internal.__cell__.printHeaders; return void 0 !== i.lineNumber && (i.lineNumber === t.lineNumber ? (t.x = (i.x || 0) + (i.width || 0), t.y = i.y || 0) : i.y + i.height + t.height + s.bottom > this.getPageHeight() ? (this.cellAddPage(), t.y = s.top, c && u && (this.printHeaderRow(t.lineNumber, !0), t.y += u[0].height)) : t.y = i.y + i.height || t.y), void 0 !== t.text[0] && (this.rect(t.x, t.y, t.width, t.height, !0 === n ? "FD" : void 0), "right" === t.align ? this.text(t.text, t.x + t.width - o, t.y + o, { align: "right", baseline: "top" }) : "center" === t.align ? this.text(t.text, t.x + t.width / 2, t.y + o, { align: "center", baseline: "top", maxWidth: t.width - o - o }) : this.text(t.text, t.x + o, t.y + o, { align: "left", baseline: "top", maxWidth: t.width - o - o })), this.internal.__cell__.lastCell = t, this; }; t.table = function (t, n, u, c, h) { if (r.call(this), !u) throw new Error("No data for PDF table."); var l, f, d, p, g = [], m = [], v = [], b = {}, y = {}, w = [], N = [], L = (h = h || {}).autoSize || !1, x = !1 !== h.printHeaders, A = h.css && void 0 !== h.css["font-size"] ? 16 * h.css["font-size"] : h.fontSize || 12, _ = h.margins || Object.assign({ width: this.getPageWidth() }, e), S = "number" == typeof h.padding ? h.padding : 3, P = h.headerBackgroundColor || "#c8c8c8"; if (i.call(this), this.internal.__cell__.printHeaders = x, this.internal.__cell__.margins = _, this.internal.__cell__.table_font_size = A, this.internal.__cell__.padding = S, this.internal.__cell__.headerBackgroundColor = P, this.setFontSize(A), null == c) m = g = Object.keys(u[0]), v = g.map(function () { return "left"; });else if (Array.isArray(c) && "object" == _typeof(c[0])) for (g = c.map(function (t) { return t.name; }), m = c.map(function (t) { return t.prompt || t.name || ""; }), v = g.map(function (t) { return t.align || "left"; }), l = 0; l < c.length; l += 1) { y[c[l].name] = c[l].width * (19.049976 / 25.4); } else Array.isArray(c) && "string" == typeof c[0] && (m = g = c, v = g.map(function () { return "left"; })); if (L) for (l = 0; l < g.length; l += 1) { for (b[p = g[l]] = u.map(function (t) { return t[p]; }), this.setFont(void 0, "bold"), w.push(this.getTextDimensions(m[l], { fontSize: this.internal.__cell__.table_font_size, scaleFactor: this.internal.scaleFactor }).w), f = b[p], this.setFont(void 0, "normal"), d = 0; d < f.length; d += 1) { w.push(this.getTextDimensions(f[d], { fontSize: this.internal.__cell__.table_font_size, scaleFactor: this.internal.scaleFactor }).w); } y[p] = Math.max.apply(null, w) + S + S, w = []; } if (x) { var k = {}; for (l = 0; l < g.length; l += 1) { k[g[l]] = {}, k[g[l]].text = m[l], k[g[l]].align = v[l]; } var F = s.call(this, k, y); N = g.map(function (e) { return new a(t, n, y[e], F, k[e].text, void 0, k[e].align); }), this.setTableHeaderRow(N), this.printHeaderRow(1, !1); } var I = c.reduce(function (t, e) { return t[e.name] = e.align, t; }, {}); for (l = 0; l < u.length; l += 1) { var C = s.call(this, u[l], y); for (d = 0; d < g.length; d += 1) { o.call(this, new a(t, n, y[g[d]], C, u[l][g[d]], l + 2, I[g[d]])); } } return this.internal.__cell__.table_x = t, this.internal.__cell__.table_y = n, this; }; var s = function s(t, e) { var n = this.internal.__cell__.padding, r = this.internal.__cell__.table_font_size, i = this.internal.scaleFactor; return Object.keys(t).map(function (e) { return [e, t[e]]; }).map(function (t) { var e = t[0], n = t[1]; return "object" == _typeof(n) ? [e, n.text] : [e, n]; }).map(function (t) { var r = t[0], i = t[1]; return this.splitTextToSize(i, e[r] - n - n); }, this).map(function (t) { return this.getLineHeightFactor() * t.length * r / i + n + n; }, this).reduce(function (t, e) { return Math.max(t, e); }, 0); }; t.setTableHeaderRow = function (t) { r.call(this), this.internal.__cell__.tableHeaderRow = t; }, t.printHeaderRow = function (t, e) { if (r.call(this), !this.internal.__cell__.tableHeaderRow) throw new Error("Property tableHeaderRow does not exist."); var i; if (n = !0, "function" == typeof this.internal.__cell__.headerFunction) { var s = this.internal.__cell__.headerFunction(this, this.internal.__cell__.pages); this.internal.__cell__.lastCell = new a(s[0], s[1], s[2], s[3], void 0, -1); } this.setFont(void 0, "bold"); for (var u = [], c = 0; c < this.internal.__cell__.tableHeaderRow.length; c += 1) { i = this.internal.__cell__.tableHeaderRow[c].clone(), e && (i.y = this.internal.__cell__.margins.top || 0, u.push(i)), i.lineNumber = t, this.setFillColor(this.internal.__cell__.headerBackgroundColor), o.call(this, i); } u.length > 0 && this.setTableHeaderRow(u), this.setFont(void 0, "normal"), n = !1; }; }(g.API), function (t) { var e, r, i, a, o, s, u, h, l, f = function f(t) { return t = t || {}, this.isStrokeTransparent = t.isStrokeTransparent || !1, this.strokeOpacity = t.strokeOpacity || 1, this.strokeStyle = t.strokeStyle || "#000000", this.fillStyle = t.fillStyle || "#000000", this.isFillTransparent = t.isFillTransparent || !1, this.fillOpacity = t.fillOpacity || 1, this.font = t.font || "10px sans-serif", this.textBaseline = t.textBaseline || "alphabetic", this.textAlign = t.textAlign || "left", this.lineWidth = t.lineWidth || 1, this.lineJoin = t.lineJoin || "miter", this.lineCap = t.lineCap || "butt", this.path = t.path || [], this.transform = void 0 !== t.transform ? t.transform.clone() : new h(), this.globalCompositeOperation = t.globalCompositeOperation || "normal", this.globalAlpha = t.globalAlpha || 1, this.clip_path = t.clip_path || [], this.currentPoint = t.currentPoint || new s(), this.miterLimit = t.miterLimit || 10, this.lastPoint = t.lastPoint || new s(), this.ignoreClearRect = "boolean" != typeof t.ignoreClearRect || t.ignoreClearRect, this; }; t.events.push(["initialized", function () { this.context2d = new d(this), e = this.internal.f2, r = this.internal.getCoordinateString, i = this.internal.getVerticalCoordinateString, a = this.internal.getHorizontalCoordinate, o = this.internal.getVerticalCoordinate, s = this.internal.Point, u = this.internal.Rectangle, h = this.internal.Matrix, l = new f(); }]); var d = function d(t) { Object.defineProperty(this, "canvas", { get: function get() { return { parentNode: !1, style: !1 }; } }); var e = t; Object.defineProperty(this, "pdf", { get: function get() { return e; } }); var n = !1; Object.defineProperty(this, "pageWrapXEnabled", { get: function get() { return n; }, set: function set(t) { n = Boolean(t); } }); var r = !1; Object.defineProperty(this, "pageWrapYEnabled", { get: function get() { return r; }, set: function set(t) { r = Boolean(t); } }); var i = 0; Object.defineProperty(this, "posX", { get: function get() { return i; }, set: function set(t) { isNaN(t) || (i = t); } }); var a = 0; Object.defineProperty(this, "posY", { get: function get() { return a; }, set: function set(t) { isNaN(t) || (a = t); } }); var o = !1; Object.defineProperty(this, "autoPaging", { get: function get() { return o; }, set: function set(t) { o = Boolean(t); } }); var s = 0; Object.defineProperty(this, "lastBreak", { get: function get() { return s; }, set: function set(t) { s = t; } }); var u = []; Object.defineProperty(this, "pageBreaks", { get: function get() { return u; }, set: function set(t) { u = t; } }), Object.defineProperty(this, "ctx", { get: function get() { return l; }, set: function set(t) { t instanceof f && (l = t); } }), Object.defineProperty(this, "path", { get: function get() { return l.path; }, set: function set(t) { l.path = t; } }); var c = []; Object.defineProperty(this, "ctxStack", { get: function get() { return c; }, set: function set(t) { c = t; } }), Object.defineProperty(this, "fillStyle", { get: function get() { return this.ctx.fillStyle; }, set: function set(t) { var e; e = p(t), this.ctx.fillStyle = e.style, this.ctx.isFillTransparent = 0 === e.a, this.ctx.fillOpacity = e.a, this.pdf.setFillColor(e.r, e.g, e.b, { a: e.a }), this.pdf.setTextColor(e.r, e.g, e.b, { a: e.a }); } }), Object.defineProperty(this, "strokeStyle", { get: function get() { return this.ctx.strokeStyle; }, set: function set(t) { var e = p(t); this.ctx.strokeStyle = e.style, this.ctx.isStrokeTransparent = 0 === e.a, this.ctx.strokeOpacity = e.a, 0 === e.a ? this.pdf.setDrawColor(255, 255, 255) : (e.a, this.pdf.setDrawColor(e.r, e.g, e.b)); } }), Object.defineProperty(this, "lineCap", { get: function get() { return this.ctx.lineCap; }, set: function set(t) { -1 !== ["butt", "round", "square"].indexOf(t) && (this.ctx.lineCap = t, this.pdf.setLineCap(t)); } }), Object.defineProperty(this, "lineWidth", { get: function get() { return this.ctx.lineWidth; }, set: function set(t) { isNaN(t) || (this.ctx.lineWidth = t, this.pdf.setLineWidth(t)); } }), Object.defineProperty(this, "lineJoin", { get: function get() { return this.ctx.lineJoin; }, set: function set(t) { -1 !== ["bevel", "round", "miter"].indexOf(t) && (this.ctx.lineJoin = t, this.pdf.setLineJoin(t)); } }), Object.defineProperty(this, "miterLimit", { get: function get() { return this.ctx.miterLimit; }, set: function set(t) { isNaN(t) || (this.ctx.miterLimit = t, this.pdf.setMiterLimit(t)); } }), Object.defineProperty(this, "textBaseline", { get: function get() { return this.ctx.textBaseline; }, set: function set(t) { this.ctx.textBaseline = t; } }), Object.defineProperty(this, "textAlign", { get: function get() { return this.ctx.textAlign; }, set: function set(t) { -1 !== ["right", "end", "center", "left", "start"].indexOf(t) && (this.ctx.textAlign = t); } }), Object.defineProperty(this, "font", { get: function get() { return this.ctx.font; }, set: function set(t) { var e; if (this.ctx.font = t, null !== (e = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z]+?)\s*$/i.exec(t))) { var n = e[1], r = (e[2], e[3]), i = e[4], a = (e[5], e[6]), o = /^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(i)[2]; i = "px" === o ? Math.floor(parseFloat(i) * this.pdf.internal.scaleFactor) : "em" === o ? Math.floor(parseFloat(i) * this.pdf.getFontSize()) : Math.floor(parseFloat(i) * this.pdf.internal.scaleFactor), this.pdf.setFontSize(i); var s = ""; ("bold" === r || parseInt(r, 10) >= 700 || "bold" === n) && (s = "bold"), "italic" === n && (s += "italic"), 0 === s.length && (s = "normal"); for (var u = "", c = a.replace(/"|'/g, "").split(/\s*,\s*/), h = { arial: "Helvetica", Arial: "Helvetica", verdana: "Helvetica", Verdana: "Helvetica", helvetica: "Helvetica", Helvetica: "Helvetica", "sans-serif": "Helvetica", fixed: "Courier", monospace: "Courier", terminal: "Courier", cursive: "Times", fantasy: "Times", serif: "Times" }, l = 0; l < c.length; l++) { if (void 0 !== this.pdf.internal.getFont(c[l], s, { noFallback: !0, disableWarning: !0 })) { u = c[l]; break; } if ("bolditalic" === s && void 0 !== this.pdf.internal.getFont(c[l], "bold", { noFallback: !0, disableWarning: !0 })) u = c[l], s = "bold";else if (void 0 !== this.pdf.internal.getFont(c[l], "normal", { noFallback: !0, disableWarning: !0 })) { u = c[l], s = "normal"; break; } } if ("" === u) for (var f = 0; f < c.length; f++) { if (h[c[f]]) { u = h[c[f]]; break; } } u = "" === u ? "Times" : u, this.pdf.setFont(u, s); } } }), Object.defineProperty(this, "globalCompositeOperation", { get: function get() { return this.ctx.globalCompositeOperation; }, set: function set(t) { this.ctx.globalCompositeOperation = t; } }), Object.defineProperty(this, "globalAlpha", { get: function get() { return this.ctx.globalAlpha; }, set: function set(t) { this.ctx.globalAlpha = t; } }), Object.defineProperty(this, "ignoreClearRect", { get: function get() { return this.ctx.ignoreClearRect; }, set: function set(t) { this.ctx.ignoreClearRect = Boolean(t); } }); }; d.prototype.fill = function () { N.call(this, "fill", !1); }, d.prototype.stroke = function () { N.call(this, "stroke", !1); }, d.prototype.beginPath = function () { this.path = [{ type: "begin" }]; }, d.prototype.moveTo = function (t, e) { if (isNaN(t) || isNaN(e)) throw n.error("jsPDF.context2d.moveTo: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.moveTo"); var r = this.ctx.transform.applyToPoint(new s(t, e)); this.path.push({ type: "mt", x: r.x, y: r.y }), this.ctx.lastPoint = new s(t, e); }, d.prototype.closePath = function () { var t = new s(0, 0), e = 0; for (e = this.path.length - 1; -1 !== e; e--) { if ("begin" === this.path[e].type && "object" == _typeof(this.path[e + 1]) && "number" == typeof this.path[e + 1].x) { t = new s(this.path[e + 1].x, this.path[e + 1].y), this.path.push({ type: "lt", x: t.x, y: t.y }); break; } } "object" == _typeof(this.path[e + 2]) && "number" == typeof this.path[e + 2].x && this.path.push(JSON.parse(JSON.stringify(this.path[e + 2]))), this.path.push({ type: "close" }), this.ctx.lastPoint = new s(t.x, t.y); }, d.prototype.lineTo = function (t, e) { if (isNaN(t) || isNaN(e)) throw n.error("jsPDF.context2d.lineTo: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.lineTo"); var r = this.ctx.transform.applyToPoint(new s(t, e)); this.path.push({ type: "lt", x: r.x, y: r.y }), this.ctx.lastPoint = new s(r.x, r.y); }, d.prototype.clip = function () { this.ctx.clip_path = JSON.parse(JSON.stringify(this.path)), N.call(this, null, !0); }, d.prototype.quadraticCurveTo = function (t, e, r, i) { if (isNaN(r) || isNaN(i) || isNaN(t) || isNaN(e)) throw n.error("jsPDF.context2d.quadraticCurveTo: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.quadraticCurveTo"); var a = this.ctx.transform.applyToPoint(new s(r, i)), o = this.ctx.transform.applyToPoint(new s(t, e)); this.path.push({ type: "qct", x1: o.x, y1: o.y, x: a.x, y: a.y }), this.ctx.lastPoint = new s(a.x, a.y); }, d.prototype.bezierCurveTo = function (t, e, r, i, a, o) { if (isNaN(a) || isNaN(o) || isNaN(t) || isNaN(e) || isNaN(r) || isNaN(i)) throw n.error("jsPDF.context2d.bezierCurveTo: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.bezierCurveTo"); var u = this.ctx.transform.applyToPoint(new s(a, o)), c = this.ctx.transform.applyToPoint(new s(t, e)), h = this.ctx.transform.applyToPoint(new s(r, i)); this.path.push({ type: "bct", x1: c.x, y1: c.y, x2: h.x, y2: h.y, x: u.x, y: u.y }), this.ctx.lastPoint = new s(u.x, u.y); }, d.prototype.arc = function (t, e, r, i, a, o) { if (isNaN(t) || isNaN(e) || isNaN(r) || isNaN(i) || isNaN(a)) throw n.error("jsPDF.context2d.arc: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.arc"); if (o = Boolean(o), !this.ctx.transform.isIdentity) { var u = this.ctx.transform.applyToPoint(new s(t, e)); t = u.x, e = u.y; var c = this.ctx.transform.applyToPoint(new s(0, r)), h = this.ctx.transform.applyToPoint(new s(0, 0)); r = Math.sqrt(Math.pow(c.x - h.x, 2) + Math.pow(c.y - h.y, 2)); } Math.abs(a - i) >= 2 * Math.PI && (i = 0, a = 2 * Math.PI), this.path.push({ type: "arc", x: t, y: e, radius: r, startAngle: i, endAngle: a, counterclockwise: o }); }, d.prototype.arcTo = function (t, e, n, r, i) { throw new Error("arcTo not implemented."); }, d.prototype.rect = function (t, e, r, i) { if (isNaN(t) || isNaN(e) || isNaN(r) || isNaN(i)) throw n.error("jsPDF.context2d.rect: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.rect"); this.moveTo(t, e), this.lineTo(t + r, e), this.lineTo(t + r, e + i), this.lineTo(t, e + i), this.lineTo(t, e), this.lineTo(t + r, e), this.lineTo(t, e); }, d.prototype.fillRect = function (t, e, r, i) { if (isNaN(t) || isNaN(e) || isNaN(r) || isNaN(i)) throw n.error("jsPDF.context2d.fillRect: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.fillRect"); if (!g.call(this)) { var a = {}; "butt" !== this.lineCap && (a.lineCap = this.lineCap, this.lineCap = "butt"), "miter" !== this.lineJoin && (a.lineJoin = this.lineJoin, this.lineJoin = "miter"), this.beginPath(), this.rect(t, e, r, i), this.fill(), a.hasOwnProperty("lineCap") && (this.lineCap = a.lineCap), a.hasOwnProperty("lineJoin") && (this.lineJoin = a.lineJoin); } }, d.prototype.strokeRect = function (t, e, r, i) { if (isNaN(t) || isNaN(e) || isNaN(r) || isNaN(i)) throw n.error("jsPDF.context2d.strokeRect: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.strokeRect"); m.call(this) || (this.beginPath(), this.rect(t, e, r, i), this.stroke()); }, d.prototype.clearRect = function (t, e, r, i) { if (isNaN(t) || isNaN(e) || isNaN(r) || isNaN(i)) throw n.error("jsPDF.context2d.clearRect: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.clearRect"); this.ignoreClearRect || (this.fillStyle = "#ffffff", this.fillRect(t, e, r, i)); }, d.prototype.save = function (t) { t = "boolean" != typeof t || t; for (var e = this.pdf.internal.getCurrentPageInfo().pageNumber, n = 0; n < this.pdf.internal.getNumberOfPages(); n++) { this.pdf.setPage(n + 1), this.pdf.internal.out("q"); } if (this.pdf.setPage(e), t) { this.ctx.fontSize = this.pdf.internal.getFontSize(); var r = new f(this.ctx); this.ctxStack.push(this.ctx), this.ctx = r; } }, d.prototype.restore = function (t) { t = "boolean" != typeof t || t; for (var e = this.pdf.internal.getCurrentPageInfo().pageNumber, n = 0; n < this.pdf.internal.getNumberOfPages(); n++) { this.pdf.setPage(n + 1), this.pdf.internal.out("Q"); } this.pdf.setPage(e), t && 0 !== this.ctxStack.length && (this.ctx = this.ctxStack.pop(), this.fillStyle = this.ctx.fillStyle, this.strokeStyle = this.ctx.strokeStyle, this.font = this.ctx.font, this.lineCap = this.ctx.lineCap, this.lineWidth = this.ctx.lineWidth, this.lineJoin = this.ctx.lineJoin); }, d.prototype.toDataURL = function () { throw new Error("toDataUrl not implemented."); }; var p = function p(t) { var e, n, r, i; if (!0 === t.isCanvasGradient && (t = t.getColor()), !t) return { r: 0, g: 0, b: 0, a: 0, style: t }; if (/transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/.test(t)) e = 0, n = 0, r = 0, i = 0;else { var a = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(t); if (null !== a) e = parseInt(a[1]), n = parseInt(a[2]), r = parseInt(a[3]), i = 1;else if (null !== (a = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)/.exec(t))) e = parseInt(a[1]), n = parseInt(a[2]), r = parseInt(a[3]), i = parseFloat(a[4]);else { if (i = 1, "string" == typeof t && "#" !== t.charAt(0)) { var o = new c(t); t = o.ok ? o.toHex() : "#000000"; } 4 === t.length ? (e = t.substring(1, 2), e += e, n = t.substring(2, 3), n += n, r = t.substring(3, 4), r += r) : (e = t.substring(1, 3), n = t.substring(3, 5), r = t.substring(5, 7)), e = parseInt(e, 16), n = parseInt(n, 16), r = parseInt(r, 16); } } return { r: e, g: n, b: r, a: i, style: t }; }, g = function g() { return this.ctx.isFillTransparent || 0 == this.globalAlpha; }, m = function m() { return Boolean(this.ctx.isStrokeTransparent || 0 == this.globalAlpha); }; d.prototype.fillText = function (t, e, r, i) { if (isNaN(e) || isNaN(r) || "string" != typeof t) throw n.error("jsPDF.context2d.fillText: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.fillText"); if (i = isNaN(i) ? void 0 : i, !g.call(this)) { r = x.call(this, r); var a = O(this.ctx.transform.rotation), o = this.ctx.transform.scaleX; k.call(this, { text: t, x: e, y: r, scale: o, angle: a, align: this.textAlign, maxWidth: i }); } }, d.prototype.strokeText = function (t, e, r, i) { if (isNaN(e) || isNaN(r) || "string" != typeof t) throw n.error("jsPDF.context2d.strokeText: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.strokeText"); if (!m.call(this)) { i = isNaN(i) ? void 0 : i, r = x.call(this, r); var a = O(this.ctx.transform.rotation), o = this.ctx.transform.scaleX; k.call(this, { text: t, x: e, y: r, scale: o, renderingMode: "stroke", angle: a, align: this.textAlign, maxWidth: i }); } }, d.prototype.measureText = function (t) { if ("string" != typeof t) throw n.error("jsPDF.context2d.measureText: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.measureText"); var e = this.pdf, r = this.pdf.internal.scaleFactor, i = e.internal.getFontSize(), a = e.getStringUnitWidth(t) * i / e.internal.scaleFactor, o = function o(t) { var e = (t = t || {}).width || 0; return Object.defineProperty(this, "width", { get: function get() { return e; } }), this; }; return new o({ width: a *= Math.round(96 * r / 72 * 1e4) / 1e4 }); }, d.prototype.scale = function (t, e) { if (isNaN(t) || isNaN(e)) throw n.error("jsPDF.context2d.scale: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.scale"); var r = new h(t, 0, 0, e, 0, 0); this.ctx.transform = this.ctx.transform.multiply(r); }, d.prototype.rotate = function (t) { if (isNaN(t)) throw n.error("jsPDF.context2d.rotate: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.rotate"); var e = new h(Math.cos(t), Math.sin(t), -Math.sin(t), Math.cos(t), 0, 0); this.ctx.transform = this.ctx.transform.multiply(e); }, d.prototype.translate = function (t, e) { if (isNaN(t) || isNaN(e)) throw n.error("jsPDF.context2d.translate: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.translate"); var r = new h(1, 0, 0, 1, t, e); this.ctx.transform = this.ctx.transform.multiply(r); }, d.prototype.transform = function (t, e, r, i, a, o) { if (isNaN(t) || isNaN(e) || isNaN(r) || isNaN(i) || isNaN(a) || isNaN(o)) throw n.error("jsPDF.context2d.transform: Invalid arguments", arguments), new Error("Invalid arguments passed to jsPDF.context2d.transform"); var s = new h(t, e, r, i, a, o); this.ctx.transform = this.ctx.transform.multiply(s); }, d.prototype.setTransform = function (t, e, n, r, i, a) { t = isNaN(t) ? 1 : t, e = isNaN(e) ? 0 : e, n = isNaN(n) ? 0 : n, r = isNaN(r) ? 1 : r, i = isNaN(i) ? 0 : i, a = isNaN(a) ? 0 : a, this.ctx.transform = new h(t, e, n, r, i, a); }, d.prototype.drawImage = function (t, e, n, r, i, a, o, s, c) { var l = this.pdf.getImageProperties(t), f = 1, d = 1, p = 1, g = 1; void 0 !== r && void 0 !== s && (p = s / r, g = c / i, f = l.width / r * s / r, d = l.height / i * c / i), void 0 === a && (a = e, o = n, e = 0, n = 0), void 0 !== r && void 0 === s && (s = r, c = i), void 0 === r && void 0 === s && (s = l.width, c = l.height); for (var m, b = this.ctx.transform.decompose(), N = O(b.rotate.shx), x = new h(), A = (x = (x = (x = x.multiply(b.translate)).multiply(b.skew)).multiply(b.scale)).applyToRectangle(new u(a - e * p, o - n * g, r * f, i * d)), _ = v.call(this, A), S = [], P = 0; P < _.length; P += 1) { -1 === S.indexOf(_[P]) && S.push(_[P]); } if (w(S), this.autoPaging) for (var k = S[0], F = S[S.length - 1], I = k; I < F + 1; I++) { if (this.pdf.setPage(I), 0 !== this.ctx.clip_path.length) { var C = this.path; m = JSON.parse(JSON.stringify(this.ctx.clip_path)), this.path = y(m, this.posX, -1 * this.pdf.internal.pageSize.height * (I - 1) + this.posY), L.call(this, "fill", !0), this.path = C; } var j = JSON.parse(JSON.stringify(A)); j = y([j], this.posX, -1 * this.pdf.internal.pageSize.height * (I - 1) + this.posY)[0], this.pdf.addImage(t, "JPEG", j.x, j.y, j.w, j.h, null, null, N); } else this.pdf.addImage(t, "JPEG", A.x, A.y, A.w, A.h, null, null, N); }; var v = function v(t, e, n) { var r = []; switch (e = e || this.pdf.internal.pageSize.width, n = n || this.pdf.internal.pageSize.height, t.type) { default: case "mt": case "lt": r.push(Math.floor((t.y + this.posY) / n) + 1); break; case "arc": r.push(Math.floor((t.y + this.posY - t.radius) / n) + 1), r.push(Math.floor((t.y + this.posY + t.radius) / n) + 1); break; case "qct": var i = M(this.ctx.lastPoint.x, this.ctx.lastPoint.y, t.x1, t.y1, t.x, t.y); r.push(Math.floor(i.y / n) + 1), r.push(Math.floor((i.y + i.h) / n) + 1); break; case "bct": var a = E(this.ctx.lastPoint.x, this.ctx.lastPoint.y, t.x1, t.y1, t.x2, t.y2, t.x, t.y); r.push(Math.floor(a.y / n) + 1), r.push(Math.floor((a.y + a.h) / n) + 1); break; case "rect": r.push(Math.floor((t.y + this.posY) / n) + 1), r.push(Math.floor((t.y + t.h + this.posY) / n) + 1); } for (var o = 0; o < r.length; o += 1) { for (; this.pdf.internal.getNumberOfPages() < r[o];) { b.call(this); } } return r; }, b = function b() { var t = this.fillStyle, e = this.strokeStyle, n = this.font, r = this.lineCap, i = this.lineWidth, a = this.lineJoin; this.pdf.addPage(), this.fillStyle = t, this.strokeStyle = e, this.font = n, this.lineCap = r, this.lineWidth = i, this.lineJoin = a; }, y = function y(t, e, n) { for (var r = 0; r < t.length; r++) { switch (t[r].type) { case "bct": t[r].x2 += e, t[r].y2 += n; case "qct": t[r].x1 += e, t[r].y1 += n; case "mt": case "lt": case "arc": default: t[r].x += e, t[r].y += n; } } return t; }, w = function w(t) { return t.sort(function (t, e) { return t - e; }); }, N = function N(t, e) { for (var n, r, i = this.fillStyle, a = this.strokeStyle, o = this.lineCap, s = this.lineWidth, u = s * this.ctx.transform.scaleX, c = this.lineJoin, h = JSON.parse(JSON.stringify(this.path)), l = JSON.parse(JSON.stringify(this.path)), f = [], d = 0; d < l.length; d++) { if (void 0 !== l[d].x) for (var p = v.call(this, l[d]), g = 0; g < p.length; g += 1) { -1 === f.indexOf(p[g]) && f.push(p[g]); } } for (var m = 0; m < f.length; m++) { for (; this.pdf.internal.getNumberOfPages() < f[m];) { b.call(this); } } if (w(f), this.autoPaging) for (var N = f[0], x = f[f.length - 1], A = N; A < x + 1; A++) { if (this.pdf.setPage(A), this.fillStyle = i, this.strokeStyle = a, this.lineCap = o, this.lineWidth = u, this.lineJoin = c, 0 !== this.ctx.clip_path.length) { var _ = this.path; n = JSON.parse(JSON.stringify(this.ctx.clip_path)), this.path = y(n, this.posX, -1 * this.pdf.internal.pageSize.height * (A - 1) + this.posY), L.call(this, t, !0), this.path = _; } r = JSON.parse(JSON.stringify(h)), this.path = y(r, this.posX, -1 * this.pdf.internal.pageSize.height * (A - 1) + this.posY), !1 !== e && 0 !== A || L.call(this, t, e), this.lineWidth = s; } else this.lineWidth = u, L.call(this, t, e), this.lineWidth = s; this.path = h; }, L = function L(t, e) { if (("stroke" !== t || e || !m.call(this)) && ("stroke" === t || e || !g.call(this))) { for (var n, r, i = [], a = this.path, o = 0; o < a.length; o++) { var s = a[o]; switch (s.type) { case "begin": i.push({ begin: !0 }); break; case "close": i.push({ close: !0 }); break; case "mt": i.push({ start: s, deltas: [], abs: [] }); break; case "lt": var u = i.length; if (!isNaN(a[o - 1].x) && (n = [s.x - a[o - 1].x, s.y - a[o - 1].y], u > 0)) for (; u >= 0; u--) { if (!0 !== i[u - 1].close && !0 !== i[u - 1].begin) { i[u - 1].deltas.push(n), i[u - 1].abs.push(s); break; } } break; case "bct": n = [s.x1 - a[o - 1].x, s.y1 - a[o - 1].y, s.x2 - a[o - 1].x, s.y2 - a[o - 1].y, s.x - a[o - 1].x, s.y - a[o - 1].y], i[i.length - 1].deltas.push(n); break; case "qct": var c = a[o - 1].x + 2 / 3 * (s.x1 - a[o - 1].x), h = a[o - 1].y + 2 / 3 * (s.y1 - a[o - 1].y), l = s.x + 2 / 3 * (s.x1 - s.x), f = s.y + 2 / 3 * (s.y1 - s.y), d = s.x, p = s.y; n = [c - a[o - 1].x, h - a[o - 1].y, l - a[o - 1].x, f - a[o - 1].y, d - a[o - 1].x, p - a[o - 1].y], i[i.length - 1].deltas.push(n); break; case "arc": i.push({ deltas: [], abs: [], arc: !0 }), Array.isArray(i[i.length - 1].abs) && i[i.length - 1].abs.push(s); } } r = e ? null : "stroke" === t ? "stroke" : "fill"; for (var v = 0; v < i.length; v++) { if (i[v].arc) { for (var b = i[v].abs, y = 0; y < b.length; y++) { var w = b[y]; "arc" === w.type ? A.call(this, w.x, w.y, w.radius, w.startAngle, w.endAngle, w.counterclockwise, void 0, e) : F.call(this, w.x, w.y); } _.call(this, r), this.pdf.internal.out("h"); } if (!i[v].arc && !0 !== i[v].close && !0 !== i[v].begin) { var N = i[v].start.x, L = i[v].start.y; I.call(this, i[v].deltas, N, L); } } r && _.call(this, r), e && S.call(this); } }, x = function x(t) { var e = this.pdf.internal.getFontSize() / this.pdf.internal.scaleFactor, n = e * (this.pdf.internal.getLineHeightFactor() - 1); switch (this.ctx.textBaseline) { case "bottom": return t - n; case "top": return t + e - n; case "hanging": return t + e - 2 * n; case "middle": return t + e / 2 - n; case "ideographic": return t; case "alphabetic": default: return t; } }; d.prototype.createLinearGradient = function () { var t = function t() {}; return t.colorStops = [], t.addColorStop = function (t, e) { this.colorStops.push([t, e]); }, t.getColor = function () { return 0 === this.colorStops.length ? "#000000" : this.colorStops[0][1]; }, t.isCanvasGradient = !0, t; }, d.prototype.createPattern = function () { return this.createLinearGradient(); }, d.prototype.createRadialGradient = function () { return this.createLinearGradient(); }; var A = function A(t, e, n, r, i, a, o, s) { for (var u = j.call(this, n, r, i, a), c = 0; c < u.length; c++) { var h = u[c]; 0 === c && P.call(this, h.x1 + t, h.y1 + e), C.call(this, t, e, h.x2, h.y2, h.x3, h.y3, h.x4, h.y4); } s ? S.call(this) : _.call(this, o); }, _ = function _(t) { switch (t) { case "stroke": this.pdf.internal.out("S"); break; case "fill": this.pdf.internal.out("f"); } }, S = function S() { this.pdf.clip(), this.pdf.discardPath(); }, P = function P(t, e) { this.pdf.internal.out(r(t) + " " + i(e) + " m"); }, k = function k(t) { var e; switch (t.align) { case "right": case "end": e = "right"; break; case "center": e = "center"; break; case "left": case "start": default: e = "left"; } var n = this.ctx.transform.applyToPoint(new s(t.x, t.y)), r = this.ctx.transform.decompose(), i = new h(); i = (i = (i = i.multiply(r.translate)).multiply(r.skew)).multiply(r.scale); for (var a, o, c, l = this.pdf.getTextDimensions(t.text), f = this.ctx.transform.applyToRectangle(new u(t.x, t.y, l.w, l.h)), d = i.applyToRectangle(new u(t.x, t.y - l.h, l.w, l.h)), p = v.call(this, d), g = [], m = 0; m < p.length; m += 1) { -1 === g.indexOf(p[m]) && g.push(p[m]); } if (w(g), !0 === this.autoPaging) for (var b = g[0], N = g[g.length - 1], x = b; x < N + 1; x++) { if (this.pdf.setPage(x), 0 !== this.ctx.clip_path.length) { var A = this.path; a = JSON.parse(JSON.stringify(this.ctx.clip_path)), this.path = y(a, this.posX, -1 * this.pdf.internal.pageSize.height * (x - 1) + this.posY), L.call(this, "fill", !0), this.path = A; } var _ = JSON.parse(JSON.stringify(f)); _ = y([_], this.posX, -1 * this.pdf.internal.pageSize.height * (x - 1) + this.posY)[0], t.scale >= .01 && (o = this.pdf.internal.getFontSize(), this.pdf.setFontSize(o * t.scale), c = this.lineWidth, this.lineWidth = c * t.scale), this.pdf.text(t.text, _.x, _.y, { angle: t.angle, align: e, renderingMode: t.renderingMode, maxWidth: t.maxWidth }), t.scale >= .01 && (this.pdf.setFontSize(o), this.lineWidth = c); } else t.scale >= .01 && (o = this.pdf.internal.getFontSize(), this.pdf.setFontSize(o * t.scale), c = this.lineWidth, this.lineWidth = c * t.scale), this.pdf.text(t.text, n.x + this.posX, n.y + this.posY, { angle: t.angle, align: e, renderingMode: t.renderingMode, maxWidth: t.maxWidth }), t.scale >= .01 && (this.pdf.setFontSize(o), this.lineWidth = c); }, F = function F(t, e, n, a) { n = n || 0, a = a || 0, this.pdf.internal.out(r(t + n) + " " + i(e + a) + " l"); }, I = function I(t, e, n) { return this.pdf.lines(t, e, n, null, null); }, C = function C(t, n, r, i, s, u, c, h) { this.pdf.internal.out([e(a(r + t)), e(o(i + n)), e(a(s + t)), e(o(u + n)), e(a(c + t)), e(o(h + n)), "c"].join(" ")); }, j = function j(t, e, n, r) { for (var i = 2 * Math.PI, a = Math.PI / 2; e > n;) { e -= i; } var o = Math.abs(n - e); o < i && r && (o = i - o); for (var s = [], u = r ? -1 : 1, c = e; o > 1e-5;) { var h = c + u * Math.min(o, a); s.push(B.call(this, t, c, h)), o -= Math.abs(h - c), c = h; } return s; }, B = function B(t, e, n) { var r = (n - e) / 2, i = t * Math.cos(r), a = t * Math.sin(r), o = i, s = -a, u = o * o + s * s, c = u + o * i + s * a, h = 4 / 3 * (Math.sqrt(2 * u * c) - c) / (o * a - s * i), l = o - h * s, f = s + h * o, d = l, p = -f, g = r + e, m = Math.cos(g), v = Math.sin(g); return { x1: t * Math.cos(e), y1: t * Math.sin(e), x2: l * m - f * v, y2: l * v + f * m, x3: d * m - p * v, y3: d * v + p * m, x4: t * Math.cos(n), y4: t * Math.sin(n) }; }, O = function O(t) { return 180 * t / Math.PI; }, M = function M(t, e, n, r, i, a) { var o = t + .5 * (n - t), s = e + .5 * (r - e), c = i + .5 * (n - i), h = a + .5 * (r - a), l = Math.min(t, i, o, c), f = Math.max(t, i, o, c), d = Math.min(e, a, s, h), p = Math.max(e, a, s, h); return new u(l, d, f - l, p - d); }, E = function E(t, e, n, r, i, a, o, s) { var c, h, l, f, d, p, g, m, v, b, y, w, N, L, x = n - t, A = r - e, _ = i - n, S = a - r, P = o - i, k = s - a; for (h = 0; h < 41; h++) { v = (g = (l = t + (c = h / 40) * x) + c * ((d = n + c * _) - l)) + c * (d + c * (i + c * P - d) - g), b = (m = (f = e + c * A) + c * ((p = r + c * S) - f)) + c * (p + c * (a + c * k - p) - m), 0 == h ? (y = v, w = b, N = v, L = b) : (y = Math.min(y, v), w = Math.min(w, b), N = Math.max(N, v), L = Math.max(L, b)); } return new u(Math.round(y), Math.round(w), Math.round(N - y), Math.round(L - w)); }; }(g.API); /** * @license Copyright (c) 2013 Gildas Lormeau. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var lt = [0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29]; function ft() { var t = this; function e(t, e) { var n = 0; do { n |= 1 & t, t >>>= 1, n <<= 1; } while (--e > 0); return n >>> 1; } t.build_tree = function (n) { var r, i, a, o = t.dyn_tree, s = t.stat_desc.static_tree, u = t.stat_desc.elems, c = -1; for (n.heap_len = 0, n.heap_max = 573, r = 0; r < u; r++) { 0 !== o[2 * r] ? (n.heap[++n.heap_len] = c = r, n.depth[r] = 0) : o[2 * r + 1] = 0; } for (; n.heap_len < 2;) { o[2 * (a = n.heap[++n.heap_len] = c < 2 ? ++c : 0)] = 1, n.depth[a] = 0, n.opt_len--, s && (n.static_len -= s[2 * a + 1]); } for (t.max_code = c, r = Math.floor(n.heap_len / 2); r >= 1; r--) { n.pqdownheap(o, r); } a = u; do { r = n.heap[1], n.heap[1] = n.heap[n.heap_len--], n.pqdownheap(o, 1), i = n.heap[1], n.heap[--n.heap_max] = r, n.heap[--n.heap_max] = i, o[2 * a] = o[2 * r] + o[2 * i], n.depth[a] = Math.max(n.depth[r], n.depth[i]) + 1, o[2 * r + 1] = o[2 * i + 1] = a, n.heap[1] = a++, n.pqdownheap(o, 1); } while (n.heap_len >= 2); n.heap[--n.heap_max] = n.heap[1], function (e) { var n, r, i, a, o, s, u = t.dyn_tree, c = t.stat_desc.static_tree, h = t.stat_desc.extra_bits, l = t.stat_desc.extra_base, f = t.stat_desc.max_length, d = 0; for (a = 0; a <= 15; a++) { e.bl_count[a] = 0; } for (u[2 * e.heap[e.heap_max] + 1] = 0, n = e.heap_max + 1; n < 573; n++) { (a = u[2 * u[2 * (r = e.heap[n]) + 1] + 1] + 1) > f && (a = f, d++), u[2 * r + 1] = a, r > t.max_code || (e.bl_count[a]++, o = 0, r >= l && (o = h[r - l]), s = u[2 * r], e.opt_len += s * (a + o), c && (e.static_len += s * (c[2 * r + 1] + o))); } if (0 !== d) { do { for (a = f - 1; 0 === e.bl_count[a];) { a--; } e.bl_count[a]--, e.bl_count[a + 1] += 2, e.bl_count[f]--, d -= 2; } while (d > 0); for (a = f; 0 !== a; a--) { for (r = e.bl_count[a]; 0 !== r;) { (i = e.heap[--n]) > t.max_code || (u[2 * i + 1] !== a && (e.opt_len += (a - u[2 * i + 1]) * u[2 * i], u[2 * i + 1] = a), r--); } } } }(n), function (t, n, r) { var i, a, o, s = [], u = 0; for (i = 1; i <= 15; i++) { s[i] = u = u + r[i - 1] << 1; } for (a = 0; a <= n; a++) { 0 !== (o = t[2 * a + 1]) && (t[2 * a] = e(s[o]++, o)); } }(o, t.max_code, n.bl_count); }; } function dt(t, e, n, r, i) { this.static_tree = t, this.extra_bits = e, this.extra_base = n, this.elems = r, this.max_length = i; } ft._length_code = [0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28], ft.base_length = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0], ft.base_dist = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576], ft.d_code = function (t) { return t < 256 ? lt[t] : lt[256 + (t >>> 7)]; }, ft.extra_lbits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], ft.extra_dbits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], ft.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], ft.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], dt.static_ltree = [12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8], dt.static_dtree = [0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5], dt.static_l_desc = new dt(dt.static_ltree, ft.extra_lbits, 257, 286, 15), dt.static_d_desc = new dt(dt.static_dtree, ft.extra_dbits, 0, 30, 15), dt.static_bl_desc = new dt(null, ft.extra_blbits, 0, 19, 7); function pt(t, e, n, r, i) { this.good_length = t, this.max_lazy = e, this.nice_length = n, this.max_chain = r, this.func = i; } var gt, mt, vt, bt = [new pt(0, 0, 0, 0, 0), new pt(4, 4, 8, 4, 1), new pt(4, 5, 16, 8, 1), new pt(4, 6, 32, 32, 1), new pt(4, 4, 16, 16, 2), new pt(8, 16, 32, 32, 2), new pt(8, 16, 128, 128, 2), new pt(8, 32, 128, 256, 2), new pt(32, 128, 258, 1024, 2), new pt(32, 258, 258, 4096, 2)], yt = ["need dictionary", "stream end", "", "", "stream error", "data error", "", "buffer error", "", ""]; function wt(t, e, n, r) { var i = t[2 * e], a = t[2 * n]; return i < a || i === a && r[e] <= r[n]; } function Nt() { var t, e, n, r, i, a, o, s, u, c, h, l, f, d, p, g, m, v, b, y, w, N, L, x, A, _, S, P, k, F, I, C, j, B, O, M, E, q, R, T, D, U = this, z = new ft(), H = new ft(), W = new ft(); function V() { var t; for (t = 0; t < 286; t++) { I[2 * t] = 0; } for (t = 0; t < 30; t++) { C[2 * t] = 0; } for (t = 0; t < 19; t++) { j[2 * t] = 0; } I[512] = 1, U.opt_len = U.static_len = 0, M = q = 0; } function G(t, e) { var n, r, i = -1, a = t[1], o = 0, s = 7, u = 4; for (0 === a && (s = 138, u = 3), t[2 * (e + 1) + 1] = 65535, n = 0; n <= e; n++) { r = a, a = t[2 * (n + 1) + 1], ++o < s && r === a || (o < u ? j[2 * r] += o : 0 !== r ? (r !== i && j[2 * r]++, j[32]++) : o <= 10 ? j[34]++ : j[36]++, o = 0, i = r, 0 === a ? (s = 138, u = 3) : r === a ? (s = 6, u = 3) : (s = 7, u = 4)); } } function Y(t) { U.pending_buf[U.pending++] = t; } function J(t) { Y(255 & t), Y(t >>> 8 & 255); } function X(t, e) { var n, r = e; D > 16 - r ? (J(T |= (n = t) << D & 65535), T = n >>> 16 - D, D += r - 16) : (T |= t << D & 65535, D += r); } function K(t, e) { var n = 2 * t; X(65535 & e[n], 65535 & e[n + 1]); } function Z(t, e) { var n, r, i = -1, a = t[1], o = 0, s = 7, u = 4; for (0 === a && (s = 138, u = 3), n = 0; n <= e; n++) { if (r = a, a = t[2 * (n + 1) + 1], !(++o < s && r === a)) { if (o < u) do { K(r, j); } while (0 != --o);else 0 !== r ? (r !== i && (K(r, j), o--), K(16, j), X(o - 3, 2)) : o <= 10 ? (K(17, j), X(o - 3, 3)) : (K(18, j), X(o - 11, 7)); o = 0, i = r, 0 === a ? (s = 138, u = 3) : r === a ? (s = 6, u = 3) : (s = 7, u = 4); } } } function $() { 16 === D ? (J(T), T = 0, D = 0) : D >= 8 && (Y(255 & T), T >>>= 8, D -= 8); } function Q(t, e) { var n, r, i; if (U.pending_buf[E + 2 * M] = t >>> 8 & 255, U.pending_buf[E + 2 * M + 1] = 255 & t, U.pending_buf[B + M] = 255 & e, M++, 0 === t ? I[2 * e]++ : (q++, t--, I[2 * (ft._length_code[e] + 256 + 1)]++, C[2 * ft.d_code(t)]++), 0 == (8191 & M) && S > 2) { for (n = 8 * M, r = w - m, i = 0; i < 30; i++) { n += C[2 * i] * (5 + ft.extra_dbits[i]); } if (n >>>= 3, q < Math.floor(M / 2) && n < Math.floor(r / 2)) return !0; } return M === O - 1; } function tt(t, e) { var n, r, i, a, o = 0; if (0 !== M) do { n = U.pending_buf[E + 2 * o] << 8 & 65280 | 255 & U.pending_buf[E + 2 * o + 1], r = 255 & U.pending_buf[B + o], o++, 0 === n ? K(r, t) : (K((i = ft._length_code[r]) + 256 + 1, t), 0 !== (a = ft.extra_lbits[i]) && X(r -= ft.base_length[i], a), n--, K(i = ft.d_code(n), e), 0 !== (a = ft.extra_dbits[i]) && X(n -= ft.base_dist[i], a)); } while (o < M); K(256, t), R = t[513]; } function et() { D > 8 ? J(T) : D > 0 && Y(255 & T), T = 0, D = 0; } function nt(t, e, n) { X(0 + (n ? 1 : 0), 3), function (t, e, n) { et(), R = 8, n && (J(e), J(~e)), U.pending_buf.set(s.subarray(t, t + e), U.pending), U.pending += e; }(t, e, !0); } function rt(t, e, n) { var r, i, a = 0; S > 0 ? (z.build_tree(U), H.build_tree(U), a = function () { var t; for (G(I, z.max_code), G(C, H.max_code), W.build_tree(U), t = 18; t >= 3 && 0 === j[2 * ft.bl_order[t] + 1]; t--) { } return U.opt_len += 3 * (t + 1) + 5 + 5 + 4, t; }(), r = U.opt_len + 3 + 7 >>> 3, (i = U.static_len + 3 + 7 >>> 3) <= r && (r = i)) : r = i = e + 5, e + 4 <= r && -1 !== t ? nt(t, e, n) : i === r ? (X(2 + (n ? 1 : 0), 3), tt(dt.static_ltree, dt.static_dtree)) : (X(4 + (n ? 1 : 0), 3), function (t, e, n) { var r; for (X(t - 257, 5), X(e - 1, 5), X(n - 4, 4), r = 0; r < n; r++) { X(j[2 * ft.bl_order[r] + 1], 3); } Z(I, t - 1), Z(C, e - 1); }(z.max_code + 1, H.max_code + 1, a + 1), tt(I, C)), V(), n && et(); } function it(e) { rt(m >= 0 ? m : -1, w - m, e), m = w, t.flush_pending(); } function at() { var e, n, r, a; do { if (0 === (a = u - L - w) && 0 === w && 0 === L) a = i;else if (-1 === a) a--;else if (w >= i + i - 262) { s.set(s.subarray(i, i + i), 0), N -= i, w -= i, m -= i, r = e = f; do { n = 65535 & h[--r], h[r] = n >= i ? n - i : 0; } while (0 != --e); r = e = i; do { n = 65535 & c[--r], c[r] = n >= i ? n - i : 0; } while (0 != --e); a += i; } if (0 === t.avail_in) return; e = t.read_buf(s, w + L, a), (L += e) >= 3 && (l = ((l = 255 & s[w]) << g ^ 255 & s[w + 1]) & p); } while (L < 262 && 0 !== t.avail_in); } function ot(t) { var e, n, r = A, a = w, u = x, h = w > i - 262 ? w - (i - 262) : 0, l = F, f = o, d = w + 258, p = s[a + u - 1], g = s[a + u]; x >= k && (r >>= 2), l > L && (l = L); do { if (s[(e = t) + u] === g && s[e + u - 1] === p && s[e] === s[a] && s[++e] === s[a + 1]) { a += 2, e++; do {} while (s[++a] === s[++e] && s[++a] === s[++e] && s[++a] === s[++e] && s[++a] === s[++e] && s[++a] === s[++e] && s[++a] === s[++e] && s[++a] === s[++e] && s[++a] === s[++e] && a < d); if (n = 258 - (d - a), a = d - 258, n > u) { if (N = t, u = n, n >= l) break; p = s[a + u - 1], g = s[a + u]; } } } while ((t = 65535 & c[t & f]) > h && 0 != --r); return u <= L ? u : L; } function st(t) { return t.total_in = t.total_out = 0, t.msg = null, U.pending = 0, U.pending_out = 0, e = 113, r = 0, z.dyn_tree = I, z.stat_desc = dt.static_l_desc, H.dyn_tree = C, H.stat_desc = dt.static_d_desc, W.dyn_tree = j, W.stat_desc = dt.static_bl_desc, T = 0, D = 0, R = 8, V(), function () { var t; for (u = 2 * i, h[f - 1] = 0, t = 0; t < f - 1; t++) { h[t] = 0; } _ = bt[S].max_lazy, k = bt[S].good_length, F = bt[S].nice_length, A = bt[S].max_chain, w = 0, m = 0, L = 0, v = x = 2, y = 0, l = 0; }(), 0; } U.depth = [], U.bl_count = [], U.heap = [], I = [], C = [], j = [], U.pqdownheap = function (t, e) { for (var n = U.heap, r = n[e], i = e << 1; i <= U.heap_len && (i < U.heap_len && wt(t, n[i + 1], n[i], U.depth) && i++, !wt(t, r, n[i], U.depth));) { n[e] = n[i], e = i, i <<= 1; } n[e] = r; }, U.deflateInit = function (t, e, r, u, l, m) { return u || (u = 8), l || (l = 8), m || (m = 0), t.msg = null, -1 === e && (e = 6), l < 1 || l > 9 || 8 !== u || r < 9 || r > 15 || e < 0 || e > 9 || m < 0 || m > 2 ? -2 : (t.dstate = U, o = (i = 1 << (a = r)) - 1, p = (f = 1 << (d = l + 7)) - 1, g = Math.floor((d + 3 - 1) / 3), s = new Uint8Array(2 * i), c = [], h = [], O = 1 << l + 6, U.pending_buf = new Uint8Array(4 * O), n = 4 * O, E = Math.floor(O / 2), B = 3 * O, S = e, P = m, st(t)); }, U.deflateEnd = function () { return 42 !== e && 113 !== e && 666 !== e ? -2 : (U.pending_buf = null, h = null, c = null, s = null, U.dstate = null, 113 === e ? -3 : 0); }, U.deflateParams = function (t, e, n) { var r = 0; return -1 === e && (e = 6), e < 0 || e > 9 || n < 0 || n > 2 ? -2 : (bt[S].func !== bt[e].func && 0 !== t.total_in && (r = t.deflate(1)), S !== e && (_ = bt[S = e].max_lazy, k = bt[S].good_length, F = bt[S].nice_length, A = bt[S].max_chain), P = n, r); }, U.deflateSetDictionary = function (t, n, r) { var a, u = r, f = 0; if (!n || 42 !== e) return -2; if (u < 3) return 0; for (u > i - 262 && (f = r - (u = i - 262)), s.set(n.subarray(f, f + u), 0), w = u, m = u, l = ((l = 255 & s[0]) << g ^ 255 & s[1]) & p, a = 0; a <= u - 3; a++) { l = (l << g ^ 255 & s[a + 2]) & p, c[a & o] = h[l], h[l] = a; } return 0; }, U.deflate = function (u, d) { var A, k, F, I, C, j; if (d > 4 || d < 0) return -2; if (!u.next_out || !u.next_in && 0 !== u.avail_in || 666 === e && 4 !== d) return u.msg = yt[4], -2; if (0 === u.avail_out) return u.msg = yt[7], -5; if (t = u, I = r, r = d, 42 === e && (k = 8 + (a - 8 << 4) << 8, (F = (S - 1 & 255) >> 1) > 3 && (F = 3), k |= F << 6, 0 !== w && (k |= 32), e = 113, Y((j = k += 31 - k % 31) >> 8 & 255), Y(255 & j)), 0 !== U.pending) { if (t.flush_pending(), 0 === t.avail_out) return r = -1, 0; } else if (0 === t.avail_in && d <= I && 4 !== d) return t.msg = yt[7], -5; if (666 === e && 0 !== t.avail_in) return u.msg = yt[7], -5; if (0 !== t.avail_in || 0 !== L || 0 !== d && 666 !== e) { switch (C = -1, bt[S].func) { case 0: C = function (e) { var r, a = 65535; for (a > n - 5 && (a = n - 5);;) { if (L <= 1) { if (at(), 0 === L && 0 === e) return 0; if (0 === L) break; } if (w += L, L = 0, r = m + a, (0 === w || w >= r) && (L = w - r, w = r, it(!1), 0 === t.avail_out)) return 0; if (w - m >= i - 262 && (it(!1), 0 === t.avail_out)) return 0; } return it(4 === e), 0 === t.avail_out ? 4 === e ? 2 : 0 : 4 === e ? 3 : 1; }(d); break; case 1: C = function (e) { for (var n, r = 0;;) { if (L < 262) { if (at(), L < 262 && 0 === e) return 0; if (0 === L) break; } if (L >= 3 && (l = (l << g ^ 255 & s[w + 2]) & p, r = 65535 & h[l], c[w & o] = h[l], h[l] = w), 0 !== r && (w - r & 65535) <= i - 262 && 2 !== P && (v = ot(r)), v >= 3) { if (n = Q(w - N, v - 3), L -= v, v <= _ && L >= 3) { v--; do { w++, l = (l << g ^ 255 & s[w + 2]) & p, r = 65535 & h[l], c[w & o] = h[l], h[l] = w; } while (0 != --v); w++; } else w += v, v = 0, l = ((l = 255 & s[w]) << g ^ 255 & s[w + 1]) & p; } else n = Q(0, 255 & s[w]), L--, w++; if (n && (it(!1), 0 === t.avail_out)) return 0; } return it(4 === e), 0 === t.avail_out ? 4 === e ? 2 : 0 : 4 === e ? 3 : 1; }(d); break; case 2: C = function (e) { for (var n, r, a = 0;;) { if (L < 262) { if (at(), L < 262 && 0 === e) return 0; if (0 === L) break; } if (L >= 3 && (l = (l << g ^ 255 & s[w + 2]) & p, a = 65535 & h[l], c[w & o] = h[l], h[l] = w), x = v, b = N, v = 2, 0 !== a && x < _ && (w - a & 65535) <= i - 262 && (2 !== P && (v = ot(a)), v <= 5 && (1 === P || 3 === v && w - N > 4096) && (v = 2)), x >= 3 && v <= x) { r = w + L - 3, n = Q(w - 1 - b, x - 3), L -= x - 1, x -= 2; do { ++w <= r && (l = (l << g ^ 255 & s[w + 2]) & p, a = 65535 & h[l], c[w & o] = h[l], h[l] = w); } while (0 != --x); if (y = 0, v = 2, w++, n && (it(!1), 0 === t.avail_out)) return 0; } else if (0 !== y) { if ((n = Q(0, 255 & s[w - 1])) && it(!1), w++, L--, 0 === t.avail_out) return 0; } else y = 1, w++, L--; } return 0 !== y && (n = Q(0, 255 & s[w - 1]), y = 0), it(4 === e), 0 === t.avail_out ? 4 === e ? 2 : 0 : 4 === e ? 3 : 1; }(d); } if (2 !== C && 3 !== C || (e = 666), 0 === C || 2 === C) return 0 === t.avail_out && (r = -1), 0; if (1 === C) { if (1 === d) X(2, 3), K(256, dt.static_ltree), $(), 1 + R + 10 - D < 9 && (X(2, 3), K(256, dt.static_ltree), $()), R = 7;else if (nt(0, 0, !1), 3 === d) for (A = 0; A < f; A++) { h[A] = 0; } if (t.flush_pending(), 0 === t.avail_out) return r = -1, 0; } } return 4 !== d ? 0 : 1; }; } function Lt() { this.next_in_index = 0, this.next_out_index = 0, this.avail_in = 0, this.total_in = 0, this.avail_out = 0, this.total_out = 0; } function xt(t) { var e = new Lt(), n = new Uint8Array(512), r = t ? t.level : -1; void 0 === r && (r = -1), e.deflateInit(r), e.next_out = n, this.append = function (t, r) { var i, a = [], o = 0, s = 0, u = 0; if (t.length) { e.next_in_index = 0, e.next_in = t, e.avail_in = t.length; do { if (e.next_out_index = 0, e.avail_out = 512, 0 !== e.deflate(0)) throw new Error("deflating: " + e.msg); e.next_out_index && (512 === e.next_out_index ? a.push(new Uint8Array(n)) : a.push(new Uint8Array(n.subarray(0, e.next_out_index)))), u += e.next_out_index, r && e.next_in_index > 0 && e.next_in_index !== o && (r(e.next_in_index), o = e.next_in_index); } while (e.avail_in > 0 || 0 === e.avail_out); return i = new Uint8Array(u), a.forEach(function (t) { i.set(t, s), s += t.length; }), i; } }, this.flush = function () { var t, r, i = [], a = 0, o = 0; do { if (e.next_out_index = 0, e.avail_out = 512, 1 !== (t = e.deflate(4)) && 0 !== t) throw new Error("deflating: " + e.msg); 512 - e.avail_out > 0 && i.push(new Uint8Array(n.subarray(0, e.next_out_index))), o += e.next_out_index; } while (e.avail_in > 0 || 0 === e.avail_out); return e.deflateEnd(), r = new Uint8Array(o), i.forEach(function (t) { r.set(t, a), a += t.length; }), r; }; } /** * @license * jsPDF filters PlugIn * Copyright (c) 2014 Aras Abbasi * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ Lt.prototype = { deflateInit: function deflateInit(t, e) { return this.dstate = new Nt(), e || (e = 15), this.dstate.deflateInit(this, t, e); }, deflate: function deflate(t) { return this.dstate ? this.dstate.deflate(this, t) : -2; }, deflateEnd: function deflateEnd() { if (!this.dstate) return -2; var t = this.dstate.deflateEnd(); return this.dstate = null, t; }, deflateParams: function deflateParams(t, e) { return this.dstate ? this.dstate.deflateParams(this, t, e) : -2; }, deflateSetDictionary: function deflateSetDictionary(t, e) { return this.dstate ? this.dstate.deflateSetDictionary(this, t, e) : -2; }, read_buf: function read_buf(t, e, n) { var r = this.avail_in; return r > n && (r = n), 0 === r ? 0 : (this.avail_in -= r, t.set(this.next_in.subarray(this.next_in_index, this.next_in_index + r), e), this.next_in_index += r, this.total_in += r, r); }, flush_pending: function flush_pending() { var t = this.dstate.pending; t > this.avail_out && (t = this.avail_out), 0 !== t && (this.next_out.set(this.dstate.pending_buf.subarray(this.dstate.pending_out, this.dstate.pending_out + t), this.next_out_index), this.next_out_index += t, this.dstate.pending_out += t, this.total_out += t, this.avail_out -= t, this.dstate.pending -= t, 0 === this.dstate.pending && (this.dstate.pending_out = 0)); } }, function (t) { var e = function e(t) { var e, n, r, i, a, o, s, u, c, h; for (/[^\x00-\xFF]/.test(t), n = [], r = 0, i = (t += e = "\0\0\0\0".slice(t.length % 4 || 4)).length; i > r; r += 4) { 0 !== (a = (t.charCodeAt(r) << 24) + (t.charCodeAt(r + 1) << 16) + (t.charCodeAt(r + 2) << 8) + t.charCodeAt(r + 3)) ? (o = (a = ((a = ((a = ((a = (a - (h = a % 85)) / 85) - (c = a % 85)) / 85) - (u = a % 85)) / 85) - (s = a % 85)) / 85) % 85, n.push(o + 33, s + 33, u + 33, c + 33, h + 33)) : n.push(122); } return function (t, e) { for (var n = e; n > 0; n--) { t.pop(); } }(n, e.length), String.fromCharCode.apply(String, n) + "~>"; }, n = function n(t) { var e, n, r, i, a, o = String, s = "length", u = 255, c = "charCodeAt", h = "slice", l = "replace"; for (t[h](-2), t = t[h](0, -2)[l](/\s/g, "")[l]("z", "!!!!!"), r = [], i = 0, a = (t += e = "uuuuu"[h](t[s] % 5 || 5))[s]; a > i; i += 5) { n = 52200625 * (t[c](i) - 33) + 614125 * (t[c](i + 1) - 33) + 7225 * (t[c](i + 2) - 33) + 85 * (t[c](i + 3) - 33) + (t[c](i + 4) - 33), r.push(u & n >> 24, u & n >> 16, u & n >> 8, u & n); } return function (t, e) { for (var n = e; n > 0; n--) { t.pop(); } }(r, e[s]), o.fromCharCode.apply(o, r); }, r = function r(t) { var e = new RegExp(/^([0-9A-Fa-f]{2})+$/); if (-1 !== (t = t.replace(/\s/g, "")).indexOf(">") && (t = t.substr(0, t.indexOf(">"))), t.length % 2 && (t += "0"), !1 === e.test(t)) return ""; for (var n = "", r = 0; r < t.length; r += 2) { n += String.fromCharCode("0x" + (t[r] + t[r + 1])); } return n; }, i = function i(e) { for (var n, r, i, a, o, s = [], u = e.length; u--;) { s[u] = e.charCodeAt(u); } return n = t.adler32cs.from(e), e = (r = new xt(6)).append(new Uint8Array(s)), i = e, a = r.flush(), (o = new Uint8Array(i.byteLength + a.byteLength)).set(new Uint8Array(i), 0), o.set(new Uint8Array(a), i.byteLength), e = o, (s = new Uint8Array(e.byteLength + 6)).set(new Uint8Array([120, 156])), s.set(e, 2), s.set(new Uint8Array([255 & n, n >> 8 & 255, n >> 16 & 255, n >> 24 & 255]), e.byteLength + 2), e = s.reduce(function (t, e) { return t + String.fromCharCode(e); }, ""); }; t.processDataByFilters = function (t, a) { var o = 0, s = t || "", u = []; for ("string" == typeof (a = a || []) && (a = [a]), o = 0; o < a.length; o += 1) { switch (a[o]) { case "ASCII85Decode": case "/ASCII85Decode": s = n(s), u.push("/ASCII85Encode"); break; case "ASCII85Encode": case "/ASCII85Encode": s = e(s), u.push("/ASCII85Decode"); break; case "ASCIIHexDecode": case "/ASCIIHexDecode": s = r(s), u.push("/ASCIIHexEncode"); break; case "ASCIIHexEncode": case "/ASCIIHexEncode": s = s.split("").map(function (t) { return ("0" + t.charCodeAt().toString(16)).slice(-2); }).join("") + ">", u.push("/ASCIIHexDecode"); break; case "FlateEncode": case "/FlateEncode": s = i(s), u.push("/FlateDecode"); break; default: throw new Error('The filter: "' + a[o] + '" is not implemented'); } } return { data: s, reverseChain: u.reverse().join(" ") }; }; }(g.API), /** * @license * jsPDF fileloading PlugIn * Copyright (c) 2018 Aras Abbasi (aras.abbasi@gmail.com) * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { t.loadFile = function (t, e, n) { return function (t, e, n) { e = !1 !== e, n = "function" == typeof n ? n : function () {}; var r = void 0; try { r = function (t, e, n) { var r = new XMLHttpRequest(), i = 0, a = function a(t) { var e = t.length, n = [], r = String.fromCharCode; for (i = 0; i < e; i += 1) { n.push(r(255 & t.charCodeAt(i))); } return n.join(""); }; if (r.open("GET", t, !e), r.overrideMimeType("text/plain; charset=x-user-defined"), !1 === e && (r.onload = function () { 200 === r.status ? n(a(this.responseText)) : n(void 0); }), r.send(null), e && 200 === r.status) return a(r.responseText); }(t, e, n); } catch (t) {} return r; }(t, e, n); }, t.loadImageFile = t.loadFile; }(g.API), /** * @license * Copyright (c) 2018 Erik Koopmans * Released under the MIT License. * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (e) { function n() { return (t.html2canvas ? Promise.resolve(t.html2canvas) : Promise.resolve().then(function () { return html2canvas$1; }))["catch"](function (t) { return Promise.reject(new Error("Could not load dompurify: " + t)); }).then(function (t) { return t["default"] ? t["default"] : t; }); } function r() { return (t.DOMPurify ? Promise.resolve(t.DOMPurify) : Promise.resolve().then(function () { return purify$1; }))["catch"](function (t) { return Promise.reject(new Error("Could not load dompurify: " + t)); }).then(function (t) { return t["default"] ? t["default"] : t; }); } var i = function i(t) { var e = _typeof(t); return "undefined" === e ? "undefined" : "string" === e || t instanceof String ? "string" : "number" === e || t instanceof Number ? "number" : "function" === e || t instanceof Function ? "function" : t && t.constructor === Array ? "array" : t && 1 === t.nodeType ? "element" : "object" === e ? "object" : "unknown"; }, a = function a(t, e) { var n = document.createElement(t); for (var r in e.className && (n.className = e.className), e.innerHTML && e.dompurify && (n.innerHTML = e.dompurify.sanitize(e.innerHTML)), e.style) { n.style[r] = e.style[r]; } return n; }, o = function o(t, e) { for (var n = 3 === t.nodeType ? document.createTextNode(t.nodeValue) : t.cloneNode(!1), r = t.firstChild; r; r = r.nextSibling) { !0 !== e && 1 === r.nodeType && "SCRIPT" === r.nodeName || n.appendChild(o(r, e)); } return 1 === t.nodeType && ("CANVAS" === t.nodeName ? (n.width = t.width, n.height = t.height, n.getContext("2d").drawImage(t, 0, 0)) : "TEXTAREA" !== t.nodeName && "SELECT" !== t.nodeName || (n.value = t.value), n.addEventListener("load", function () { n.scrollTop = t.scrollTop, n.scrollLeft = t.scrollLeft; }, !0)), n; }, s = function t(e) { var n = Object.assign(t.convert(Promise.resolve()), JSON.parse(JSON.stringify(t.template))), r = t.convert(Promise.resolve(), n); return r = (r = r.setProgress(1, t, 1, [t])).set(e); }; (s.prototype = Object.create(Promise.prototype)).constructor = s, s.convert = function (t, e) { return t.__proto__ = e || s.prototype, t; }, s.template = { prop: { src: null, container: null, overlay: null, canvas: null, img: null, pdf: null, pageSize: null, callback: function callback() {} }, progress: { val: 0, state: null, n: 0, stack: [] }, opt: { filename: "file.pdf", margin: [0, 0, 0, 0], enableLinks: !0, x: 0, y: 0, html2canvas: {}, jsPDF: {}, backgroundColor: "transparent" } }, s.prototype.from = function (t, e) { return this.then(function () { switch (e = e || function (t) { switch (i(t)) { case "string": return "string"; case "element": return "canvas" === t.nodeName.toLowerCase ? "canvas" : "element"; default: return "unknown"; } }(t)) { case "string": return this.then(r).then(function (e) { return this.set({ src: a("div", { innerHTML: t, dompurify: e }) }); }); case "element": return this.set({ src: t }); case "canvas": return this.set({ canvas: t }); case "img": return this.set({ img: t }); default: return this.error("Unknown source type."); } }); }, s.prototype.to = function (t) { switch (t) { case "container": return this.toContainer(); case "canvas": return this.toCanvas(); case "img": return this.toImg(); case "pdf": return this.toPdf(); default: return this.error("Invalid target."); } }, s.prototype.toContainer = function () { return this.thenList([function () { return this.prop.src || this.error("Cannot duplicate - no source HTML."); }, function () { return this.prop.pageSize || this.setPageSize(); }]).then(function () { var t = { position: "relative", display: "inline-block", width: Math.max(this.prop.src.clientWidth, this.prop.src.scrollWidth, this.prop.src.offsetWidth) + "px", left: 0, right: 0, top: 0, margin: "auto", backgroundColor: this.opt.backgroundColor }, e = o(this.prop.src, this.opt.html2canvas.javascriptEnabled); "BODY" === e.tagName && (t.height = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) + "px"), this.prop.overlay = a("div", { className: "html2pdf__overlay", style: { position: "fixed", overflow: "hidden", zIndex: 1e3, left: "-100000px", right: 0, bottom: 0, top: 0 } }), this.prop.container = a("div", { className: "html2pdf__container", style: t }), this.prop.container.appendChild(e), this.prop.container.firstChild.appendChild(a("div", { style: { clear: "both", border: "0 none transparent", margin: 0, padding: 0, height: 0 } })), this.prop.container.style["float"] = "none", this.prop.overlay.appendChild(this.prop.container), document.body.appendChild(this.prop.overlay), this.prop.container.firstChild.style.position = "relative", this.prop.container.height = Math.max(this.prop.container.firstChild.clientHeight, this.prop.container.firstChild.scrollHeight, this.prop.container.firstChild.offsetHeight) + "px"; }); }, s.prototype.toCanvas = function () { var t = [function () { return document.body.contains(this.prop.container) || this.toContainer(); }]; return this.thenList(t).then(n).then(function (t) { var e = Object.assign({}, this.opt.html2canvas); return delete e.onrendered, t(this.prop.container, e); }).then(function (t) { (this.opt.html2canvas.onrendered || function () {})(t), this.prop.canvas = t, document.body.removeChild(this.prop.overlay); }); }, s.prototype.toContext2d = function () { var t = [function () { return document.body.contains(this.prop.container) || this.toContainer(); }]; return this.thenList(t).then(n).then(function (t) { var e = this.opt.jsPDF, n = Object.assign({ async: !0, allowTaint: !0, scale: 1, scrollX: this.opt.scrollX || 0, scrollY: this.opt.scrollY || 0, backgroundColor: "#ffffff", imageTimeout: 15e3, logging: !0, proxy: null, removeContainer: !0, foreignObjectRendering: !1, useCORS: !1 }, this.opt.html2canvas); return delete n.onrendered, e.context2d.autoPaging = !0, e.context2d.posX = this.opt.x, e.context2d.posY = this.opt.y, n.windowHeight = n.windowHeight || 0, n.windowHeight = 0 == n.windowHeight ? Math.max(this.prop.container.clientHeight, this.prop.container.scrollHeight, this.prop.container.offsetHeight) : n.windowHeight, t(this.prop.container, n); }).then(function (t) { (this.opt.html2canvas.onrendered || function () {})(t), this.prop.canvas = t, document.body.removeChild(this.prop.overlay); }); }, s.prototype.toImg = function () { return this.thenList([function () { return this.prop.canvas || this.toCanvas(); }]).then(function () { var t = this.prop.canvas.toDataURL("image/" + this.opt.image.type, this.opt.image.quality); this.prop.img = document.createElement("img"), this.prop.img.src = t; }); }, s.prototype.toPdf = function () { return this.thenList([function () { return this.toContext2d(); }]).then(function () { this.prop.pdf = this.prop.pdf || this.opt.jsPDF; }); }, s.prototype.output = function (t, e, n) { return "img" === (n = n || "pdf").toLowerCase() || "image" === n.toLowerCase() ? this.outputImg(t, e) : this.outputPdf(t, e); }, s.prototype.outputPdf = function (t, e) { return this.thenList([function () { return this.prop.pdf || this.toPdf(); }]).then(function () { return this.prop.pdf.output(t, e); }); }, s.prototype.outputImg = function (t) { return this.thenList([function () { return this.prop.img || this.toImg(); }]).then(function () { switch (t) { case void 0: case "img": return this.prop.img; case "datauristring": case "dataurlstring": return this.prop.img.src; case "datauri": case "dataurl": return document.location.href = this.prop.img.src; default: throw 'Image output type "' + t + '" is not supported.'; } }); }, s.prototype.save = function (t) { return this.thenList([function () { return this.prop.pdf || this.toPdf(); }]).set(t ? { filename: t } : null).then(function () { this.prop.pdf.save(this.opt.filename); }); }, s.prototype.doCallback = function () { return this.thenList([function () { return this.prop.pdf || this.toPdf(); }]).then(function () { this.prop.callback(this.prop.pdf); }); }, s.prototype.set = function (t) { if ("object" !== i(t)) return this; var e = Object.keys(t || {}).map(function (e) { if (e in s.template.prop) return function () { this.prop[e] = t[e]; }; switch (e) { case "margin": return this.setMargin.bind(this, t.margin); case "jsPDF": return function () { return this.opt.jsPDF = t.jsPDF, this.setPageSize(); }; case "pageSize": return this.setPageSize.bind(this, t.pageSize); default: return function () { this.opt[e] = t[e]; }; } }, this); return this.then(function () { return this.thenList(e); }); }, s.prototype.get = function (t, e) { return this.then(function () { var n = t in s.template.prop ? this.prop[t] : this.opt[t]; return e ? e(n) : n; }); }, s.prototype.setMargin = function (t) { return this.then(function () { switch (i(t)) { case "number": t = [t, t, t, t]; case "array": if (2 === t.length && (t = [t[0], t[1], t[0], t[1]]), 4 === t.length) break; default: return this.error("Invalid margin array."); } this.opt.margin = t; }).then(this.setPageSize); }, s.prototype.setPageSize = function (t) { function e(t, e) { return Math.floor(t * e / 72 * 96); } return this.then(function () { (t = t || g.getPageSize(this.opt.jsPDF)).hasOwnProperty("inner") || (t.inner = { width: t.width - this.opt.margin[1] - this.opt.margin[3], height: t.height - this.opt.margin[0] - this.opt.margin[2] }, t.inner.px = { width: e(t.inner.width, t.k), height: e(t.inner.height, t.k) }, t.inner.ratio = t.inner.height / t.inner.width), this.prop.pageSize = t; }); }, s.prototype.setProgress = function (t, e, n, r) { return null != t && (this.progress.val = t), null != e && (this.progress.state = e), null != n && (this.progress.n = n), null != r && (this.progress.stack = r), this.progress.ratio = this.progress.val / this.progress.state, this; }, s.prototype.updateProgress = function (t, e, n, r) { return this.setProgress(t ? this.progress.val + t : null, e || null, n ? this.progress.n + n : null, r ? this.progress.stack.concat(r) : null); }, s.prototype.then = function (t, e) { var n = this; return this.thenCore(t, e, function (t, e) { return n.updateProgress(null, null, 1, [t]), Promise.prototype.then.call(this, function (e) { return n.updateProgress(null, t), e; }).then(t, e).then(function (t) { return n.updateProgress(1), t; }); }); }, s.prototype.thenCore = function (t, e, n) { n = n || Promise.prototype.then; t && (t = t.bind(this)), e && (e = e.bind(this)); var r = -1 !== Promise.toString().indexOf("[native code]") && "Promise" === Promise.name ? this : s.convert(Object.assign({}, this), Promise.prototype), i = n.call(r, t, e); return s.convert(i, this.__proto__); }, s.prototype.thenExternal = function (t, e) { return Promise.prototype.then.call(this, t, e); }, s.prototype.thenList = function (t) { var e = this; return t.forEach(function (t) { e = e.thenCore(t); }), e; }, s.prototype["catch"] = function (t) { t && (t = t.bind(this)); var e = Promise.prototype["catch"].call(this, t); return s.convert(e, this); }, s.prototype.catchExternal = function (t) { return Promise.prototype["catch"].call(this, t); }, s.prototype.error = function (t) { return this.then(function () { throw new Error(t); }); }, s.prototype.using = s.prototype.set, s.prototype.saveAs = s.prototype.save, s.prototype["export"] = s.prototype.output, s.prototype.run = s.prototype.then, g.getPageSize = function (t, e, n) { if ("object" == _typeof(t)) { var r = t; t = r.orientation, e = r.unit || e, n = r.format || n; } e = e || "mm", n = n || "a4", t = ("" + (t || "P")).toLowerCase(); var i, a = ("" + n).toLowerCase(), o = { a0: [2383.94, 3370.39], a1: [1683.78, 2383.94], a2: [1190.55, 1683.78], a3: [841.89, 1190.55], a4: [595.28, 841.89], a5: [419.53, 595.28], a6: [297.64, 419.53], a7: [209.76, 297.64], a8: [147.4, 209.76], a9: [104.88, 147.4], a10: [73.7, 104.88], b0: [2834.65, 4008.19], b1: [2004.09, 2834.65], b2: [1417.32, 2004.09], b3: [1000.63, 1417.32], b4: [708.66, 1000.63], b5: [498.9, 708.66], b6: [354.33, 498.9], b7: [249.45, 354.33], b8: [175.75, 249.45], b9: [124.72, 175.75], b10: [87.87, 124.72], c0: [2599.37, 3676.54], c1: [1836.85, 2599.37], c2: [1298.27, 1836.85], c3: [918.43, 1298.27], c4: [649.13, 918.43], c5: [459.21, 649.13], c6: [323.15, 459.21], c7: [229.61, 323.15], c8: [161.57, 229.61], c9: [113.39, 161.57], c10: [79.37, 113.39], dl: [311.81, 623.62], letter: [612, 792], "government-letter": [576, 756], legal: [612, 1008], "junior-legal": [576, 360], ledger: [1224, 792], tabloid: [792, 1224], "credit-card": [153, 243] }; switch (e) { case "pt": i = 1; break; case "mm": i = 72 / 25.4; break; case "cm": i = 72 / 2.54; break; case "in": i = 72; break; case "px": i = .75; break; case "pc": case "em": i = 12; break; case "ex": i = 6; break; default: throw "Invalid unit: " + e; } var s, u = 0, c = 0; if (o.hasOwnProperty(a)) u = o[a][1] / i, c = o[a][0] / i;else try { u = n[1], c = n[0]; } catch (t) { throw new Error("Invalid format: " + n); } if ("p" === t || "portrait" === t) t = "p", c > u && (s = c, c = u, u = s);else { if ("l" !== t && "landscape" !== t) throw "Invalid orientation: " + t; t = "l", u > c && (s = c, c = u, u = s); } return { width: c, height: u, unit: e, k: i, orientation: t }; }, e.html = function (t, e) { (e = e || {}).callback = e.callback || function () {}, e.html2canvas = e.html2canvas || {}, e.html2canvas.canvas = e.html2canvas.canvas || this.canvas, e.jsPDF = e.jsPDF || this; var n = new s(e); return e.worker ? n : n.from(t).doCallback(); }; }(g.API), g.API.addJS = function (t) { return vt = t, this.internal.events.subscribe("postPutResources", function () { gt = this.internal.newObject(), this.internal.out("<<"), this.internal.out("/Names [(EmbeddedJS) " + (gt + 1) + " 0 R]"), this.internal.out(">>"), this.internal.out("endobj"), mt = this.internal.newObject(), this.internal.out("<<"), this.internal.out("/S /JavaScript"), this.internal.out("/JS (" + vt + ")"), this.internal.out(">>"), this.internal.out("endobj"); }), this.internal.events.subscribe("putCatalog", function () { void 0 !== gt && void 0 !== mt && this.internal.out("/Names <</JavaScript " + gt + " 0 R>>"); }), this; }, /** * @license * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { var e; t.events.push(["postPutResources", function () { var t = this, n = /^(\d+) 0 obj$/; if (this.outline.root.children.length > 0) for (var r = t.outline.render().split(/\r\n/), i = 0; i < r.length; i++) { var a = r[i], o = n.exec(a); if (null != o) { var s = o[1]; t.internal.newObjectDeferredBegin(s, !1); } t.internal.write(a); } if (this.outline.createNamedDestinations) { var u = this.internal.pages.length, c = []; for (i = 0; i < u; i++) { var h = t.internal.newObject(); c.push(h); var l = t.internal.getPageInfo(i + 1); t.internal.write("<< /D[" + l.objId + " 0 R /XYZ null null null]>> endobj"); } var f = t.internal.newObject(); t.internal.write("<< /Names [ "); for (i = 0; i < c.length; i++) { t.internal.write("(page_" + (i + 1) + ")" + c[i] + " 0 R"); } t.internal.write(" ] >>", "endobj"), e = t.internal.newObject(), t.internal.write("<< /Dests " + f + " 0 R"), t.internal.write(">>", "endobj"); } }]), t.events.push(["putCatalog", function () { this.outline.root.children.length > 0 && (this.internal.write("/Outlines", this.outline.makeRef(this.outline.root)), this.outline.createNamedDestinations && this.internal.write("/Names " + e + " 0 R")); }]), t.events.push(["initialized", function () { var t = this; t.outline = { createNamedDestinations: !1, root: { children: [] } }, t.outline.add = function (t, e, n) { var r = { title: e, options: n, children: [] }; return null == t && (t = this.root), t.children.push(r), r; }, t.outline.render = function () { return this.ctx = {}, this.ctx.val = "", this.ctx.pdf = t, this.genIds_r(this.root), this.renderRoot(this.root), this.renderItems(this.root), this.ctx.val; }, t.outline.genIds_r = function (e) { e.id = t.internal.newObjectDeferred(); for (var n = 0; n < e.children.length; n++) { this.genIds_r(e.children[n]); } }, t.outline.renderRoot = function (t) { this.objStart(t), this.line("/Type /Outlines"), t.children.length > 0 && (this.line("/First " + this.makeRef(t.children[0])), this.line("/Last " + this.makeRef(t.children[t.children.length - 1]))), this.line("/Count " + this.count_r({ count: 0 }, t)), this.objEnd(); }, t.outline.renderItems = function (e) { for (var n = this.ctx.pdf.internal.getVerticalCoordinateString, r = 0; r < e.children.length; r++) { var i = e.children[r]; this.objStart(i), this.line("/Title " + this.makeString(i.title)), this.line("/Parent " + this.makeRef(e)), r > 0 && this.line("/Prev " + this.makeRef(e.children[r - 1])), r < e.children.length - 1 && this.line("/Next " + this.makeRef(e.children[r + 1])), i.children.length > 0 && (this.line("/First " + this.makeRef(i.children[0])), this.line("/Last " + this.makeRef(i.children[i.children.length - 1]))); var a = this.count = this.count_r({ count: 0 }, i); if (a > 0 && this.line("/Count " + a), i.options && i.options.pageNumber) { var o = t.internal.getPageInfo(i.options.pageNumber); this.line("/Dest [" + o.objId + " 0 R /XYZ 0 " + n(0) + " 0]"); } this.objEnd(); } for (var s = 0; s < e.children.length; s++) { this.renderItems(e.children[s]); } }, t.outline.line = function (t) { this.ctx.val += t + "\r\n"; }, t.outline.makeRef = function (t) { return t.id + " 0 R"; }, t.outline.makeString = function (e) { return "(" + t.internal.pdfEscape(e) + ")"; }, t.outline.objStart = function (t) { this.ctx.val += "\r\n" + t.id + " 0 obj\r\n<<\r\n"; }, t.outline.objEnd = function () { this.ctx.val += ">> \r\nendobj\r\n"; }, t.outline.count_r = function (t, e) { for (var n = 0; n < e.children.length; n++) { t.count++, this.count_r(t, e.children[n]); } return t.count; }; }]); }(g.API), /** * @license * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { var e = [192, 193, 194, 195, 196, 197, 198, 199]; t.processJPEG = function (t, n, r, i, a, o) { var s, u = this.decode.DCT_DECODE, c = null; if ("string" == typeof t || this.__addimage__.isArrayBuffer(t) || this.__addimage__.isArrayBufferView(t)) { switch (t = a || t, t = this.__addimage__.isArrayBuffer(t) ? new Uint8Array(t) : t, (s = function (t) { for (var n, r = 256 * t.charCodeAt(4) + t.charCodeAt(5), i = t.length, a = { width: 0, height: 0, numcomponents: 1 }, o = 4; o < i; o += 2) { if (o += r, -1 !== e.indexOf(t.charCodeAt(o + 1))) { n = 256 * t.charCodeAt(o + 5) + t.charCodeAt(o + 6), a = { width: 256 * t.charCodeAt(o + 7) + t.charCodeAt(o + 8), height: n, numcomponents: t.charCodeAt(o + 9) }; break; } r = 256 * t.charCodeAt(o + 2) + t.charCodeAt(o + 3); } return a; }(t = this.__addimage__.isArrayBufferView(t) ? this.__addimage__.arrayBufferToBinaryString(t) : t)).numcomponents) { case 1: o = this.color_spaces.DEVICE_GRAY; break; case 4: o = this.color_spaces.DEVICE_CMYK; break; case 3: o = this.color_spaces.DEVICE_RGB; } c = { data: t, width: s.width, height: s.height, colorSpace: o, bitsPerComponent: 8, filter: u, index: n, alias: r }; } return c; }; }(g.API); /** * @license * Extracted from pdf.js * https://github.com/andreasgal/pdf.js * * Copyright (c) 2011 Mozilla Foundation * * Contributors: Andreas Gal <gal@mozilla.com> * Chris G Jones <cjones@mozilla.com> * Shaon Barman <shaon.barman@gmail.com> * Vivien Nicolas <21@vingtetun.org> * Justin D'Arcangelo <justindarc@gmail.com> * Yury Delendik * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ var At, _t, St, Pt, kt, Ft = function () { function t() { this.pos = 0, this.bufferLength = 0, this.eof = !1, this.buffer = null; } return t.prototype = { ensureBuffer: function ensureBuffer(t) { var e = this.buffer, n = e ? e.byteLength : 0; if (t < n) return e; for (var r = 512; r < t;) { r <<= 1; } for (var i = new Uint8Array(r), a = 0; a < n; ++a) { i[a] = e[a]; } return this.buffer = i; }, getByte: function getByte() { for (var t = this.pos; this.bufferLength <= t;) { if (this.eof) return null; this.readBlock(); } return this.buffer[this.pos++]; }, getBytes: function getBytes(t) { var e = this.pos; if (t) { this.ensureBuffer(e + t); for (var n = e + t; !this.eof && this.bufferLength < n;) { this.readBlock(); } var r = this.bufferLength; n > r && (n = r); } else { for (; !this.eof;) { this.readBlock(); } n = this.bufferLength; } return this.pos = n, this.buffer.subarray(e, n); }, lookChar: function lookChar() { for (var t = this.pos; this.bufferLength <= t;) { if (this.eof) return null; this.readBlock(); } return String.fromCharCode(this.buffer[this.pos]); }, getChar: function getChar() { for (var t = this.pos; this.bufferLength <= t;) { if (this.eof) return null; this.readBlock(); } return String.fromCharCode(this.buffer[this.pos++]); }, makeSubStream: function makeSubStream(t, e, n) { for (var r = t + e; this.bufferLength <= r && !this.eof;) { this.readBlock(); } return new Stream(this.buffer, t, e, n); }, skip: function skip(t) { t || (t = 1), this.pos += t; }, reset: function reset() { this.pos = 0; } }, t; }(), It = ("undefined" != typeof self && self || "undefined" != typeof window && window || "undefined" != typeof global$1 && global$1 || Function('return typeof this === "object" && this.content')() || Function("return this")()).FlateStream = function () { if ("undefined" != typeof Uint32Array) { var t = new Uint32Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]), e = new Uint32Array([3, 4, 5, 6, 7, 8, 9, 10, 65547, 65549, 65551, 65553, 131091, 131095, 131099, 131103, 196643, 196651, 196659, 196667, 262211, 262227, 262243, 262259, 327811, 327843, 327875, 327907, 258, 258, 258]), n = new Uint32Array([1, 2, 3, 4, 65541, 65543, 131081, 131085, 196625, 196633, 262177, 262193, 327745, 327777, 393345, 393409, 459009, 459137, 524801, 525057, 590849, 591361, 657409, 658433, 724993, 727041, 794625, 798721, 868353, 876545]), r = [new Uint32Array([459008, 524368, 524304, 524568, 459024, 524400, 524336, 590016, 459016, 524384, 524320, 589984, 524288, 524416, 524352, 590048, 459012, 524376, 524312, 589968, 459028, 524408, 524344, 590032, 459020, 524392, 524328, 59e4, 524296, 524424, 524360, 590064, 459010, 524372, 524308, 524572, 459026, 524404, 524340, 590024, 459018, 524388, 524324, 589992, 524292, 524420, 524356, 590056, 459014, 524380, 524316, 589976, 459030, 524412, 524348, 590040, 459022, 524396, 524332, 590008, 524300, 524428, 524364, 590072, 459009, 524370, 524306, 524570, 459025, 524402, 524338, 590020, 459017, 524386, 524322, 589988, 524290, 524418, 524354, 590052, 459013, 524378, 524314, 589972, 459029, 524410, 524346, 590036, 459021, 524394, 524330, 590004, 524298, 524426, 524362, 590068, 459011, 524374, 524310, 524574, 459027, 524406, 524342, 590028, 459019, 524390, 524326, 589996, 524294, 524422, 524358, 590060, 459015, 524382, 524318, 589980, 459031, 524414, 524350, 590044, 459023, 524398, 524334, 590012, 524302, 524430, 524366, 590076, 459008, 524369, 524305, 524569, 459024, 524401, 524337, 590018, 459016, 524385, 524321, 589986, 524289, 524417, 524353, 590050, 459012, 524377, 524313, 589970, 459028, 524409, 524345, 590034, 459020, 524393, 524329, 590002, 524297, 524425, 524361, 590066, 459010, 524373, 524309, 524573, 459026, 524405, 524341, 590026, 459018, 524389, 524325, 589994, 524293, 524421, 524357, 590058, 459014, 524381, 524317, 589978, 459030, 524413, 524349, 590042, 459022, 524397, 524333, 590010, 524301, 524429, 524365, 590074, 459009, 524371, 524307, 524571, 459025, 524403, 524339, 590022, 459017, 524387, 524323, 589990, 524291, 524419, 524355, 590054, 459013, 524379, 524315, 589974, 459029, 524411, 524347, 590038, 459021, 524395, 524331, 590006, 524299, 524427, 524363, 590070, 459011, 524375, 524311, 524575, 459027, 524407, 524343, 590030, 459019, 524391, 524327, 589998, 524295, 524423, 524359, 590062, 459015, 524383, 524319, 589982, 459031, 524415, 524351, 590046, 459023, 524399, 524335, 590014, 524303, 524431, 524367, 590078, 459008, 524368, 524304, 524568, 459024, 524400, 524336, 590017, 459016, 524384, 524320, 589985, 524288, 524416, 524352, 590049, 459012, 524376, 524312, 589969, 459028, 524408, 524344, 590033, 459020, 524392, 524328, 590001, 524296, 524424, 524360, 590065, 459010, 524372, 524308, 524572, 459026, 524404, 524340, 590025, 459018, 524388, 524324, 589993, 524292, 524420, 524356, 590057, 459014, 524380, 524316, 589977, 459030, 524412, 524348, 590041, 459022, 524396, 524332, 590009, 524300, 524428, 524364, 590073, 459009, 524370, 524306, 524570, 459025, 524402, 524338, 590021, 459017, 524386, 524322, 589989, 524290, 524418, 524354, 590053, 459013, 524378, 524314, 589973, 459029, 524410, 524346, 590037, 459021, 524394, 524330, 590005, 524298, 524426, 524362, 590069, 459011, 524374, 524310, 524574, 459027, 524406, 524342, 590029, 459019, 524390, 524326, 589997, 524294, 524422, 524358, 590061, 459015, 524382, 524318, 589981, 459031, 524414, 524350, 590045, 459023, 524398, 524334, 590013, 524302, 524430, 524366, 590077, 459008, 524369, 524305, 524569, 459024, 524401, 524337, 590019, 459016, 524385, 524321, 589987, 524289, 524417, 524353, 590051, 459012, 524377, 524313, 589971, 459028, 524409, 524345, 590035, 459020, 524393, 524329, 590003, 524297, 524425, 524361, 590067, 459010, 524373, 524309, 524573, 459026, 524405, 524341, 590027, 459018, 524389, 524325, 589995, 524293, 524421, 524357, 590059, 459014, 524381, 524317, 589979, 459030, 524413, 524349, 590043, 459022, 524397, 524333, 590011, 524301, 524429, 524365, 590075, 459009, 524371, 524307, 524571, 459025, 524403, 524339, 590023, 459017, 524387, 524323, 589991, 524291, 524419, 524355, 590055, 459013, 524379, 524315, 589975, 459029, 524411, 524347, 590039, 459021, 524395, 524331, 590007, 524299, 524427, 524363, 590071, 459011, 524375, 524311, 524575, 459027, 524407, 524343, 590031, 459019, 524391, 524327, 589999, 524295, 524423, 524359, 590063, 459015, 524383, 524319, 589983, 459031, 524415, 524351, 590047, 459023, 524399, 524335, 590015, 524303, 524431, 524367, 590079]), 9], i = [new Uint32Array([327680, 327696, 327688, 327704, 327684, 327700, 327692, 327708, 327682, 327698, 327690, 327706, 327686, 327702, 327694, 0, 327681, 327697, 327689, 327705, 327685, 327701, 327693, 327709, 327683, 327699, 327691, 327707, 327687, 327703, 327695, 0]), 5]; return o.prototype = Object.create(Ft.prototype), o.prototype.getBits = function (t) { for (var e, n = this.codeSize, r = this.codeBuf, i = this.bytes, o = this.bytesPos; n < t;) { void 0 === (e = i[o++]) && a("Bad encoding in flate stream"), r |= e << n, n += 8; } return e = r & (1 << t) - 1, this.codeBuf = r >> t, this.codeSize = n -= t, this.bytesPos = o, e; }, o.prototype.getCode = function (t) { for (var e = t[0], n = t[1], r = this.codeSize, i = this.codeBuf, o = this.bytes, s = this.bytesPos; r < n;) { var u; void 0 === (u = o[s++]) && a("Bad encoding in flate stream"), i |= u << r, r += 8; } var c = e[i & (1 << n) - 1], h = c >> 16, l = 65535 & c; return (0 == r || r < h || 0 == h) && a("Bad encoding in flate stream"), this.codeBuf = i >> h, this.codeSize = r - h, this.bytesPos = s, l; }, o.prototype.generateHuffmanTable = function (t) { for (var e = t.length, n = 0, r = 0; r < e; ++r) { t[r] > n && (n = t[r]); } for (var i = 1 << n, a = new Uint32Array(i), o = 1, s = 0, u = 2; o <= n; ++o, s <<= 1, u <<= 1) { for (var c = 0; c < e; ++c) { if (t[c] == o) { var h = 0, l = s; for (r = 0; r < o; ++r) { h = h << 1 | 1 & l, l >>= 1; } for (r = h; r < i; r += u) { a[r] = o << 16 | c; } ++s; } } } return [a, n]; }, o.prototype.readBlock = function () { function o(t, e, n, r, i) { for (var a = t.getBits(n) + r; a-- > 0;) { e[p++] = i; } } var s = this.getBits(3); if (1 & s && (this.eof = !0), 0 != (s >>= 1)) { var u, c; if (1 == s) u = r, c = i;else if (2 == s) { for (var h = this.getBits(5) + 257, l = this.getBits(5) + 1, f = this.getBits(4) + 4, d = Array(t.length), p = 0; p < f;) { d[t[p++]] = this.getBits(3); } for (var g = this.generateHuffmanTable(d), m = 0, v = (p = 0, h + l), b = new Array(v); p < v;) { var y = this.getCode(g); 16 == y ? o(this, b, 2, 3, m) : 17 == y ? o(this, b, 3, 3, m = 0) : 18 == y ? o(this, b, 7, 11, m = 0) : b[p++] = m = y; } u = this.generateHuffmanTable(b.slice(0, h)), c = this.generateHuffmanTable(b.slice(h, v)); } else a("Unknown block type in flate stream"); for (var w = (j = this.buffer) ? j.length : 0, N = this.bufferLength;;) { var L = this.getCode(u); if (L < 256) N + 1 >= w && (w = (j = this.ensureBuffer(N + 1)).length), j[N++] = L;else { if (256 == L) return void (this.bufferLength = N); var x = (L = e[L -= 257]) >> 16; x > 0 && (x = this.getBits(x)); m = (65535 & L) + x; L = this.getCode(c), (x = (L = n[L]) >> 16) > 0 && (x = this.getBits(x)); var A = (65535 & L) + x; N + m >= w && (w = (j = this.ensureBuffer(N + m)).length); for (var _ = 0; _ < m; ++_, ++N) { j[N] = j[N - A]; } } } } else { var S, P = this.bytes, k = this.bytesPos; void 0 === (S = P[k++]) && a("Bad block header in flate stream"); var F = S; void 0 === (S = P[k++]) && a("Bad block header in flate stream"), F |= S << 8, void 0 === (S = P[k++]) && a("Bad block header in flate stream"); var I = S; void 0 === (S = P[k++]) && a("Bad block header in flate stream"), (I |= S << 8) != (65535 & ~F) && a("Bad uncompressed block length in flate stream"), this.codeBuf = 0, this.codeSize = 0; var C = this.bufferLength, j = this.ensureBuffer(C + F), B = C + F; this.bufferLength = B; for (var O = C; O < B; ++O) { if (void 0 === (S = P[k++])) { this.eof = !0; break; } j[O] = S; } this.bytesPos = k; } }, o; } function a(t) { throw new Error(t); } function o(t) { var e = 0, n = t[e++], r = t[e++]; -1 != n && -1 != r || a("Invalid header in flate stream"), 8 != (15 & n) && a("Unknown compression method in flate stream"), ((n << 8) + r) % 31 != 0 && a("Bad FCHECK in flate stream"), 32 & r && a("FDICT bit set in flate stream"), this.bytes = t, this.bytesPos = 2, this.codeSize = 0, this.codeBuf = 0, Ft.call(this); } }(), Ct = function () { var e, n, r; function i(t) { var e, n, r, i, a, o, s, u, c, h, l, f, d, p; for (this.data = t, this.pos = 8, this.palette = [], this.imgData = [], this.transparency = {}, this.animation = null, this.text = {}, o = null;;) { switch (e = this.readUInt32(), c = function () { var t, e; for (e = [], t = 0; t < 4; ++t) { e.push(String.fromCharCode(this.data[this.pos++])); } return e; }.call(this).join("")) { case "IHDR": this.width = this.readUInt32(), this.height = this.readUInt32(), this.bits = this.data[this.pos++], this.colorType = this.data[this.pos++], this.compressionMethod = this.data[this.pos++], this.filterMethod = this.data[this.pos++], this.interlaceMethod = this.data[this.pos++]; break; case "acTL": this.animation = { numFrames: this.readUInt32(), numPlays: this.readUInt32() || 1 / 0, frames: [] }; break; case "PLTE": this.palette = this.read(e); break; case "fcTL": o && this.animation.frames.push(o), this.pos += 4, o = { width: this.readUInt32(), height: this.readUInt32(), xOffset: this.readUInt32(), yOffset: this.readUInt32() }, a = this.readUInt16(), i = this.readUInt16() || 100, o.delay = 1e3 * a / i, o.disposeOp = this.data[this.pos++], o.blendOp = this.data[this.pos++], o.data = []; break; case "IDAT": case "fdAT": for ("fdAT" === c && (this.pos += 4, e -= 4), t = (null != o ? o.data : void 0) || this.imgData, f = 0; 0 <= e ? f < e : f > e; 0 <= e ? ++f : --f) { t.push(this.data[this.pos++]); } break; case "tRNS": switch (this.transparency = {}, this.colorType) { case 3: if (r = this.palette.length / 3, this.transparency.indexed = this.read(e), this.transparency.indexed.length > r) throw new Error("More transparent colors than palette size"); if ((h = r - this.transparency.indexed.length) > 0) for (d = 0; 0 <= h ? d < h : d > h; 0 <= h ? ++d : --d) { this.transparency.indexed.push(255); } break; case 0: this.transparency.grayscale = this.read(e)[0]; break; case 2: this.transparency.rgb = this.read(e); } break; case "tEXt": s = (l = this.read(e)).indexOf(0), u = String.fromCharCode.apply(String, l.slice(0, s)), this.text[u] = String.fromCharCode.apply(String, l.slice(s + 1)); break; case "IEND": return o && this.animation.frames.push(o), this.colors = function () { switch (this.colorType) { case 0: case 3: case 4: return 1; case 2: case 6: return 3; } }.call(this), this.hasAlphaChannel = 4 === (p = this.colorType) || 6 === p, n = this.colors + (this.hasAlphaChannel ? 1 : 0), this.pixelBitlength = this.bits * n, this.colorSpace = function () { switch (this.colors) { case 1: return "DeviceGray"; case 3: return "DeviceRGB"; } }.call(this), void (this.imgData = new Uint8Array(this.imgData)); default: this.pos += e; } if (this.pos += 4, this.pos > this.data.length) throw new Error("Incomplete or corrupt PNG file"); } } i.prototype.read = function (t) { var e, n; for (n = [], e = 0; 0 <= t ? e < t : e > t; 0 <= t ? ++e : --e) { n.push(this.data[this.pos++]); } return n; }, i.prototype.readUInt32 = function () { return this.data[this.pos++] << 24 | this.data[this.pos++] << 16 | this.data[this.pos++] << 8 | this.data[this.pos++]; }, i.prototype.readUInt16 = function () { return this.data[this.pos++] << 8 | this.data[this.pos++]; }, i.prototype.decodePixels = function (t) { var e = this.pixelBitlength / 8, n = new Uint8Array(this.width * this.height * e), r = 0, i = this; if (null == t && (t = this.imgData), 0 === t.length) return new Uint8Array(0); function a(a, o, s, u) { var c, h, l, f, d, p, g, m, v, b, y, w, N, L, x, A, _, S, P, k, F, I = Math.ceil((i.width - a) / s), C = Math.ceil((i.height - o) / u), j = i.width == I && i.height == C; for (L = e * I, w = j ? n : new Uint8Array(L * C), p = t.length, N = 0, h = 0; N < C && r < p;) { switch (t[r++]) { case 0: for (f = _ = 0; _ < L; f = _ += 1) { w[h++] = t[r++]; } break; case 1: for (f = S = 0; S < L; f = S += 1) { c = t[r++], d = f < e ? 0 : w[h - e], w[h++] = (c + d) % 256; } break; case 2: for (f = P = 0; P < L; f = P += 1) { c = t[r++], l = (f - f % e) / e, x = N && w[(N - 1) * L + l * e + f % e], w[h++] = (x + c) % 256; } break; case 3: for (f = k = 0; k < L; f = k += 1) { c = t[r++], l = (f - f % e) / e, d = f < e ? 0 : w[h - e], x = N && w[(N - 1) * L + l * e + f % e], w[h++] = (c + Math.floor((d + x) / 2)) % 256; } break; case 4: for (f = F = 0; F < L; f = F += 1) { c = t[r++], l = (f - f % e) / e, d = f < e ? 0 : w[h - e], 0 === N ? x = A = 0 : (x = w[(N - 1) * L + l * e + f % e], A = l && w[(N - 1) * L + (l - 1) * e + f % e]), g = d + x - A, m = Math.abs(g - d), b = Math.abs(g - x), y = Math.abs(g - A), v = m <= b && m <= y ? d : b <= y ? x : A, w[h++] = (c + v) % 256; } break; default: throw new Error("Invalid filter algorithm: " + t[r - 1]); } if (!j) { var B = ((o + N * u) * i.width + a) * e, O = N * L; for (f = 0; f < I; f += 1) { for (var M = 0; M < e; M += 1) { n[B++] = w[O++]; } B += (s - 1) * e; } } N++; } } return t = (t = new It(t)).getBytes(), 1 == i.interlaceMethod ? (a(0, 0, 8, 8), a(4, 0, 8, 8), a(0, 4, 4, 8), a(2, 0, 4, 4), a(0, 2, 2, 4), a(1, 0, 2, 2), a(0, 1, 1, 2)) : a(0, 0, 1, 1), n; }, i.prototype.decodePalette = function () { var t, e, n, r, i, a, o, s, u; for (n = this.palette, a = this.transparency.indexed || [], i = new Uint8Array((a.length || 0) + n.length), r = 0, t = 0, e = o = 0, s = n.length; o < s; e = o += 3) { i[r++] = n[e], i[r++] = n[e + 1], i[r++] = n[e + 2], i[r++] = null != (u = a[t++]) ? u : 255; } return i; }, i.prototype.copyToImageData = function (t, e) { var n, r, i, a, o, s, u, c, h, l, f; if (r = this.colors, h = null, n = this.hasAlphaChannel, this.palette.length && (h = null != (f = this._decodedPalette) ? f : this._decodedPalette = this.decodePalette(), r = 4, n = !0), c = (i = t.data || t).length, o = h || e, a = s = 0, 1 === r) for (; a < c;) { u = h ? 4 * e[a / 4] : s, l = o[u++], i[a++] = l, i[a++] = l, i[a++] = l, i[a++] = n ? o[u++] : 255, s = u; } else for (; a < c;) { u = h ? 4 * e[a / 4] : s, i[a++] = o[u++], i[a++] = o[u++], i[a++] = o[u++], i[a++] = n ? o[u++] : 255, s = u; } }, i.prototype.decode = function () { var t; return t = new Uint8Array(this.width * this.height * 4), this.copyToImageData(t, this.decodePixels()), t; }; var a = function a() { if ("[object Window]" === Object.prototype.toString.call(t)) { try { n = t.document.createElement("canvas"), r = n.getContext("2d"); } catch (t) { return !1; } return !0; } return !1; }; return a(), e = function e(t) { var e; if (!0 === a()) return r.width = t.width, r.height = t.height, r.clearRect(0, 0, t.width, t.height), r.putImageData(t, 0, 0), (e = new Image()).src = n.toDataURL(), e; throw new Error("This method requires a Browser with Canvas-capability."); }, i.prototype.decodeFrames = function (t) { var n, r, i, a, o, s, u, c; if (this.animation) { for (c = [], r = o = 0, s = (u = this.animation.frames).length; o < s; r = ++o) { n = u[r], i = t.createImageData(n.width, n.height), a = this.decodePixels(new Uint8Array(n.data)), this.copyToImageData(i, a), n.imageData = i, c.push(n.image = e(i)); } return c; } }, i.prototype.renderFrame = function (t, e) { var n, r, i; return n = (r = this.animation.frames)[e], i = r[e - 1], 0 === e && t.clearRect(0, 0, this.width, this.height), 1 === (null != i ? i.disposeOp : void 0) ? t.clearRect(i.xOffset, i.yOffset, i.width, i.height) : 2 === (null != i ? i.disposeOp : void 0) && t.putImageData(i.imageData, i.xOffset, i.yOffset), 0 === n.blendOp && t.clearRect(n.xOffset, n.yOffset, n.width, n.height), t.drawImage(n.image, n.xOffset, n.yOffset); }, i.prototype.animate = function (t) { var _e3, n, r, i, a, o, s = this; return n = 0, o = this.animation, i = o.numFrames, r = o.frames, a = o.numPlays, (_e3 = function e() { var o, u; if (o = n++ % i, u = r[o], s.renderFrame(t, o), i > 1 && n / i < a) return s.animation._timeout = setTimeout(_e3, u.delay); })(); }, i.prototype.stopAnimation = function () { var t; return clearTimeout(null != (t = this.animation) ? t._timeout : void 0); }, i.prototype.render = function (t) { var e, n; return t._png && t._png.stopAnimation(), t._png = this, t.width = this.width, t.height = this.height, e = t.getContext("2d"), this.animation ? (this.decodeFrames(e), this.animate(e)) : (n = e.createImageData(this.width, this.height), this.copyToImageData(n, this.decodePixels()), e.putImageData(n, 0, 0)); }, i; }(); /** * @license * (c) Dean McNamee <dean@gmail.com>, 2013. * * https://github.com/deanm/omggif * * 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. * * omggif is a JavaScript implementation of a GIF 89a encoder and decoder, * including animation and compression. It does not rely on any specific * underlying system, so should run in the browser, Node, or Plask. */ function jt(t) { var e = 0; if (71 !== t[e++] || 73 !== t[e++] || 70 !== t[e++] || 56 !== t[e++] || 56 != (t[e++] + 1 & 253) || 97 !== t[e++]) throw new Error("Invalid GIF 87a/89a header."); var n = t[e++] | t[e++] << 8, r = t[e++] | t[e++] << 8, i = t[e++], a = i >> 7, o = 1 << (7 & i) + 1; t[e++]; t[e++]; var s = null, u = null; a && (s = e, u = o, e += 3 * o); var c = !0, h = [], l = 0, f = null, d = 0, p = null; for (this.width = n, this.height = r; c && e < t.length;) { switch (t[e++]) { case 33: switch (t[e++]) { case 255: if (11 !== t[e] || 78 == t[e + 1] && 69 == t[e + 2] && 84 == t[e + 3] && 83 == t[e + 4] && 67 == t[e + 5] && 65 == t[e + 6] && 80 == t[e + 7] && 69 == t[e + 8] && 50 == t[e + 9] && 46 == t[e + 10] && 48 == t[e + 11] && 3 == t[e + 12] && 1 == t[e + 13] && 0 == t[e + 16]) e += 14, p = t[e++] | t[e++] << 8, e++;else for (e += 12;;) { if (!((P = t[e++]) >= 0)) throw Error("Invalid block size"); if (0 === P) break; e += P; } break; case 249: if (4 !== t[e++] || 0 !== t[e + 4]) throw new Error("Invalid graphics extension block."); var g = t[e++]; l = t[e++] | t[e++] << 8, f = t[e++], 0 == (1 & g) && (f = null), d = g >> 2 & 7, e++; break; case 254: for (;;) { if (!((P = t[e++]) >= 0)) throw Error("Invalid block size"); if (0 === P) break; e += P; } break; default: throw new Error("Unknown graphic control label: 0x" + t[e - 1].toString(16)); } break; case 44: var m = t[e++] | t[e++] << 8, v = t[e++] | t[e++] << 8, b = t[e++] | t[e++] << 8, y = t[e++] | t[e++] << 8, w = t[e++], N = w >> 6 & 1, L = 1 << (7 & w) + 1, x = s, A = u, _ = !1; if (w >> 7) { _ = !0; x = e, A = L, e += 3 * L; } var S = e; for (e++;;) { var P; if (!((P = t[e++]) >= 0)) throw Error("Invalid block size"); if (0 === P) break; e += P; } h.push({ x: m, y: v, width: b, height: y, has_local_palette: _, palette_offset: x, palette_size: A, data_offset: S, data_length: e - S, transparent_index: f, interlaced: !!N, delay: l, disposal: d }); break; case 59: c = !1; break; default: throw new Error("Unknown gif block: 0x" + t[e - 1].toString(16)); } } this.numFrames = function () { return h.length; }, this.loopCount = function () { return p; }, this.frameInfo = function (t) { if (t < 0 || t >= h.length) throw new Error("Frame index out of range."); return h[t]; }, this.decodeAndBlitFrameBGRA = function (e, r) { var i = this.frameInfo(e), a = i.width * i.height, o = new Uint8Array(a); Bt(t, i.data_offset, o, a); var s = i.palette_offset, u = i.transparent_index; null === u && (u = 256); var c = i.width, h = n - c, l = c, f = 4 * (i.y * n + i.x), d = 4 * ((i.y + i.height) * n + i.x), p = f, g = 4 * h; !0 === i.interlaced && (g += 4 * n * 7); for (var m = 8, v = 0, b = o.length; v < b; ++v) { var y = o[v]; if (0 === l && (l = c, (p += g) >= d && (g = 4 * h + 4 * n * (m - 1), p = f + (c + h) * (m << 1), m >>= 1)), y === u) p += 4;else { var w = t[s + 3 * y], N = t[s + 3 * y + 1], L = t[s + 3 * y + 2]; r[p++] = L, r[p++] = N, r[p++] = w, r[p++] = 255; } --l; } }, this.decodeAndBlitFrameRGBA = function (e, r) { var i = this.frameInfo(e), a = i.width * i.height, o = new Uint8Array(a); Bt(t, i.data_offset, o, a); var s = i.palette_offset, u = i.transparent_index; null === u && (u = 256); var c = i.width, h = n - c, l = c, f = 4 * (i.y * n + i.x), d = 4 * ((i.y + i.height) * n + i.x), p = f, g = 4 * h; !0 === i.interlaced && (g += 4 * n * 7); for (var m = 8, v = 0, b = o.length; v < b; ++v) { var y = o[v]; if (0 === l && (l = c, (p += g) >= d && (g = 4 * h + 4 * n * (m - 1), p = f + (c + h) * (m << 1), m >>= 1)), y === u) p += 4;else { var w = t[s + 3 * y], N = t[s + 3 * y + 1], L = t[s + 3 * y + 2]; r[p++] = w, r[p++] = N, r[p++] = L, r[p++] = 255; } --l; } }; } function Bt(t, e, r, i) { for (var a = t[e++], o = 1 << a, s = o + 1, u = s + 1, c = a + 1, h = (1 << c) - 1, l = 0, f = 0, d = 0, p = t[e++], g = new Int32Array(4096), m = null;;) { for (; l < 16 && 0 !== p;) { f |= t[e++] << l, l += 8, 1 === p ? p = t[e++] : --p; } if (l < c) break; var v = f & h; if (f >>= c, l -= c, v !== o) { if (v === s) break; for (var b = v < u ? v : m, y = 0, w = b; w > o;) { w = g[w] >> 8, ++y; } var N = w; if (d + y + (b !== v ? 1 : 0) > i) return void n.log("Warning, gif stream longer than expected."); r[d++] = N; var L = d += y; for (b !== v && (r[d++] = N), w = b; y--;) { w = g[w], r[--L] = 255 & w, w >>= 8; } null !== m && u < 4096 && (g[u++] = m << 8 | N, u >= h + 1 && c < 12 && (++c, h = h << 1 | 1)), m = v; } else u = s + 1, h = (1 << (c = a + 1)) - 1, m = null; } return d !== i && n.log("Warning, gif stream shorter than expected."), r; } /** * @license Copyright (c) 2008, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function Ot(t) { var e, n, r, i, a, o = Math.floor, s = new Array(64), u = new Array(64), c = new Array(64), h = new Array(64), l = new Array(65535), f = new Array(65535), d = new Array(64), p = new Array(64), g = [], m = 0, v = 7, b = new Array(64), y = new Array(64), w = new Array(64), N = new Array(256), L = new Array(2048), x = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63], A = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], _ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], S = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125], P = [1, 2, 3, 0, 4, 17, 5, 18, 33, 49, 65, 6, 19, 81, 97, 7, 34, 113, 20, 50, 129, 145, 161, 8, 35, 66, 177, 193, 21, 82, 209, 240, 36, 51, 98, 114, 130, 9, 10, 22, 23, 24, 25, 26, 37, 38, 39, 40, 41, 42, 52, 53, 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, 131, 132, 133, 134, 135, 136, 137, 138, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163, 164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181, 182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199, 200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217, 218, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250], k = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], F = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], I = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119], C = [0, 1, 2, 3, 17, 4, 5, 33, 49, 6, 18, 65, 81, 7, 97, 113, 19, 34, 50, 129, 8, 20, 66, 145, 161, 177, 193, 9, 35, 51, 82, 240, 21, 98, 114, 209, 10, 22, 36, 52, 225, 37, 241, 23, 24, 25, 26, 38, 39, 40, 41, 42, 53, 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, 130, 131, 132, 133, 134, 135, 136, 137, 138, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163, 164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181, 182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199, 200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217, 218, 226, 227, 228, 229, 230, 231, 232, 233, 234, 242, 243, 244, 245, 246, 247, 248, 249, 250]; function j(t, e) { for (var n = 0, r = 0, i = new Array(), a = 1; a <= 16; a++) { for (var o = 1; o <= t[a]; o++) { i[e[r]] = [], i[e[r]][0] = n, i[e[r]][1] = a, r++, n++; } n *= 2; } return i; } function B(t) { for (var e = t[0], n = t[1] - 1; n >= 0;) { e & 1 << n && (m |= 1 << v), n--, --v < 0 && (255 == m ? (O(255), O(0)) : O(m), v = 7, m = 0); } } function O(t) { g.push(t); } function M(t) { O(t >> 8 & 255), O(255 & t); } function E(t, e, n, r, i) { for (var a, o = i[0], s = i[240], u = function (t, e) { var n, r, i, a, o, s, u, c, h, l, f = 0; for (h = 0; h < 8; ++h) { n = t[f], r = t[f + 1], i = t[f + 2], a = t[f + 3], o = t[f + 4], s = t[f + 5], u = t[f + 6]; var p = n + (c = t[f + 7]), g = n - c, m = r + u, v = r - u, b = i + s, y = i - s, w = a + o, N = a - o, L = p + w, x = p - w, A = m + b, _ = m - b; t[f] = L + A, t[f + 4] = L - A; var S = .707106781 * (_ + x); t[f + 2] = x + S, t[f + 6] = x - S; var P = .382683433 * ((L = N + y) - (_ = v + g)), k = .5411961 * L + P, F = 1.306562965 * _ + P, I = .707106781 * (A = y + v), C = g + I, j = g - I; t[f + 5] = j + k, t[f + 3] = j - k, t[f + 1] = C + F, t[f + 7] = C - F, f += 8; } for (f = 0, h = 0; h < 8; ++h) { n = t[f], r = t[f + 8], i = t[f + 16], a = t[f + 24], o = t[f + 32], s = t[f + 40], u = t[f + 48]; var B = n + (c = t[f + 56]), O = n - c, M = r + u, E = r - u, q = i + s, R = i - s, T = a + o, D = a - o, U = B + T, z = B - T, H = M + q, W = M - q; t[f] = U + H, t[f + 32] = U - H; var V = .707106781 * (W + z); t[f + 16] = z + V, t[f + 48] = z - V; var G = .382683433 * ((U = D + R) - (W = E + O)), Y = .5411961 * U + G, J = 1.306562965 * W + G, X = .707106781 * (H = R + E), K = O + X, Z = O - X; t[f + 40] = Z + Y, t[f + 24] = Z - Y, t[f + 8] = K + J, t[f + 56] = K - J, f++; } for (h = 0; h < 64; ++h) { l = t[h] * e[h], d[h] = l > 0 ? l + .5 | 0 : l - .5 | 0; } return d; }(t, e), c = 0; c < 64; ++c) { p[x[c]] = u[c]; } var h = p[0] - n; n = p[0], 0 == h ? B(r[0]) : (B(r[f[a = 32767 + h]]), B(l[a])); for (var g = 63; g > 0 && 0 == p[g];) { g--; } if (0 == g) return B(o), n; for (var m, v = 1; v <= g;) { for (var b = v; 0 == p[v] && v <= g;) { ++v; } var y = v - b; if (y >= 16) { m = y >> 4; for (var w = 1; w <= m; ++w) { B(s); } y &= 15; } a = 32767 + p[v], B(i[(y << 4) + f[a]]), B(l[a]), v++; } return 63 != g && B(o), n; } function q(t) { (t = Math.min(Math.max(t, 1), 100), a != t) && (!function (t) { for (var e = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99], n = 0; n < 64; n++) { var r = o((e[n] * t + 50) / 100); r = Math.min(Math.max(r, 1), 255), s[x[n]] = r; } for (var i = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99], a = 0; a < 64; a++) { var l = o((i[a] * t + 50) / 100); l = Math.min(Math.max(l, 1), 255), u[x[a]] = l; } for (var f = [1, 1.387039845, 1.306562965, 1.175875602, 1, .785694958, .5411961, .275899379], d = 0, p = 0; p < 8; p++) { for (var g = 0; g < 8; g++) { c[d] = 1 / (s[x[d]] * f[p] * f[g] * 8), h[d] = 1 / (u[x[d]] * f[p] * f[g] * 8), d++; } } }(t < 50 ? Math.floor(5e3 / t) : Math.floor(200 - 2 * t)), a = t); } this.encode = function (t, a) { a && q(a), g = new Array(), m = 0, v = 7, M(65496), M(65504), M(16), O(74), O(70), O(73), O(70), O(0), O(1), O(1), O(0), M(1), M(1), O(0), O(0), function () { M(65499), M(132), O(0); for (var t = 0; t < 64; t++) { O(s[t]); } O(1); for (var e = 0; e < 64; e++) { O(u[e]); } }(), function (t, e) { M(65472), M(17), O(8), M(e), M(t), O(3), O(1), O(17), O(0), O(2), O(17), O(1), O(3), O(17), O(1); }(t.width, t.height), function () { M(65476), M(418), O(0); for (var t = 0; t < 16; t++) { O(A[t + 1]); } for (var e = 0; e <= 11; e++) { O(_[e]); } O(16); for (var n = 0; n < 16; n++) { O(S[n + 1]); } for (var r = 0; r <= 161; r++) { O(P[r]); } O(1); for (var i = 0; i < 16; i++) { O(k[i + 1]); } for (var a = 0; a <= 11; a++) { O(F[a]); } O(17); for (var o = 0; o < 16; o++) { O(I[o + 1]); } for (var s = 0; s <= 161; s++) { O(C[s]); } }(), M(65498), M(12), O(3), O(1), O(0), O(2), O(17), O(3), O(17), O(0), O(63), O(0); var o = 0, l = 0, f = 0; m = 0, v = 7, this.encode.displayName = "_encode_"; for (var d, p, N, x, j, R, T, D, U, z = t.data, H = t.width, W = t.height, V = 4 * H, G = 0; G < W;) { for (d = 0; d < V;) { for (j = V * G + d, T = -1, D = 0, U = 0; U < 64; U++) { R = j + (D = U >> 3) * V + (T = 4 * (7 & U)), G + D >= W && (R -= V * (G + 1 + D - W)), d + T >= V && (R -= d + T - V + 4), p = z[R++], N = z[R++], x = z[R++], b[U] = (L[p] + L[N + 256 >> 0] + L[x + 512 >> 0] >> 16) - 128, y[U] = (L[p + 768 >> 0] + L[N + 1024 >> 0] + L[x + 1280 >> 0] >> 16) - 128, w[U] = (L[p + 1280 >> 0] + L[N + 1536 >> 0] + L[x + 1792 >> 0] >> 16) - 128; } o = E(b, c, o, e, r), l = E(y, h, l, n, i), f = E(w, h, f, n, i), d += 32; } G += 8; } if (v >= 0) { var Y = []; Y[1] = v + 1, Y[0] = (1 << v + 1) - 1, B(Y); } return M(65497), new Uint8Array(g); }, t = t || 50, function () { for (var t = String.fromCharCode, e = 0; e < 256; e++) { N[e] = t(e); } }(), e = j(A, _), n = j(k, F), r = j(S, P), i = j(I, C), function () { for (var t = 1, e = 2, n = 1; n <= 15; n++) { for (var r = t; r < e; r++) { f[32767 + r] = n, l[32767 + r] = [], l[32767 + r][1] = n, l[32767 + r][0] = r; } for (var i = -(e - 1); i <= -t; i++) { f[32767 + i] = n, l[32767 + i] = [], l[32767 + i][1] = n, l[32767 + i][0] = e - 1 + i; } t <<= 1, e <<= 1; } }(), function () { for (var t = 0; t < 256; t++) { L[t] = 19595 * t, L[t + 256 >> 0] = 38470 * t, L[t + 512 >> 0] = 7471 * t + 32768, L[t + 768 >> 0] = -11059 * t, L[t + 1024 >> 0] = -21709 * t, L[t + 1280 >> 0] = 32768 * t + 8421375, L[t + 1536 >> 0] = -27439 * t, L[t + 1792 >> 0] = -5329 * t; } }(), q(t); } /** * @license * Copyright (c) 2017 Aras Abbasi * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function Mt(t, e) { if (this.pos = 0, this.buffer = t, this.datav = new DataView(t.buffer), this.is_with_alpha = !!e, this.bottom_up = !0, this.flag = String.fromCharCode(this.buffer[0]) + String.fromCharCode(this.buffer[1]), this.pos += 2, -1 === ["BM", "BA", "CI", "CP", "IC", "PT"].indexOf(this.flag)) throw new Error("Invalid BMP File"); this.parseHeader(), this.parseBGR(); } function Et(t) { function e(t) { if (!t) throw Error("assert :P"); } function n(t, e, n) { for (var r = 0; 4 > r; r++) { if (t[e + r] != n.charCodeAt(r)) return !0; } return !1; } function r(t, e, n, r, i) { for (var a = 0; a < i; a++) { t[e + a] = n[r + a]; } } function i(t, e, n, r) { for (var i = 0; i < r; i++) { t[e + i] = n; } } function a(t) { return new Int32Array(t); } function o(t, e) { for (var n = [], r = 0; r < t; r++) { n.push(new e()); } return n; } function s(t, e) { var n = []; return function t(n, r, i) { for (var a = i[r], o = 0; o < a && (n.push(i.length > r + 1 ? [] : new e()), !(i.length < r + 1)); o++) { t(n[o], r + 1, i); } }(n, 0, t), n; } function u(t, e) { for (var n = "", r = 0; r < 4; r++) { n += String.fromCharCode(t[e++]); } return n; } function c(t, e) { return (t[e + 0] << 0 | t[e + 1] << 8 | t[e + 2] << 16) >>> 0; } function h(t, e) { return (t[e + 0] << 0 | t[e + 1] << 8 | t[e + 2] << 16 | t[e + 3] << 24) >>> 0; } new (Et = function Et() { var t = this; function u(t, e) { for (var n = 1 << e - 1 >>> 0; t & n;) { n >>>= 1; } return n ? (t & n - 1) + n : t; } function c(t, n, r, i, a) { e(!(i % r)); do { t[n + (i -= r)] = a; } while (0 < i); } function h(t, n, r, i, o) { if (e(2328 >= o), 512 >= o) var s = a(512);else if (null == (s = a(o))) return 0; return function (t, n, r, i, o, s) { var h, f, d = n, p = 1 << r, g = a(16), m = a(16); for (e(0 != o), e(null != i), e(null != t), e(0 < r), f = 0; f < o; ++f) { if (15 < i[f]) return 0; ++g[i[f]]; } if (g[0] == o) return 0; for (m[1] = 0, h = 1; 15 > h; ++h) { if (g[h] > 1 << h) return 0; m[h + 1] = m[h] + g[h]; } for (f = 0; f < o; ++f) { h = i[f], 0 < i[f] && (s[m[h]++] = f); } if (1 == m[15]) return (i = new l()).g = 0, i.value = s[0], c(t, d, 1, p, i), p; var v, b = -1, y = p - 1, w = 0, N = 1, L = 1, x = 1 << r; for (f = 0, h = 1, o = 2; h <= r; ++h, o <<= 1) { if (N += L <<= 1, 0 > (L -= g[h])) return 0; for (; 0 < g[h]; --g[h]) { (i = new l()).g = h, i.value = s[f++], c(t, d + w, o, x, i), w = u(w, h); } } for (h = r + 1, o = 2; 15 >= h; ++h, o <<= 1) { if (N += L <<= 1, 0 > (L -= g[h])) return 0; for (; 0 < g[h]; --g[h]) { if (i = new l(), (w & y) != b) { for (d += x, v = 1 << (b = h) - r; 15 > b && !(0 >= (v -= g[b]));) { ++b, v <<= 1; } p += x = 1 << (v = b - r), t[n + (b = w & y)].g = v + r, t[n + b].value = d - n - b; } i.g = h - r, i.value = s[f++], c(t, d + (w >> r), o, x, i), w = u(w, h); } } return N != 2 * m[15] - 1 ? 0 : p; }(t, n, r, i, o, s); } function l() { this.value = this.g = 0; } function f() { this.value = this.g = 0; } function d() { this.G = o(5, l), this.H = a(5), this.jc = this.Qb = this.qb = this.nd = 0, this.pd = o(Tn, f); } function p(t, n, r, i) { e(null != t), e(null != n), e(2147483648 > i), t.Ca = 254, t.I = 0, t.b = -8, t.Ka = 0, t.oa = n, t.pa = r, t.Jd = n, t.Yc = r + i, t.Zc = 4 <= i ? r + i - 4 + 1 : r, S(t); } function g(t, e) { for (var n = 0; 0 < e--;) { n |= k(t, 128) << e; } return n; } function m(t, e) { var n = g(t, e); return P(t) ? -n : n; } function v(t, n, r, i) { var a, o = 0; for (e(null != t), e(null != n), e(4294967288 > i), t.Sb = i, t.Ra = 0, t.u = 0, t.h = 0, 4 < i && (i = 4), a = 0; a < i; ++a) { o += n[r + a] << 8 * a; } t.Ra = o, t.bb = i, t.oa = n, t.pa = r; } function b(t) { for (; 8 <= t.u && t.bb < t.Sb;) { t.Ra >>>= 8, t.Ra += t.oa[t.pa + t.bb] << zn - 8 >>> 0, ++t.bb, t.u -= 8; } x(t) && (t.h = 1, t.u = 0); } function y(t, n) { if (e(0 <= n), !t.h && n <= Un) { var r = L(t) & Dn[n]; return t.u += n, b(t), r; } return t.h = 1, t.u = 0; } function w() { this.b = this.Ca = this.I = 0, this.oa = [], this.pa = 0, this.Jd = [], this.Yc = 0, this.Zc = [], this.Ka = 0; } function N() { this.Ra = 0, this.oa = [], this.h = this.u = this.bb = this.Sb = this.pa = 0; } function L(t) { return t.Ra >>> (t.u & zn - 1) >>> 0; } function x(t) { return e(t.bb <= t.Sb), t.h || t.bb == t.Sb && t.u > zn; } function A(t, e) { t.u = e, t.h = x(t); } function _(t) { t.u >= Hn && (e(t.u >= Hn), b(t)); } function S(t) { e(null != t && null != t.oa), t.pa < t.Zc ? (t.I = (t.oa[t.pa++] | t.I << 8) >>> 0, t.b += 8) : (e(null != t && null != t.oa), t.pa < t.Yc ? (t.b += 8, t.I = t.oa[t.pa++] | t.I << 8) : t.Ka ? t.b = 0 : (t.I <<= 8, t.b += 8, t.Ka = 1)); } function P(t) { return g(t, 1); } function k(t, e) { var n = t.Ca; 0 > t.b && S(t); var r = t.b, i = n * e >>> 8, a = (t.I >>> r > i) + 0; for (a ? (n -= i, t.I -= i + 1 << r >>> 0) : n = i + 1, r = n, i = 0; 256 <= r;) { i += 8, r >>= 8; } return r = 7 ^ i + Wn[r], t.b -= r, t.Ca = (n << r) - 1, a; } function F(t, e, n) { t[e + 0] = n >> 24 & 255, t[e + 1] = n >> 16 & 255, t[e + 2] = n >> 8 & 255, t[e + 3] = n >> 0 & 255; } function I(t, e) { return t[e + 0] << 0 | t[e + 1] << 8; } function C(t, e) { return I(t, e) | t[e + 2] << 16; } function j(t, e) { return I(t, e) | I(t, e + 2) << 16; } function B(t, n) { var r = 1 << n; return e(null != t), e(0 < n), t.X = a(r), null == t.X ? 0 : (t.Mb = 32 - n, t.Xa = n, 1); } function O(t, n) { e(null != t), e(null != n), e(t.Xa == n.Xa), r(n.X, 0, t.X, 0, 1 << n.Xa); } function M() { this.X = [], this.Xa = this.Mb = 0; } function E(t, n, r, i) { e(null != r), e(null != i); var a = r[0], o = i[0]; return 0 == a && (a = (t * o + n / 2) / n), 0 == o && (o = (n * a + t / 2) / t), 0 >= a || 0 >= o ? 0 : (r[0] = a, i[0] = o, 1); } function q(t, e) { return t + (1 << e) - 1 >>> e; } function R(t, e) { return ((4278255360 & t) + (4278255360 & e) >>> 0 & 4278255360) + ((16711935 & t) + (16711935 & e) >>> 0 & 16711935) >>> 0; } function T(e, n) { t[n] = function (n, r, i, a, o, s, u) { var c; for (c = 0; c < o; ++c) { var h = t[e](s[u + c - 1], i, a + c); s[u + c] = R(n[r + c], h); } }; } function D() { this.ud = this.hd = this.jd = 0; } function U(t, e) { return ((4278124286 & (t ^ e)) >>> 1) + (t & e) >>> 0; } function z(t) { return 0 <= t && 256 > t ? t : 0 > t ? 0 : 255 < t ? 255 : void 0; } function H(t, e) { return z(t + (t - e + .5 >> 1)); } function W(t, e, n) { return Math.abs(e - n) - Math.abs(t - n); } function V(t, e, n, r, i, a, o) { for (r = a[o - 1], n = 0; n < i; ++n) { a[o + n] = r = R(t[e + n], r); } } function G(t, e, n, r, i) { var a; for (a = 0; a < n; ++a) { var o = t[e + a], s = o >> 8 & 255, u = 16711935 & (u = (u = 16711935 & o) + ((s << 16) + s)); r[i + a] = (4278255360 & o) + u >>> 0; } } function Y(t, e) { e.jd = t >> 0 & 255, e.hd = t >> 8 & 255, e.ud = t >> 16 & 255; } function J(t, e, n, r, i, a) { var o; for (o = 0; o < r; ++o) { var s = e[n + o], u = s >>> 8, c = s, h = 255 & (h = (h = s >>> 16) + ((t.jd << 24 >> 24) * (u << 24 >> 24) >>> 5)); c = 255 & (c = (c = c + ((t.hd << 24 >> 24) * (u << 24 >> 24) >>> 5)) + ((t.ud << 24 >> 24) * (h << 24 >> 24) >>> 5)); i[a + o] = (4278255360 & s) + (h << 16) + c; } } function X(e, n, r, i, a) { t[n] = function (t, e, n, r, o, s, u, c, h) { for (r = u; r < c; ++r) { for (u = 0; u < h; ++u) { o[s++] = a(n[i(t[e++])]); } } }, t[e] = function (e, n, o, s, u, c, h) { var l = 8 >> e.b, f = e.Ea, d = e.K[0], p = e.w; if (8 > l) for (e = (1 << e.b) - 1, p = (1 << l) - 1; n < o; ++n) { var g, m = 0; for (g = 0; g < f; ++g) { g & e || (m = i(s[u++])), c[h++] = a(d[m & p]), m >>= l; } } else t["VP8LMapColor" + r](s, u, d, p, c, h, n, o, f); }; } function K(t, e, n, r, i) { for (n = e + n; e < n;) { var a = t[e++]; r[i++] = a >> 16 & 255, r[i++] = a >> 8 & 255, r[i++] = a >> 0 & 255; } } function Z(t, e, n, r, i) { for (n = e + n; e < n;) { var a = t[e++]; r[i++] = a >> 16 & 255, r[i++] = a >> 8 & 255, r[i++] = a >> 0 & 255, r[i++] = a >> 24 & 255; } } function $(t, e, n, r, i) { for (n = e + n; e < n;) { var a = (o = t[e++]) >> 16 & 240 | o >> 12 & 15, o = o >> 0 & 240 | o >> 28 & 15; r[i++] = a, r[i++] = o; } } function Q(t, e, n, r, i) { for (n = e + n; e < n;) { var a = (o = t[e++]) >> 16 & 248 | o >> 13 & 7, o = o >> 5 & 224 | o >> 3 & 31; r[i++] = a, r[i++] = o; } } function tt(t, e, n, r, i) { for (n = e + n; e < n;) { var a = t[e++]; r[i++] = a >> 0 & 255, r[i++] = a >> 8 & 255, r[i++] = a >> 16 & 255; } } function et(t, e, n, i, a, o) { if (0 == o) for (n = e + n; e < n;) { F(i, ((o = t[e++])[0] >> 24 | o[1] >> 8 & 65280 | o[2] << 8 & 16711680 | o[3] << 24) >>> 0), a += 32; } else r(i, a, t, e, n); } function nt(e, n) { t[n][0] = t[e + "0"], t[n][1] = t[e + "1"], t[n][2] = t[e + "2"], t[n][3] = t[e + "3"], t[n][4] = t[e + "4"], t[n][5] = t[e + "5"], t[n][6] = t[e + "6"], t[n][7] = t[e + "7"], t[n][8] = t[e + "8"], t[n][9] = t[e + "9"], t[n][10] = t[e + "10"], t[n][11] = t[e + "11"], t[n][12] = t[e + "12"], t[n][13] = t[e + "13"], t[n][14] = t[e + "0"], t[n][15] = t[e + "0"]; } function rt(t) { return t == Hr || t == Wr || t == Vr || t == Gr; } function it() { this.eb = [], this.size = this.A = this.fb = 0; } function at() { this.y = [], this.f = [], this.ea = [], this.F = [], this.Tc = this.Ed = this.Cd = this.Fd = this.lb = this.Db = this.Ab = this.fa = this.J = this.W = this.N = this.O = 0; } function ot() { this.Rd = this.height = this.width = this.S = 0, this.f = {}, this.f.RGBA = new it(), this.f.kb = new at(), this.sd = null; } function st() { this.width = [0], this.height = [0], this.Pd = [0], this.Qd = [0], this.format = [0]; } function ut() { this.Id = this.fd = this.Md = this.hb = this.ib = this.da = this.bd = this.cd = this.j = this.v = this.Da = this.Sd = this.ob = 0; } function ct(t) { return alert("todo:WebPSamplerProcessPlane"), t.T; } function ht(t, e) { var n = t.T, i = e.ba.f.RGBA, a = i.eb, o = i.fb + t.ka * i.A, s = vi[e.ba.S], u = t.y, c = t.O, h = t.f, l = t.N, f = t.ea, d = t.W, p = e.cc, g = e.dc, m = e.Mc, v = e.Nc, b = t.ka, y = t.ka + t.T, w = t.U, N = w + 1 >> 1; for (0 == b ? s(u, c, null, null, h, l, f, d, h, l, f, d, a, o, null, null, w) : (s(e.ec, e.fc, u, c, p, g, m, v, h, l, f, d, a, o - i.A, a, o, w), ++n); b + 2 < y; b += 2) { p = h, g = l, m = f, v = d, l += t.Rc, d += t.Rc, o += 2 * i.A, s(u, (c += 2 * t.fa) - t.fa, u, c, p, g, m, v, h, l, f, d, a, o - i.A, a, o, w); } return c += t.fa, t.j + y < t.o ? (r(e.ec, e.fc, u, c, w), r(e.cc, e.dc, h, l, N), r(e.Mc, e.Nc, f, d, N), n--) : 1 & y || s(u, c, null, null, h, l, f, d, h, l, f, d, a, o + i.A, null, null, w), n; } function lt(t, n, r) { var i = t.F, a = [t.J]; if (null != i) { var o = t.U, s = n.ba.S, u = s == Dr || s == Vr; n = n.ba.f.RGBA; var c = [0], h = t.ka; c[0] = t.T, t.Kb && (0 == h ? --c[0] : (--h, a[0] -= t.width), t.j + t.ka + t.T == t.o && (c[0] = t.o - t.j - h)); var l = n.eb; h = n.fb + h * n.A; t = _r(i, a[0], t.width, o, c, l, h + (u ? 0 : 3), n.A), e(r == c), t && rt(s) && xr(l, h, u, o, c, n.A); } return 0; } function ft(t) { var e = t.ma, n = e.ba.S, r = 11 > n, i = n == qr || n == Tr || n == Dr || n == Ur || 12 == n || rt(n); if (e.memory = null, e.Ib = null, e.Jb = null, e.Nd = null, !En(e.Oa, t, i ? 11 : 12)) return 0; if (i && rt(n) && yn(), t.da) alert("todo:use_scaling");else { if (r) { if (e.Ib = ct, t.Kb) { if (n = t.U + 1 >> 1, e.memory = a(t.U + 2 * n), null == e.memory) return 0; e.ec = e.memory, e.fc = 0, e.cc = e.ec, e.dc = e.fc + t.U, e.Mc = e.cc, e.Nc = e.dc + n, e.Ib = ht, yn(); } } else alert("todo:EmitYUV"); i && (e.Jb = lt, r && vn()); } if (r && !Ci) { for (t = 0; 256 > t; ++t) { ji[t] = 89858 * (t - 128) + Si >> _i, Mi[t] = -22014 * (t - 128) + Si, Oi[t] = -45773 * (t - 128), Bi[t] = 113618 * (t - 128) + Si >> _i; } for (t = Pi; t < ki; ++t) { e = 76283 * (t - 16) + Si >> _i, Ei[t - Pi] = Vt(e, 255), qi[t - Pi] = Vt(e + 8 >> 4, 15); } Ci = 1; } return 1; } function dt(t) { var n = t.ma, r = t.U, i = t.T; return e(!(1 & t.ka)), 0 >= r || 0 >= i ? 0 : (r = n.Ib(t, n), null != n.Jb && n.Jb(t, n, r), n.Dc += r, 1); } function pt(t) { t.ma.memory = null; } function gt(t, e, n, r) { return 47 != y(t, 8) ? 0 : (e[0] = y(t, 14) + 1, n[0] = y(t, 14) + 1, r[0] = y(t, 1), 0 != y(t, 3) ? 0 : !t.h); } function mt(t, e) { if (4 > t) return t + 1; var n = t - 2 >> 1; return (2 + (1 & t) << n) + y(e, n) + 1; } function vt(t, e) { return 120 < e ? e - 120 : 1 <= (n = ((n = $r[e - 1]) >> 4) * t + (8 - (15 & n))) ? n : 1; var n; } function bt(t, e, n) { var r = L(n), i = t[e += 255 & r].g - 8; return 0 < i && (A(n, n.u + 8), r = L(n), e += t[e].value, e += r & (1 << i) - 1), A(n, n.u + t[e].g), t[e].value; } function yt(t, n, r) { return r.g += t.g, r.value += t.value << n >>> 0, e(8 >= r.g), t.g; } function wt(t, n, r) { var i = t.xc; return e((n = 0 == i ? 0 : t.vc[t.md * (r >> i) + (n >> i)]) < t.Wb), t.Ya[n]; } function Nt(t, n, i, a) { var o = t.ab, s = t.c * n, u = t.C; n = u + n; var c = i, h = a; for (a = t.Ta, i = t.Ua; 0 < o--;) { var l = t.gc[o], f = u, d = n, p = c, g = h, m = (h = a, c = i, l.Ea); switch (e(f < d), e(d <= l.nc), l.hc) { case 2: Yn(p, g, (d - f) * m, h, c); break; case 0: var v = f, b = d, y = h, w = c, N = (S = l).Ea; 0 == v && (Vn(p, g, null, null, 1, y, w), V(p, g + 1, 0, 0, N - 1, y, w + 1), g += N, w += N, ++v); for (var L = 1 << S.b, x = L - 1, A = q(N, S.b), _ = S.K, S = S.w + (v >> S.b) * A; v < b;) { var P = _, k = S, F = 1; for (Gn(p, g, y, w - N, 1, y, w); F < N;) { var I = (F & ~x) + L; I > N && (I = N), (0, $n[P[k++] >> 8 & 15])(p, g + +F, y, w + F - N, I - F, y, w + F), F = I; } g += N, w += N, ++v & x || (S += A); } d != l.nc && r(h, c - m, h, c + (d - f - 1) * m, m); break; case 1: for (m = p, b = g, N = (p = l.Ea) - (w = p & ~(y = (g = 1 << l.b) - 1)), v = q(p, l.b), L = l.K, l = l.w + (f >> l.b) * v; f < d;) { for (x = L, A = l, _ = new D(), S = b + w, P = b + p; b < S;) { Y(x[A++], _), Qn(_, m, b, g, h, c), b += g, c += g; } b < P && (Y(x[A++], _), Qn(_, m, b, N, h, c), b += N, c += N), ++f & y || (l += v); } break; case 3: if (p == h && g == c && 0 < l.b) { for (b = h, p = m = c + (d - f) * m - (w = (d - f) * q(l.Ea, l.b)), g = h, y = c, v = [], w = (N = w) - 1; 0 <= w; --w) { v[w] = g[y + w]; } for (w = N - 1; 0 <= w; --w) { b[p + w] = v[w]; } Jn(l, f, d, h, m, h, c); } else Jn(l, f, d, p, g, h, c); } c = a, h = i; } h != i && r(a, i, c, h, s); } function Lt(t, n) { var r = t.V, i = t.Ba + t.c * t.C, a = n - t.C; if (e(n <= t.l.o), e(16 >= a), 0 < a) { var o = t.l, s = t.Ta, u = t.Ua, c = o.width; if (Nt(t, a, r, i), a = u = [u], e((r = t.C) < (i = n)), e(o.v < o.va), i > o.o && (i = o.o), r < o.j) { var h = o.j - r; r = o.j; a[0] += h * c; } if (r >= i ? r = 0 : (a[0] += 4 * o.v, o.ka = r - o.j, o.U = o.va - o.v, o.T = i - r, r = 1), r) { if (u = u[0], 11 > (r = t.ca).S) { var l = r.f.RGBA, f = (i = r.S, a = o.U, o = o.T, h = l.eb, l.A), d = o; for (l = l.fb + t.Ma * l.A; 0 < d--;) { var p = s, g = u, m = a, v = h, b = l; switch (i) { case Er: tr(p, g, m, v, b); break; case qr: er(p, g, m, v, b); break; case Hr: er(p, g, m, v, b), xr(v, b, 0, m, 1, 0); break; case Rr: ir(p, g, m, v, b); break; case Tr: et(p, g, m, v, b, 1); break; case Wr: et(p, g, m, v, b, 1), xr(v, b, 0, m, 1, 0); break; case Dr: et(p, g, m, v, b, 0); break; case Vr: et(p, g, m, v, b, 0), xr(v, b, 1, m, 1, 0); break; case Ur: nr(p, g, m, v, b); break; case Gr: nr(p, g, m, v, b), Ar(v, b, m, 1, 0); break; case zr: rr(p, g, m, v, b); break; default: e(0); } u += c, l += f; } t.Ma += o; } else alert("todo:EmitRescaledRowsYUVA"); e(t.Ma <= r.height); } } t.C = n, e(t.C <= t.i); } function xt(t) { var e; if (0 < t.ua) return 0; for (e = 0; e < t.Wb; ++e) { var n = t.Ya[e].G, r = t.Ya[e].H; if (0 < n[1][r[1] + 0].g || 0 < n[2][r[2] + 0].g || 0 < n[3][r[3] + 0].g) return 0; } return 1; } function At(t, n, r, i, a, o) { if (0 != t.Z) { var s = t.qd, u = t.rd; for (e(null != mi[t.Z]); n < r; ++n) { mi[t.Z](s, u, i, a, i, a, o), s = i, u = a, a += o; } t.qd = s, t.rd = u; } } function _t(t, n) { var r = t.l.ma, i = 0 == r.Z || 1 == r.Z ? t.l.j : t.C; i = t.C < i ? i : t.C; if (e(n <= t.l.o), n > i) { var a = t.l.width, o = r.ca, s = r.tb + a * i, u = t.V, c = t.Ba + t.c * i, h = t.gc; e(1 == t.ab), e(3 == h[0].hc), Kn(h[0], i, n, u, c, o, s), At(r, i, n, o, s, a); } t.C = t.Ma = n; } function St(t, n, r, i, a, o, s) { var u = t.$ / i, c = t.$ % i, h = t.m, l = t.s, f = r + t.$, d = f; a = r + i * a; var p = r + i * o, g = 280 + l.ua, m = t.Pb ? u : 16777216, v = 0 < l.ua ? l.Wa : null, b = l.wc, y = f < p ? wt(l, c, u) : null; e(t.C < o), e(p <= a); var w = !1; t: for (;;) { for (; w || f < p;) { var N = 0; if (u >= m) { var S = f - r; e((m = t).Pb), m.wd = m.m, m.xd = S, 0 < m.s.ua && O(m.s.Wa, m.s.vb), m = u + ti; } if (c & b || (y = wt(l, c, u)), e(null != y), y.Qb && (n[f] = y.qb, w = !0), !w) if (_(h), y.jc) { N = h, S = n; var P = f, k = y.pd[L(N) & Tn - 1]; e(y.jc), 256 > k.g ? (A(N, N.u + k.g), S[P] = k.value, N = 0) : (A(N, N.u + k.g - 256), e(256 <= k.value), N = k.value), 0 == N && (w = !0); } else N = bt(y.G[0], y.H[0], h); if (h.h) break; if (w || 256 > N) { if (!w) if (y.nd) n[f] = (y.qb | N << 8) >>> 0;else { if (_(h), w = bt(y.G[1], y.H[1], h), _(h), S = bt(y.G[2], y.H[2], h), P = bt(y.G[3], y.H[3], h), h.h) break; n[f] = (P << 24 | w << 16 | N << 8 | S) >>> 0; } if (w = !1, ++f, ++c >= i && (c = 0, ++u, null != s && u <= o && !(u % 16) && s(t, u), null != v)) for (; d < f;) { N = n[d++], v.X[(506832829 * N & 4294967295) >>> v.Mb] = N; } } else if (280 > N) { if (N = mt(N - 256, h), S = bt(y.G[4], y.H[4], h), _(h), S = vt(i, S = mt(S, h)), h.h) break; if (f - r < S || a - f < N) break t; for (P = 0; P < N; ++P) { n[f + P] = n[f + P - S]; } for (f += N, c += N; c >= i;) { c -= i, ++u, null != s && u <= o && !(u % 16) && s(t, u); } if (e(f <= a), c & b && (y = wt(l, c, u)), null != v) for (; d < f;) { N = n[d++], v.X[(506832829 * N & 4294967295) >>> v.Mb] = N; } } else { if (!(N < g)) break t; for (w = N - 280, e(null != v); d < f;) { N = n[d++], v.X[(506832829 * N & 4294967295) >>> v.Mb] = N; } N = f, e(!(w >>> (S = v).Xa)), n[N] = S.X[w], w = !0; } w || e(h.h == x(h)); } if (t.Pb && h.h && f < a) e(t.m.h), t.a = 5, t.m = t.wd, t.$ = t.xd, 0 < t.s.ua && O(t.s.vb, t.s.Wa);else { if (h.h) break t; null != s && s(t, u > o ? o : u), t.a = 0, t.$ = f - r; } return 1; } return t.a = 3, 0; } function Pt(t) { e(null != t), t.vc = null, t.yc = null, t.Ya = null; var n = t.Wa; null != n && (n.X = null), t.vb = null, e(null != t); } function kt() { var e = new sn(); return null == e ? null : (e.a = 0, e.xb = gi, nt("Predictor", "VP8LPredictors"), nt("Predictor", "VP8LPredictors_C"), nt("PredictorAdd", "VP8LPredictorsAdd"), nt("PredictorAdd", "VP8LPredictorsAdd_C"), Yn = G, Qn = J, tr = K, er = Z, nr = $, rr = Q, ir = tt, t.VP8LMapColor32b = Xn, t.VP8LMapColor8b = Zn, e); } function Ft(t, n, r, s, u) { var c = 1, f = [t], p = [n], g = s.m, m = s.s, v = null, b = 0; t: for (;;) { if (r) for (; c && y(g, 1);) { var w = f, N = p, x = s, S = 1, P = x.m, k = x.gc[x.ab], F = y(P, 2); if (x.Oc & 1 << F) c = 0;else { switch (x.Oc |= 1 << F, k.hc = F, k.Ea = w[0], k.nc = N[0], k.K = [null], ++x.ab, e(4 >= x.ab), F) { case 0: case 1: k.b = y(P, 3) + 2, S = Ft(q(k.Ea, k.b), q(k.nc, k.b), 0, x, k.K), k.K = k.K[0]; break; case 3: var I, C = y(P, 8) + 1, j = 16 < C ? 0 : 4 < C ? 1 : 2 < C ? 2 : 3; if (w[0] = q(k.Ea, j), k.b = j, I = S = Ft(C, 1, 0, x, k.K)) { var O, M = C, E = k, T = 1 << (8 >> E.b), D = a(T); if (null == D) I = 0;else { var U = E.K[0], z = E.w; for (D[0] = E.K[0][0], O = 1; O < 1 * M; ++O) { D[O] = R(U[z + O], D[O - 1]); } for (; O < 4 * T; ++O) { D[O] = 0; } E.K[0] = null, E.K[0] = D, I = 1; } } S = I; break; case 2: break; default: e(0); } c = S; } } if (f = f[0], p = p[0], c && y(g, 1) && !(c = 1 <= (b = y(g, 4)) && 11 >= b)) { s.a = 3; break t; } var H; if (H = c) e: { var W, V, G, Y = s, J = f, X = p, K = b, Z = r, $ = Y.m, Q = Y.s, tt = [null], et = 1, nt = 0, rt = Qr[K]; n: for (;;) { if (Z && y($, 1)) { var it = y($, 3) + 2, at = q(J, it), ot = q(X, it), st = at * ot; if (!Ft(at, ot, 0, Y, tt)) break n; for (tt = tt[0], Q.xc = it, W = 0; W < st; ++W) { var ut = tt[W] >> 8 & 65535; tt[W] = ut, ut >= et && (et = ut + 1); } } if ($.h) break n; for (V = 0; 5 > V; ++V) { var ct = Xr[V]; !V && 0 < K && (ct += 1 << K), nt < ct && (nt = ct); } var ht = o(et * rt, l), lt = et, ft = o(lt, d); if (null == ft) var dt = null;else e(65536 >= lt), dt = ft; var pt = a(nt); if (null == dt || null == pt || null == ht) { Y.a = 1; break n; } var gt = ht; for (W = G = 0; W < et; ++W) { var mt = dt[W], vt = mt.G, bt = mt.H, wt = 0, Nt = 1, Lt = 0; for (V = 0; 5 > V; ++V) { ct = Xr[V], vt[V] = gt, bt[V] = G, !V && 0 < K && (ct += 1 << K); r: { var xt, At = ct, _t = Y, kt = pt, It = gt, Ct = G, jt = 0, Bt = _t.m, Ot = y(Bt, 1); if (i(kt, 0, 0, At), Ot) { var Mt = y(Bt, 1) + 1, Et = y(Bt, 1), qt = y(Bt, 0 == Et ? 1 : 8); kt[qt] = 1, 2 == Mt && (kt[qt = y(Bt, 8)] = 1); var Rt = 1; } else { var Tt = a(19), Dt = y(Bt, 4) + 4; if (19 < Dt) { _t.a = 3; var Ut = 0; break r; } for (xt = 0; xt < Dt; ++xt) { Tt[Zr[xt]] = y(Bt, 3); } var zt = void 0, Ht = void 0, Wt = _t, Vt = Tt, Gt = At, Yt = kt, Jt = 0, Xt = Wt.m, Kt = 8, Zt = o(128, l); i: for (; h(Zt, 0, 7, Vt, 19);) { if (y(Xt, 1)) { var $t = 2 + 2 * y(Xt, 3); if ((zt = 2 + y(Xt, $t)) > Gt) break i; } else zt = Gt; for (Ht = 0; Ht < Gt && zt--;) { _(Xt); var Qt = Zt[0 + (127 & L(Xt))]; A(Xt, Xt.u + Qt.g); var te = Qt.value; if (16 > te) Yt[Ht++] = te, 0 != te && (Kt = te);else { var ee = 16 == te, ne = te - 16, re = Jr[ne], ie = y(Xt, Yr[ne]) + re; if (Ht + ie > Gt) break i; for (var ae = ee ? Kt : 0; 0 < ie--;) { Yt[Ht++] = ae; } } } Jt = 1; break i; } Jt || (Wt.a = 3), Rt = Jt; } (Rt = Rt && !Bt.h) && (jt = h(It, Ct, 8, kt, At)), Rt && 0 != jt ? Ut = jt : (_t.a = 3, Ut = 0); } if (0 == Ut) break n; if (Nt && 1 == Kr[V] && (Nt = 0 == gt[G].g), wt += gt[G].g, G += Ut, 3 >= V) { var oe, se = pt[0]; for (oe = 1; oe < ct; ++oe) { pt[oe] > se && (se = pt[oe]); } Lt += se; } } if (mt.nd = Nt, mt.Qb = 0, Nt && (mt.qb = (vt[3][bt[3] + 0].value << 24 | vt[1][bt[1] + 0].value << 16 | vt[2][bt[2] + 0].value) >>> 0, 0 == wt && 256 > vt[0][bt[0] + 0].value && (mt.Qb = 1, mt.qb += vt[0][bt[0] + 0].value << 8)), mt.jc = !mt.Qb && 6 > Lt, mt.jc) { var ue, ce = mt; for (ue = 0; ue < Tn; ++ue) { var he = ue, le = ce.pd[he], fe = ce.G[0][ce.H[0] + he]; 256 <= fe.value ? (le.g = fe.g + 256, le.value = fe.value) : (le.g = 0, le.value = 0, he >>= yt(fe, 8, le), he >>= yt(ce.G[1][ce.H[1] + he], 16, le), he >>= yt(ce.G[2][ce.H[2] + he], 0, le), yt(ce.G[3][ce.H[3] + he], 24, le)); } } } Q.vc = tt, Q.Wb = et, Q.Ya = dt, Q.yc = ht, H = 1; break e; } H = 0; } if (!(c = H)) { s.a = 3; break t; } if (0 < b) { if (m.ua = 1 << b, !B(m.Wa, b)) { s.a = 1, c = 0; break t; } } else m.ua = 0; var de = s, pe = f, ge = p, me = de.s, ve = me.xc; if (de.c = pe, de.i = ge, me.md = q(pe, ve), me.wc = 0 == ve ? -1 : (1 << ve) - 1, r) { s.xb = pi; break t; } if (null == (v = a(f * p))) { s.a = 1, c = 0; break t; } c = (c = St(s, v, 0, f, p, p, null)) && !g.h; break t; } return c ? (null != u ? u[0] = v : (e(null == v), e(r)), s.$ = 0, r || Pt(m)) : Pt(m), c; } function It(t, n) { var r = t.c * t.i, i = r + n + 16 * n; return e(t.c <= n), t.V = a(i), null == t.V ? (t.Ta = null, t.Ua = 0, t.a = 1, 0) : (t.Ta = t.V, t.Ua = t.Ba + r + n, 1); } function Ct(t, n) { var r = t.C, i = n - r, a = t.V, o = t.Ba + t.c * r; for (e(n <= t.l.o); 0 < i;) { var s = 16 < i ? 16 : i, u = t.l.ma, c = t.l.width, h = c * s, l = u.ca, f = u.tb + c * r, d = t.Ta, p = t.Ua; Nt(t, s, a, o), Sr(d, p, l, f, h), At(u, r, r + s, l, f, c), i -= s, a += s * t.c, r += s; } e(r == n), t.C = t.Ma = n; } function jt() { this.ub = this.yd = this.td = this.Rb = 0; } function Bt() { this.Kd = this.Ld = this.Ud = this.Td = this.i = this.c = 0; } function Ot() { this.Fb = this.Bb = this.Cb = 0, this.Zb = a(4), this.Lb = a(4); } function Mt() { this.Yb = function () { var t = []; return function t(e, n, r) { for (var i = r[n], a = 0; a < i && (e.push(r.length > n + 1 ? [] : 0), !(r.length < n + 1)); a++) { t(e[a], n + 1, r); } }(t, 0, [3, 11]), t; }(); } function Et() { this.jb = a(3), this.Wc = s([4, 8], Mt), this.Xc = s([4, 17], Mt); } function qt() { this.Pc = this.wb = this.Tb = this.zd = 0, this.vd = new a(4), this.od = new a(4); } function Rt() { this.ld = this.La = this.dd = this.tc = 0; } function Tt() { this.Na = this.la = 0; } function Dt() { this.Sc = [0, 0], this.Eb = [0, 0], this.Qc = [0, 0], this.ia = this.lc = 0; } function Ut() { this.ad = a(384), this.Za = 0, this.Ob = a(16), this.$b = this.Ad = this.ia = this.Gc = this.Hc = this.Dd = 0; } function zt() { this.uc = this.M = this.Nb = 0, this.wa = Array(new Rt()), this.Y = 0, this.ya = Array(new Ut()), this.aa = 0, this.l = new Gt(); } function Ht() { this.y = a(16), this.f = a(8), this.ea = a(8); } function Wt() { this.cb = this.a = 0, this.sc = "", this.m = new w(), this.Od = new jt(), this.Kc = new Bt(), this.ed = new qt(), this.Qa = new Ot(), this.Ic = this.$c = this.Aa = 0, this.D = new zt(), this.Xb = this.Va = this.Hb = this.zb = this.yb = this.Ub = this.za = 0, this.Jc = o(8, w), this.ia = 0, this.pb = o(4, Dt), this.Pa = new Et(), this.Bd = this.kc = 0, this.Ac = [], this.Bc = 0, this.zc = [0, 0, 0, 0], this.Gd = Array(new Ht()), this.Hd = 0, this.rb = Array(new Tt()), this.sb = 0, this.wa = Array(new Rt()), this.Y = 0, this.oc = [], this.pc = 0, this.sa = [], this.ta = 0, this.qa = [], this.ra = 0, this.Ha = [], this.B = this.R = this.Ia = 0, this.Ec = [], this.M = this.ja = this.Vb = this.Fc = 0, this.ya = Array(new Ut()), this.L = this.aa = 0, this.gd = s([4, 2], Rt), this.ga = null, this.Fa = [], this.Cc = this.qc = this.P = 0, this.Gb = [], this.Uc = 0, this.mb = [], this.nb = 0, this.rc = [], this.Ga = this.Vc = 0; } function Vt(t, e) { return 0 > t ? 0 : t > e ? e : t; } function Gt() { this.T = this.U = this.ka = this.height = this.width = 0, this.y = [], this.f = [], this.ea = [], this.Rc = this.fa = this.W = this.N = this.O = 0, this.ma = "void", this.put = "VP8IoPutHook", this.ac = "VP8IoSetupHook", this.bc = "VP8IoTeardownHook", this.ha = this.Kb = 0, this.data = [], this.hb = this.ib = this.da = this.o = this.j = this.va = this.v = this.Da = this.ob = this.w = 0, this.F = [], this.J = 0; } function Yt() { var t = new Wt(); return null != t && (t.a = 0, t.sc = "OK", t.cb = 0, t.Xb = 0, ri || (ri = Zt)), t; } function Jt(t, e, n) { return 0 == t.a && (t.a = e, t.sc = n, t.cb = 0), 0; } function Xt(t, e, n) { return 3 <= n && 157 == t[e + 0] && 1 == t[e + 1] && 42 == t[e + 2]; } function Kt(t, n) { if (null == t) return 0; if (t.a = 0, t.sc = "OK", null == n) return Jt(t, 2, "null VP8Io passed to VP8GetHeaders()"); var r = n.data, a = n.w, o = n.ha; if (4 > o) return Jt(t, 7, "Truncated header."); var s = r[a + 0] | r[a + 1] << 8 | r[a + 2] << 16, u = t.Od; if (u.Rb = !(1 & s), u.td = s >> 1 & 7, u.yd = s >> 4 & 1, u.ub = s >> 5, 3 < u.td) return Jt(t, 3, "Incorrect keyframe parameters."); if (!u.yd) return Jt(t, 4, "Frame not displayable."); a += 3, o -= 3; var c = t.Kc; if (u.Rb) { if (7 > o) return Jt(t, 7, "cannot parse picture header"); if (!Xt(r, a, o)) return Jt(t, 3, "Bad code word"); c.c = 16383 & (r[a + 4] << 8 | r[a + 3]), c.Td = r[a + 4] >> 6, c.i = 16383 & (r[a + 6] << 8 | r[a + 5]), c.Ud = r[a + 6] >> 6, a += 7, o -= 7, t.za = c.c + 15 >> 4, t.Ub = c.i + 15 >> 4, n.width = c.c, n.height = c.i, n.Da = 0, n.j = 0, n.v = 0, n.va = n.width, n.o = n.height, n.da = 0, n.ib = n.width, n.hb = n.height, n.U = n.width, n.T = n.height, i((s = t.Pa).jb, 0, 255, s.jb.length), e(null != (s = t.Qa)), s.Cb = 0, s.Bb = 0, s.Fb = 1, i(s.Zb, 0, 0, s.Zb.length), i(s.Lb, 0, 0, s.Lb); } if (u.ub > o) return Jt(t, 7, "bad partition length"); p(s = t.m, r, a, u.ub), a += u.ub, o -= u.ub, u.Rb && (c.Ld = P(s), c.Kd = P(s)), c = t.Qa; var h, l = t.Pa; if (e(null != s), e(null != c), c.Cb = P(s), c.Cb) { if (c.Bb = P(s), P(s)) { for (c.Fb = P(s), h = 0; 4 > h; ++h) { c.Zb[h] = P(s) ? m(s, 7) : 0; } for (h = 0; 4 > h; ++h) { c.Lb[h] = P(s) ? m(s, 6) : 0; } } if (c.Bb) for (h = 0; 3 > h; ++h) { l.jb[h] = P(s) ? g(s, 8) : 255; } } else c.Bb = 0; if (s.Ka) return Jt(t, 3, "cannot parse segment header"); if ((c = t.ed).zd = P(s), c.Tb = g(s, 6), c.wb = g(s, 3), c.Pc = P(s), c.Pc && P(s)) { for (l = 0; 4 > l; ++l) { P(s) && (c.vd[l] = m(s, 6)); } for (l = 0; 4 > l; ++l) { P(s) && (c.od[l] = m(s, 6)); } } if (t.L = 0 == c.Tb ? 0 : c.zd ? 1 : 2, s.Ka) return Jt(t, 3, "cannot parse filter header"); var f = o; if (o = h = a, a = h + f, c = f, t.Xb = (1 << g(t.m, 2)) - 1, f < 3 * (l = t.Xb)) r = 7;else { for (h += 3 * l, c -= 3 * l, f = 0; f < l; ++f) { var d = r[o + 0] | r[o + 1] << 8 | r[o + 2] << 16; d > c && (d = c), p(t.Jc[+f], r, h, d), h += d, c -= d, o += 3; } p(t.Jc[+l], r, h, c), r = h < a ? 0 : 5; } if (0 != r) return Jt(t, r, "cannot parse partitions"); for (r = g(h = t.m, 7), o = P(h) ? m(h, 4) : 0, a = P(h) ? m(h, 4) : 0, c = P(h) ? m(h, 4) : 0, l = P(h) ? m(h, 4) : 0, h = P(h) ? m(h, 4) : 0, f = t.Qa, d = 0; 4 > d; ++d) { if (f.Cb) { var v = f.Zb[d]; f.Fb || (v += r); } else { if (0 < d) { t.pb[d] = t.pb[0]; continue; } v = r; } var b = t.pb[d]; b.Sc[0] = ei[Vt(v + o, 127)], b.Sc[1] = ni[Vt(v + 0, 127)], b.Eb[0] = 2 * ei[Vt(v + a, 127)], b.Eb[1] = 101581 * ni[Vt(v + c, 127)] >> 16, 8 > b.Eb[1] && (b.Eb[1] = 8), b.Qc[0] = ei[Vt(v + l, 117)], b.Qc[1] = ni[Vt(v + h, 127)], b.lc = v + h; } if (!u.Rb) return Jt(t, 4, "Not a key frame."); for (P(s), u = t.Pa, r = 0; 4 > r; ++r) { for (o = 0; 8 > o; ++o) { for (a = 0; 3 > a; ++a) { for (c = 0; 11 > c; ++c) { l = k(s, ci[r][o][a][c]) ? g(s, 8) : si[r][o][a][c], u.Wc[r][o].Yb[a][c] = l; } } } for (o = 0; 17 > o; ++o) { u.Xc[r][o] = u.Wc[r][hi[o]]; } } return t.kc = P(s), t.kc && (t.Bd = g(s, 8)), t.cb = 1; } function Zt(t, e, n, r, i, a, o) { var s = e[i].Yb[n]; for (n = 0; 16 > i; ++i) { if (!k(t, s[n + 0])) return i; for (; !k(t, s[n + 1]);) { if (s = e[++i].Yb[0], n = 0, 16 == i) return 16; } var u = e[i + 1].Yb; if (k(t, s[n + 2])) { var c = t, h = 0; if (k(c, (f = s)[(l = n) + 3])) { if (k(c, f[l + 6])) { for (s = 0, l = 2 * (h = k(c, f[l + 8])) + (f = k(c, f[l + 9 + h])), h = 0, f = ii[l]; f[s]; ++s) { h += h + k(c, f[s]); } h += 3 + (8 << l); } else k(c, f[l + 7]) ? (h = 7 + 2 * k(c, 165), h += k(c, 145)) : h = 5 + k(c, 159); } else h = k(c, f[l + 4]) ? 3 + k(c, f[l + 5]) : 2; s = u[2]; } else h = 1, s = u[1]; u = o + ai[i], 0 > (c = t).b && S(c); var l, f = c.b, d = (l = c.Ca >> 1) - (c.I >> f) >> 31; --c.b, c.Ca += d, c.Ca |= 1, c.I -= (l + 1 & d) << f, a[u] = ((h ^ d) - d) * r[(0 < i) + 0]; } return 16; } function $t(t) { var e = t.rb[t.sb - 1]; e.la = 0, e.Na = 0, i(t.zc, 0, 0, t.zc.length), t.ja = 0; } function Qt(t, n) { if (null == t) return 0; if (null == n) return Jt(t, 2, "NULL VP8Io parameter in VP8Decode()."); if (!t.cb && !Kt(t, n)) return 0; if (e(t.cb), null == n.ac || n.ac(n)) { n.ob && (t.L = 0); var s = Ti[t.L]; if (2 == t.L ? (t.yb = 0, t.zb = 0) : (t.yb = n.v - s >> 4, t.zb = n.j - s >> 4, 0 > t.yb && (t.yb = 0), 0 > t.zb && (t.zb = 0)), t.Va = n.o + 15 + s >> 4, t.Hb = n.va + 15 + s >> 4, t.Hb > t.za && (t.Hb = t.za), t.Va > t.Ub && (t.Va = t.Ub), 0 < t.L) { var u = t.ed; for (s = 0; 4 > s; ++s) { var c; if (t.Qa.Cb) { var h = t.Qa.Lb[s]; t.Qa.Fb || (h += u.Tb); } else h = u.Tb; for (c = 0; 1 >= c; ++c) { var l = t.gd[s][c], f = h; if (u.Pc && (f += u.vd[0], c && (f += u.od[0])), 0 < (f = 0 > f ? 0 : 63 < f ? 63 : f)) { var d = f; 0 < u.wb && (d = 4 < u.wb ? d >> 2 : d >> 1) > 9 - u.wb && (d = 9 - u.wb), 1 > d && (d = 1), l.dd = d, l.tc = 2 * f + d, l.ld = 40 <= f ? 2 : 15 <= f ? 1 : 0; } else l.tc = 0; l.La = c; } } } s = 0; } else Jt(t, 6, "Frame setup failed"), s = t.a; if (s = 0 == s) { if (s) { t.$c = 0, 0 < t.Aa || (t.Ic = Ui); t: { s = t.Ic; u = 4 * (d = t.za); var p = 32 * d, g = d + 1, m = 0 < t.L ? d * (0 < t.Aa ? 2 : 1) : 0, v = (2 == t.Aa ? 2 : 1) * d; if ((l = u + 832 + (c = 3 * (16 * s + Ti[t.L]) / 2 * p) + (h = null != t.Fa && 0 < t.Fa.length ? t.Kc.c * t.Kc.i : 0)) != l) s = 0;else { if (l > t.Vb) { if (t.Vb = 0, t.Ec = a(l), t.Fc = 0, null == t.Ec) { s = Jt(t, 1, "no memory during frame initialization."); break t; } t.Vb = l; } l = t.Ec, f = t.Fc, t.Ac = l, t.Bc = f, f += u, t.Gd = o(p, Ht), t.Hd = 0, t.rb = o(g + 1, Tt), t.sb = 1, t.wa = m ? o(m, Rt) : null, t.Y = 0, t.D.Nb = 0, t.D.wa = t.wa, t.D.Y = t.Y, 0 < t.Aa && (t.D.Y += d), e(!0), t.oc = l, t.pc = f, f += 832, t.ya = o(v, Ut), t.aa = 0, t.D.ya = t.ya, t.D.aa = t.aa, 2 == t.Aa && (t.D.aa += d), t.R = 16 * d, t.B = 8 * d, d = (p = Ti[t.L]) * t.R, p = p / 2 * t.B, t.sa = l, t.ta = f + d, t.qa = t.sa, t.ra = t.ta + 16 * s * t.R + p, t.Ha = t.qa, t.Ia = t.ra + 8 * s * t.B + p, t.$c = 0, f += c, t.mb = h ? l : null, t.nb = h ? f : null, e(f + h <= t.Fc + t.Vb), $t(t), i(t.Ac, t.Bc, 0, u), s = 1; } } if (s) { if (n.ka = 0, n.y = t.sa, n.O = t.ta, n.f = t.qa, n.N = t.ra, n.ea = t.Ha, n.Vd = t.Ia, n.fa = t.R, n.Rc = t.B, n.F = null, n.J = 0, !Cr) { for (s = -255; 255 >= s; ++s) { Pr[255 + s] = 0 > s ? -s : s; } for (s = -1020; 1020 >= s; ++s) { kr[1020 + s] = -128 > s ? -128 : 127 < s ? 127 : s; } for (s = -112; 112 >= s; ++s) { Fr[112 + s] = -16 > s ? -16 : 15 < s ? 15 : s; } for (s = -255; 510 >= s; ++s) { Ir[255 + s] = 0 > s ? 0 : 255 < s ? 255 : s; } Cr = 1; } ar = ce, or = ae, ur = oe, cr = se, hr = ue, sr = ie, lr = Je, fr = Xe, dr = $e, pr = Qe, gr = Ke, mr = Ze, vr = tn, br = en, yr = ze, wr = He, Nr = We, Lr = Ve, fi[0] = Ae, fi[1] = le, fi[2] = Le, fi[3] = xe, fi[4] = _e, fi[5] = Pe, fi[6] = Se, fi[7] = ke, fi[8] = Ie, fi[9] = Fe, li[0] = ve, li[1] = de, li[2] = pe, li[3] = ge, li[4] = be, li[5] = ye, li[6] = we, di[0] = Oe, di[1] = fe, di[2] = Ce, di[3] = je, di[4] = Ee, di[5] = Me, di[6] = qe, s = 1; } else s = 0; } s && (s = function (t, n) { for (t.M = 0; t.M < t.Va; ++t.M) { var o, s = t.Jc[t.M & t.Xb], u = t.m, c = t; for (o = 0; o < c.za; ++o) { var h = u, l = c, f = l.Ac, d = l.Bc + 4 * o, p = l.zc, g = l.ya[l.aa + o]; if (l.Qa.Bb ? g.$b = k(h, l.Pa.jb[0]) ? 2 + k(h, l.Pa.jb[2]) : k(h, l.Pa.jb[1]) : g.$b = 0, l.kc && (g.Ad = k(h, l.Bd)), g.Za = !k(h, 145) + 0, g.Za) { var m = g.Ob, v = 0; for (l = 0; 4 > l; ++l) { var b, y = p[0 + l]; for (b = 0; 4 > b; ++b) { y = ui[f[d + b]][y]; for (var w = oi[k(h, y[0])]; 0 < w;) { w = oi[2 * w + k(h, y[w])]; } y = -w, f[d + b] = y; } r(m, v, f, d, 4), v += 4, p[0 + l] = y; } } else y = k(h, 156) ? k(h, 128) ? 1 : 3 : k(h, 163) ? 2 : 0, g.Ob[0] = y, i(f, d, y, 4), i(p, 0, y, 4); g.Dd = k(h, 142) ? k(h, 114) ? k(h, 183) ? 1 : 3 : 2 : 0; } if (c.m.Ka) return Jt(t, 7, "Premature end-of-partition0 encountered."); for (; t.ja < t.za; ++t.ja) { if (c = s, h = (u = t).rb[u.sb - 1], f = u.rb[u.sb + u.ja], o = u.ya[u.aa + u.ja], d = u.kc ? o.Ad : 0) h.la = f.la = 0, o.Za || (h.Na = f.Na = 0), o.Hc = 0, o.Gc = 0, o.ia = 0;else { var N, L; h = f, f = c, d = u.Pa.Xc, p = u.ya[u.aa + u.ja], g = u.pb[p.$b]; if (l = p.ad, m = 0, v = u.rb[u.sb - 1], y = b = 0, i(l, m, 0, 384), p.Za) var x = 0, A = d[3];else { w = a(16); var _ = h.Na + v.Na; if (_ = ri(f, d[1], _, g.Eb, 0, w, 0), h.Na = v.Na = (0 < _) + 0, 1 < _) ar(w, 0, l, m);else { var S = w[0] + 3 >> 3; for (w = 0; 256 > w; w += 16) { l[m + w] = S; } } x = 1, A = d[0]; } var P = 15 & h.la, F = 15 & v.la; for (w = 0; 4 > w; ++w) { var I = 1 & F; for (S = L = 0; 4 > S; ++S) { P = P >> 1 | (I = (_ = ri(f, A, _ = I + (1 & P), g.Sc, x, l, m)) > x) << 7, L = L << 2 | (3 < _ ? 3 : 1 < _ ? 2 : 0 != l[m + 0]), m += 16; } P >>= 4, F = F >> 1 | I << 7, b = (b << 8 | L) >>> 0; } for (A = P, x = F >> 4, N = 0; 4 > N; N += 2) { for (L = 0, P = h.la >> 4 + N, F = v.la >> 4 + N, w = 0; 2 > w; ++w) { for (I = 1 & F, S = 0; 2 > S; ++S) { _ = I + (1 & P), P = P >> 1 | (I = 0 < (_ = ri(f, d[2], _, g.Qc, 0, l, m))) << 3, L = L << 2 | (3 < _ ? 3 : 1 < _ ? 2 : 0 != l[m + 0]), m += 16; } P >>= 2, F = F >> 1 | I << 5; } y |= L << 4 * N, A |= P << 4 << N, x |= (240 & F) << N; } h.la = A, v.la = x, p.Hc = b, p.Gc = y, p.ia = 43690 & y ? 0 : g.ia, d = !(b | y); } if (0 < u.L && (u.wa[u.Y + u.ja] = u.gd[o.$b][o.Za], u.wa[u.Y + u.ja].La |= !d), c.Ka) return Jt(t, 7, "Premature end-of-file encountered."); } if ($t(t), u = n, c = 1, o = (s = t).D, h = 0 < s.L && s.M >= s.zb && s.M <= s.Va, 0 == s.Aa) t: { if (o.M = s.M, o.uc = h, On(s, o), c = 1, o = (L = s.D).Nb, h = (y = Ti[s.L]) * s.R, f = y / 2 * s.B, w = 16 * o * s.R, S = 8 * o * s.B, d = s.sa, p = s.ta - h + w, g = s.qa, l = s.ra - f + S, m = s.Ha, v = s.Ia - f + S, F = 0 == (P = L.M), b = P >= s.Va - 1, 2 == s.Aa && On(s, L), L.uc) for (I = (_ = s).D.M, e(_.D.uc), L = _.yb; L < _.Hb; ++L) { x = L, A = I; var C = (j = (U = _).D).Nb; N = U.R; var j = j.wa[j.Y + x], B = U.sa, O = U.ta + 16 * C * N + 16 * x, M = j.dd, E = j.tc; if (0 != E) if (e(3 <= E), 1 == U.L) 0 < x && wr(B, O, N, E + 4), j.La && Lr(B, O, N, E), 0 < A && yr(B, O, N, E + 4), j.La && Nr(B, O, N, E);else { var q = U.B, R = U.qa, T = U.ra + 8 * C * q + 8 * x, D = U.Ha, U = U.Ia + 8 * C * q + 8 * x; C = j.ld; 0 < x && (fr(B, O, N, E + 4, M, C), pr(R, T, D, U, q, E + 4, M, C)), j.La && (mr(B, O, N, E, M, C), br(R, T, D, U, q, E, M, C)), 0 < A && (lr(B, O, N, E + 4, M, C), dr(R, T, D, U, q, E + 4, M, C)), j.La && (gr(B, O, N, E, M, C), vr(R, T, D, U, q, E, M, C)); } } if (s.ia && alert("todo:DitherRow"), null != u.put) { if (L = 16 * P, P = 16 * (P + 1), F ? (u.y = s.sa, u.O = s.ta + w, u.f = s.qa, u.N = s.ra + S, u.ea = s.Ha, u.W = s.Ia + S) : (L -= y, u.y = d, u.O = p, u.f = g, u.N = l, u.ea = m, u.W = v), b || (P -= y), P > u.o && (P = u.o), u.F = null, u.J = null, null != s.Fa && 0 < s.Fa.length && L < P && (u.J = fn(s, u, L, P - L), u.F = s.mb, null == u.F && 0 == u.F.length)) { c = Jt(s, 3, "Could not decode alpha data."); break t; } L < u.j && (y = u.j - L, L = u.j, e(!(1 & y)), u.O += s.R * y, u.N += s.B * (y >> 1), u.W += s.B * (y >> 1), null != u.F && (u.J += u.width * y)), L < P && (u.O += u.v, u.N += u.v >> 1, u.W += u.v >> 1, null != u.F && (u.J += u.v), u.ka = L - u.j, u.U = u.va - u.v, u.T = P - L, c = u.put(u)); } o + 1 != s.Ic || b || (r(s.sa, s.ta - h, d, p + 16 * s.R, h), r(s.qa, s.ra - f, g, l + 8 * s.B, f), r(s.Ha, s.Ia - f, m, v + 8 * s.B, f)); } if (!c) return Jt(t, 6, "Output aborted."); } return 1; }(t, n)), null != n.bc && n.bc(n), s &= 1; } return s ? (t.cb = 0, s) : 0; } function te(t, e, n, r, i) { i = t[e + n + 32 * r] + (i >> 3), t[e + n + 32 * r] = -256 & i ? 0 > i ? 0 : 255 : i; } function ee(t, e, n, r, i, a) { te(t, e, 0, n, r + i), te(t, e, 1, n, r + a), te(t, e, 2, n, r - a), te(t, e, 3, n, r - i); } function ne(t) { return (20091 * t >> 16) + t; } function re(t, e, n, r) { var i, o = 0, s = a(16); for (i = 0; 4 > i; ++i) { var u = t[e + 0] + t[e + 8], c = t[e + 0] - t[e + 8], h = (35468 * t[e + 4] >> 16) - ne(t[e + 12]), l = ne(t[e + 4]) + (35468 * t[e + 12] >> 16); s[o + 0] = u + l, s[o + 1] = c + h, s[o + 2] = c - h, s[o + 3] = u - l, o += 4, e++; } for (i = o = 0; 4 > i; ++i) { u = (t = s[o + 0] + 4) + s[o + 8], c = t - s[o + 8], h = (35468 * s[o + 4] >> 16) - ne(s[o + 12]), te(n, r, 0, 0, u + (l = ne(s[o + 4]) + (35468 * s[o + 12] >> 16))), te(n, r, 1, 0, c + h), te(n, r, 2, 0, c - h), te(n, r, 3, 0, u - l), o++, r += 32; } } function ie(t, e, n, r) { var i = t[e + 0] + 4, a = 35468 * t[e + 4] >> 16, o = ne(t[e + 4]), s = 35468 * t[e + 1] >> 16; ee(n, r, 0, i + o, t = ne(t[e + 1]), s), ee(n, r, 1, i + a, t, s), ee(n, r, 2, i - a, t, s), ee(n, r, 3, i - o, t, s); } function ae(t, e, n, r, i) { re(t, e, n, r), i && re(t, e + 16, n, r + 4); } function oe(t, e, n, r) { or(t, e + 0, n, r, 1), or(t, e + 32, n, r + 128, 1); } function se(t, e, n, r) { var i; for (t = t[e + 0] + 4, i = 0; 4 > i; ++i) { for (e = 0; 4 > e; ++e) { te(n, r, e, i, t); } } } function ue(t, e, n, r) { t[e + 0] && cr(t, e + 0, n, r), t[e + 16] && cr(t, e + 16, n, r + 4), t[e + 32] && cr(t, e + 32, n, r + 128), t[e + 48] && cr(t, e + 48, n, r + 128 + 4); } function ce(t, e, n, r) { var i, o = a(16); for (i = 0; 4 > i; ++i) { var s = t[e + 0 + i] + t[e + 12 + i], u = t[e + 4 + i] + t[e + 8 + i], c = t[e + 4 + i] - t[e + 8 + i], h = t[e + 0 + i] - t[e + 12 + i]; o[0 + i] = s + u, o[8 + i] = s - u, o[4 + i] = h + c, o[12 + i] = h - c; } for (i = 0; 4 > i; ++i) { s = (t = o[0 + 4 * i] + 3) + o[3 + 4 * i], u = o[1 + 4 * i] + o[2 + 4 * i], c = o[1 + 4 * i] - o[2 + 4 * i], h = t - o[3 + 4 * i], n[r + 0] = s + u >> 3, n[r + 16] = h + c >> 3, n[r + 32] = s - u >> 3, n[r + 48] = h - c >> 3, r += 64; } } function he(t, e, n) { var r, i = e - 32, a = Or, o = 255 - t[i - 1]; for (r = 0; r < n; ++r) { var s, u = a, c = o + t[e - 1]; for (s = 0; s < n; ++s) { t[e + s] = u[c + t[i + s]]; } e += 32; } } function le(t, e) { he(t, e, 4); } function fe(t, e) { he(t, e, 8); } function de(t, e) { he(t, e, 16); } function pe(t, e) { var n; for (n = 0; 16 > n; ++n) { r(t, e + 32 * n, t, e - 32, 16); } } function ge(t, e) { var n; for (n = 16; 0 < n; --n) { i(t, e, t[e - 1], 16), e += 32; } } function me(t, e, n) { var r; for (r = 0; 16 > r; ++r) { i(e, n + 32 * r, t, 16); } } function ve(t, e) { var n, r = 16; for (n = 0; 16 > n; ++n) { r += t[e - 1 + 32 * n] + t[e + n - 32]; } me(r >> 5, t, e); } function be(t, e) { var n, r = 8; for (n = 0; 16 > n; ++n) { r += t[e - 1 + 32 * n]; } me(r >> 4, t, e); } function ye(t, e) { var n, r = 8; for (n = 0; 16 > n; ++n) { r += t[e + n - 32]; } me(r >> 4, t, e); } function we(t, e) { me(128, t, e); } function Ne(t, e, n) { return t + 2 * e + n + 2 >> 2; } function Le(t, e) { var n, i = e - 32; i = new Uint8Array([Ne(t[i - 1], t[i + 0], t[i + 1]), Ne(t[i + 0], t[i + 1], t[i + 2]), Ne(t[i + 1], t[i + 2], t[i + 3]), Ne(t[i + 2], t[i + 3], t[i + 4])]); for (n = 0; 4 > n; ++n) { r(t, e + 32 * n, i, 0, i.length); } } function xe(t, e) { var n = t[e - 1], r = t[e - 1 + 32], i = t[e - 1 + 64], a = t[e - 1 + 96]; F(t, e + 0, 16843009 * Ne(t[e - 1 - 32], n, r)), F(t, e + 32, 16843009 * Ne(n, r, i)), F(t, e + 64, 16843009 * Ne(r, i, a)), F(t, e + 96, 16843009 * Ne(i, a, a)); } function Ae(t, e) { var n, r = 4; for (n = 0; 4 > n; ++n) { r += t[e + n - 32] + t[e - 1 + 32 * n]; } for (r >>= 3, n = 0; 4 > n; ++n) { i(t, e + 32 * n, r, 4); } } function _e(t, e) { var n = t[e - 1 + 0], r = t[e - 1 + 32], i = t[e - 1 + 64], a = t[e - 1 - 32], o = t[e + 0 - 32], s = t[e + 1 - 32], u = t[e + 2 - 32], c = t[e + 3 - 32]; t[e + 0 + 96] = Ne(r, i, t[e - 1 + 96]), t[e + 1 + 96] = t[e + 0 + 64] = Ne(n, r, i), t[e + 2 + 96] = t[e + 1 + 64] = t[e + 0 + 32] = Ne(a, n, r), t[e + 3 + 96] = t[e + 2 + 64] = t[e + 1 + 32] = t[e + 0 + 0] = Ne(o, a, n), t[e + 3 + 64] = t[e + 2 + 32] = t[e + 1 + 0] = Ne(s, o, a), t[e + 3 + 32] = t[e + 2 + 0] = Ne(u, s, o), t[e + 3 + 0] = Ne(c, u, s); } function Se(t, e) { var n = t[e + 1 - 32], r = t[e + 2 - 32], i = t[e + 3 - 32], a = t[e + 4 - 32], o = t[e + 5 - 32], s = t[e + 6 - 32], u = t[e + 7 - 32]; t[e + 0 + 0] = Ne(t[e + 0 - 32], n, r), t[e + 1 + 0] = t[e + 0 + 32] = Ne(n, r, i), t[e + 2 + 0] = t[e + 1 + 32] = t[e + 0 + 64] = Ne(r, i, a), t[e + 3 + 0] = t[e + 2 + 32] = t[e + 1 + 64] = t[e + 0 + 96] = Ne(i, a, o), t[e + 3 + 32] = t[e + 2 + 64] = t[e + 1 + 96] = Ne(a, o, s), t[e + 3 + 64] = t[e + 2 + 96] = Ne(o, s, u), t[e + 3 + 96] = Ne(s, u, u); } function Pe(t, e) { var n = t[e - 1 + 0], r = t[e - 1 + 32], i = t[e - 1 + 64], a = t[e - 1 - 32], o = t[e + 0 - 32], s = t[e + 1 - 32], u = t[e + 2 - 32], c = t[e + 3 - 32]; t[e + 0 + 0] = t[e + 1 + 64] = a + o + 1 >> 1, t[e + 1 + 0] = t[e + 2 + 64] = o + s + 1 >> 1, t[e + 2 + 0] = t[e + 3 + 64] = s + u + 1 >> 1, t[e + 3 + 0] = u + c + 1 >> 1, t[e + 0 + 96] = Ne(i, r, n), t[e + 0 + 64] = Ne(r, n, a), t[e + 0 + 32] = t[e + 1 + 96] = Ne(n, a, o), t[e + 1 + 32] = t[e + 2 + 96] = Ne(a, o, s), t[e + 2 + 32] = t[e + 3 + 96] = Ne(o, s, u), t[e + 3 + 32] = Ne(s, u, c); } function ke(t, e) { var n = t[e + 0 - 32], r = t[e + 1 - 32], i = t[e + 2 - 32], a = t[e + 3 - 32], o = t[e + 4 - 32], s = t[e + 5 - 32], u = t[e + 6 - 32], c = t[e + 7 - 32]; t[e + 0 + 0] = n + r + 1 >> 1, t[e + 1 + 0] = t[e + 0 + 64] = r + i + 1 >> 1, t[e + 2 + 0] = t[e + 1 + 64] = i + a + 1 >> 1, t[e + 3 + 0] = t[e + 2 + 64] = a + o + 1 >> 1, t[e + 0 + 32] = Ne(n, r, i), t[e + 1 + 32] = t[e + 0 + 96] = Ne(r, i, a), t[e + 2 + 32] = t[e + 1 + 96] = Ne(i, a, o), t[e + 3 + 32] = t[e + 2 + 96] = Ne(a, o, s), t[e + 3 + 64] = Ne(o, s, u), t[e + 3 + 96] = Ne(s, u, c); } function Fe(t, e) { var n = t[e - 1 + 0], r = t[e - 1 + 32], i = t[e - 1 + 64], a = t[e - 1 + 96]; t[e + 0 + 0] = n + r + 1 >> 1, t[e + 2 + 0] = t[e + 0 + 32] = r + i + 1 >> 1, t[e + 2 + 32] = t[e + 0 + 64] = i + a + 1 >> 1, t[e + 1 + 0] = Ne(n, r, i), t[e + 3 + 0] = t[e + 1 + 32] = Ne(r, i, a), t[e + 3 + 32] = t[e + 1 + 64] = Ne(i, a, a), t[e + 3 + 64] = t[e + 2 + 64] = t[e + 0 + 96] = t[e + 1 + 96] = t[e + 2 + 96] = t[e + 3 + 96] = a; } function Ie(t, e) { var n = t[e - 1 + 0], r = t[e - 1 + 32], i = t[e - 1 + 64], a = t[e - 1 + 96], o = t[e - 1 - 32], s = t[e + 0 - 32], u = t[e + 1 - 32], c = t[e + 2 - 32]; t[e + 0 + 0] = t[e + 2 + 32] = n + o + 1 >> 1, t[e + 0 + 32] = t[e + 2 + 64] = r + n + 1 >> 1, t[e + 0 + 64] = t[e + 2 + 96] = i + r + 1 >> 1, t[e + 0 + 96] = a + i + 1 >> 1, t[e + 3 + 0] = Ne(s, u, c), t[e + 2 + 0] = Ne(o, s, u), t[e + 1 + 0] = t[e + 3 + 32] = Ne(n, o, s), t[e + 1 + 32] = t[e + 3 + 64] = Ne(r, n, o), t[e + 1 + 64] = t[e + 3 + 96] = Ne(i, r, n), t[e + 1 + 96] = Ne(a, i, r); } function Ce(t, e) { var n; for (n = 0; 8 > n; ++n) { r(t, e + 32 * n, t, e - 32, 8); } } function je(t, e) { var n; for (n = 0; 8 > n; ++n) { i(t, e, t[e - 1], 8), e += 32; } } function Be(t, e, n) { var r; for (r = 0; 8 > r; ++r) { i(e, n + 32 * r, t, 8); } } function Oe(t, e) { var n, r = 8; for (n = 0; 8 > n; ++n) { r += t[e + n - 32] + t[e - 1 + 32 * n]; } Be(r >> 4, t, e); } function Me(t, e) { var n, r = 4; for (n = 0; 8 > n; ++n) { r += t[e + n - 32]; } Be(r >> 3, t, e); } function Ee(t, e) { var n, r = 4; for (n = 0; 8 > n; ++n) { r += t[e - 1 + 32 * n]; } Be(r >> 3, t, e); } function qe(t, e) { Be(128, t, e); } function Re(t, e, n) { var r = t[e - n], i = t[e + 0], a = 3 * (i - r) + jr[1020 + t[e - 2 * n] - t[e + n]], o = Br[112 + (a + 4 >> 3)]; t[e - n] = Or[255 + r + Br[112 + (a + 3 >> 3)]], t[e + 0] = Or[255 + i - o]; } function Te(t, e, n, r) { var i = t[e + 0], a = t[e + n]; return Mr[255 + t[e - 2 * n] - t[e - n]] > r || Mr[255 + a - i] > r; } function De(t, e, n, r) { return 4 * Mr[255 + t[e - n] - t[e + 0]] + Mr[255 + t[e - 2 * n] - t[e + n]] <= r; } function Ue(t, e, n, r, i) { var a = t[e - 3 * n], o = t[e - 2 * n], s = t[e - n], u = t[e + 0], c = t[e + n], h = t[e + 2 * n], l = t[e + 3 * n]; return 4 * Mr[255 + s - u] + Mr[255 + o - c] > r ? 0 : Mr[255 + t[e - 4 * n] - a] <= i && Mr[255 + a - o] <= i && Mr[255 + o - s] <= i && Mr[255 + l - h] <= i && Mr[255 + h - c] <= i && Mr[255 + c - u] <= i; } function ze(t, e, n, r) { var i = 2 * r + 1; for (r = 0; 16 > r; ++r) { De(t, e + r, n, i) && Re(t, e + r, n); } } function He(t, e, n, r) { var i = 2 * r + 1; for (r = 0; 16 > r; ++r) { De(t, e + r * n, 1, i) && Re(t, e + r * n, 1); } } function We(t, e, n, r) { var i; for (i = 3; 0 < i; --i) { ze(t, e += 4 * n, n, r); } } function Ve(t, e, n, r) { var i; for (i = 3; 0 < i; --i) { He(t, e += 4, n, r); } } function Ge(t, e, n, r, i, a, o, s) { for (a = 2 * a + 1; 0 < i--;) { if (Ue(t, e, n, a, o)) if (Te(t, e, n, s)) Re(t, e, n);else { var u = t, c = e, h = n, l = u[c - 2 * h], f = u[c - h], d = u[c + 0], p = u[c + h], g = u[c + 2 * h], m = 27 * (b = jr[1020 + 3 * (d - f) + jr[1020 + l - p]]) + 63 >> 7, v = 18 * b + 63 >> 7, b = 9 * b + 63 >> 7; u[c - 3 * h] = Or[255 + u[c - 3 * h] + b], u[c - 2 * h] = Or[255 + l + v], u[c - h] = Or[255 + f + m], u[c + 0] = Or[255 + d - m], u[c + h] = Or[255 + p - v], u[c + 2 * h] = Or[255 + g - b]; } e += r; } } function Ye(t, e, n, r, i, a, o, s) { for (a = 2 * a + 1; 0 < i--;) { if (Ue(t, e, n, a, o)) if (Te(t, e, n, s)) Re(t, e, n);else { var u = t, c = e, h = n, l = u[c - h], f = u[c + 0], d = u[c + h], p = Br[112 + ((g = 3 * (f - l)) + 4 >> 3)], g = Br[112 + (g + 3 >> 3)], m = p + 1 >> 1; u[c - 2 * h] = Or[255 + u[c - 2 * h] + m], u[c - h] = Or[255 + l + g], u[c + 0] = Or[255 + f - p], u[c + h] = Or[255 + d - m]; } e += r; } } function Je(t, e, n, r, i, a) { Ge(t, e, n, 1, 16, r, i, a); } function Xe(t, e, n, r, i, a) { Ge(t, e, 1, n, 16, r, i, a); } function Ke(t, e, n, r, i, a) { var o; for (o = 3; 0 < o; --o) { Ye(t, e += 4 * n, n, 1, 16, r, i, a); } } function Ze(t, e, n, r, i, a) { var o; for (o = 3; 0 < o; --o) { Ye(t, e += 4, 1, n, 16, r, i, a); } } function $e(t, e, n, r, i, a, o, s) { Ge(t, e, i, 1, 8, a, o, s), Ge(n, r, i, 1, 8, a, o, s); } function Qe(t, e, n, r, i, a, o, s) { Ge(t, e, 1, i, 8, a, o, s), Ge(n, r, 1, i, 8, a, o, s); } function tn(t, e, n, r, i, a, o, s) { Ye(t, e + 4 * i, i, 1, 8, a, o, s), Ye(n, r + 4 * i, i, 1, 8, a, o, s); } function en(t, e, n, r, i, a, o, s) { Ye(t, e + 4, 1, i, 8, a, o, s), Ye(n, r + 4, 1, i, 8, a, o, s); } function nn() { this.ba = new ot(), this.ec = [], this.cc = [], this.Mc = [], this.Dc = this.Nc = this.dc = this.fc = 0, this.Oa = new ut(), this.memory = 0, this.Ib = "OutputFunc", this.Jb = "OutputAlphaFunc", this.Nd = "OutputRowFunc"; } function rn() { this.data = [], this.offset = this.kd = this.ha = this.w = 0, this.na = [], this.xa = this.gb = this.Ja = this.Sa = this.P = 0; } function an() { this.nc = this.Ea = this.b = this.hc = 0, this.K = [], this.w = 0; } function on() { this.ua = 0, this.Wa = new M(), this.vb = new M(), this.md = this.xc = this.wc = 0, this.vc = [], this.Wb = 0, this.Ya = new d(), this.yc = new l(); } function sn() { this.xb = this.a = 0, this.l = new Gt(), this.ca = new ot(), this.V = [], this.Ba = 0, this.Ta = [], this.Ua = 0, this.m = new N(), this.Pb = 0, this.wd = new N(), this.Ma = this.$ = this.C = this.i = this.c = this.xd = 0, this.s = new on(), this.ab = 0, this.gc = o(4, an), this.Oc = 0; } function un() { this.Lc = this.Z = this.$a = this.i = this.c = 0, this.l = new Gt(), this.ic = 0, this.ca = [], this.tb = 0, this.qd = null, this.rd = 0; } function cn(t, e, n, r, i, a, o) { for (t = null == t ? 0 : t[e + 0], e = 0; e < o; ++e) { i[a + e] = t + n[r + e] & 255, t = i[a + e]; } } function hn(t, e, n, r, i, a, o) { var s; if (null == t) cn(null, null, n, r, i, a, o);else for (s = 0; s < o; ++s) { i[a + s] = t[e + s] + n[r + s] & 255; } } function ln(t, e, n, r, i, a, o) { if (null == t) cn(null, null, n, r, i, a, o);else { var s, u = t[e + 0], c = u, h = u; for (s = 0; s < o; ++s) { c = h + (u = t[e + s]) - c, h = n[r + s] + (-256 & c ? 0 > c ? 0 : 255 : c) & 255, c = u, i[a + s] = h; } } } function fn(t, n, i, o) { var s = n.width, u = n.o; if (e(null != t && null != n), 0 > i || 0 >= o || i + o > u) return null; if (!t.Cc) { if (null == t.ga) { var c; if (t.ga = new un(), (c = null == t.ga) || (c = n.width * n.o, e(0 == t.Gb.length), t.Gb = a(c), t.Uc = 0, null == t.Gb ? c = 0 : (t.mb = t.Gb, t.nb = t.Uc, t.rc = null, c = 1), c = !c), !c) { c = t.ga; var h = t.Fa, l = t.P, f = t.qc, d = t.mb, p = t.nb, g = l + 1, m = f - 1, b = c.l; if (e(null != h && null != d && null != n), mi[0] = null, mi[1] = cn, mi[2] = hn, mi[3] = ln, c.ca = d, c.tb = p, c.c = n.width, c.i = n.height, e(0 < c.c && 0 < c.i), 1 >= f) n = 0;else if (c.$a = h[l + 0] >> 0 & 3, c.Z = h[l + 0] >> 2 & 3, c.Lc = h[l + 0] >> 4 & 3, l = h[l + 0] >> 6 & 3, 0 > c.$a || 1 < c.$a || 4 <= c.Z || 1 < c.Lc || l) n = 0;else if (b.put = dt, b.ac = ft, b.bc = pt, b.ma = c, b.width = n.width, b.height = n.height, b.Da = n.Da, b.v = n.v, b.va = n.va, b.j = n.j, b.o = n.o, c.$a) t: { e(1 == c.$a), n = kt(); e: for (;;) { if (null == n) { n = 0; break t; } if (e(null != c), c.mc = n, n.c = c.c, n.i = c.i, n.l = c.l, n.l.ma = c, n.l.width = c.c, n.l.height = c.i, n.a = 0, v(n.m, h, g, m), !Ft(c.c, c.i, 1, n, null)) break e; if (1 == n.ab && 3 == n.gc[0].hc && xt(n.s) ? (c.ic = 1, h = n.c * n.i, n.Ta = null, n.Ua = 0, n.V = a(h), n.Ba = 0, null == n.V ? (n.a = 1, n = 0) : n = 1) : (c.ic = 0, n = It(n, c.c)), !n) break e; n = 1; break t; } c.mc = null, n = 0; } else n = m >= c.c * c.i; c = !n; } if (c) return null; 1 != t.ga.Lc ? t.Ga = 0 : o = u - i; } e(null != t.ga), e(i + o <= u); t: { if (n = (h = t.ga).c, u = h.l.o, 0 == h.$a) { if (g = t.rc, m = t.Vc, b = t.Fa, l = t.P + 1 + i * n, f = t.mb, d = t.nb + i * n, e(l <= t.P + t.qc), 0 != h.Z) for (e(null != mi[h.Z]), c = 0; c < o; ++c) { mi[h.Z](g, m, b, l, f, d, n), g = f, m = d, d += n, l += n; } else for (c = 0; c < o; ++c) { r(f, d, b, l, n), g = f, m = d, d += n, l += n; } t.rc = g, t.Vc = m; } else { if (e(null != h.mc), n = i + o, e(null != (c = h.mc)), e(n <= c.i), c.C >= n) n = 1;else if (h.ic || vn(), h.ic) { h = c.V, g = c.Ba, m = c.c; var y = c.i, w = (b = 1, l = c.$ / m, f = c.$ % m, d = c.m, p = c.s, c.$), N = m * y, L = m * n, A = p.wc, S = w < L ? wt(p, f, l) : null; e(w <= N), e(n <= y), e(xt(p)); e: for (;;) { for (; !d.h && w < L;) { if (f & A || (S = wt(p, f, l)), e(null != S), _(d), 256 > (y = bt(S.G[0], S.H[0], d))) h[g + w] = y, ++w, ++f >= m && (f = 0, ++l <= n && !(l % 16) && _t(c, l));else { if (!(280 > y)) { b = 0; break e; } y = mt(y - 256, d); var P, k = bt(S.G[4], S.H[4], d); if (_(d), !(w >= (k = vt(m, k = mt(k, d))) && N - w >= y)) { b = 0; break e; } for (P = 0; P < y; ++P) { h[g + w + P] = h[g + w + P - k]; } for (w += y, f += y; f >= m;) { f -= m, ++l <= n && !(l % 16) && _t(c, l); } w < L && f & A && (S = wt(p, f, l)); } e(d.h == x(d)); } _t(c, l > n ? n : l); break e; } !b || d.h && w < N ? (b = 0, c.a = d.h ? 5 : 3) : c.$ = w, n = b; } else n = St(c, c.V, c.Ba, c.c, c.i, n, Ct); if (!n) { o = 0; break t; } } i + o >= u && (t.Cc = 1), o = 1; } if (!o) return null; if (t.Cc && (null != (o = t.ga) && (o.mc = null), t.ga = null, 0 < t.Ga)) return alert("todo:WebPDequantizeLevels"), null; } return t.nb + i * s; } function dn(t, e, n, r, i, a) { for (; 0 < i--;) { var o, s = t, u = e + (n ? 1 : 0), c = t, h = e + (n ? 0 : 3); for (o = 0; o < r; ++o) { var l = c[h + 4 * o]; 255 != l && (l *= 32897, s[u + 4 * o + 0] = s[u + 4 * o + 0] * l >> 23, s[u + 4 * o + 1] = s[u + 4 * o + 1] * l >> 23, s[u + 4 * o + 2] = s[u + 4 * o + 2] * l >> 23); } e += a; } } function pn(t, e, n, r, i) { for (; 0 < r--;) { var a; for (a = 0; a < n; ++a) { var o = t[e + 2 * a + 0], s = 15 & (c = t[e + 2 * a + 1]), u = 4369 * s, c = (240 & c | c >> 4) * u >> 16; t[e + 2 * a + 0] = (240 & o | o >> 4) * u >> 16 & 240 | (15 & o | o << 4) * u >> 16 >> 4 & 15, t[e + 2 * a + 1] = 240 & c | s; } e += i; } } function gn(t, e, n, r, i, a, o, s) { var u, c, h = 255; for (c = 0; c < i; ++c) { for (u = 0; u < r; ++u) { var l = t[e + u]; a[o + 4 * u] = l, h &= l; } e += n, o += s; } return 255 != h; } function mn(t, e, n, r, i) { var a; for (a = 0; a < i; ++a) { n[r + a] = t[e + a] >> 8; } } function vn() { xr = dn, Ar = pn, _r = gn, Sr = mn; } function bn(n, r, i) { t[n] = function (t, n, a, o, s, u, c, h, l, f, d, p, g, m, v, b, y) { var w, N = y - 1 >> 1, L = s[u + 0] | c[h + 0] << 16, x = l[f + 0] | d[p + 0] << 16; e(null != t); var A = 3 * L + x + 131074 >> 2; for (r(t[n + 0], 255 & A, A >> 16, g, m), null != a && (A = 3 * x + L + 131074 >> 2, r(a[o + 0], 255 & A, A >> 16, v, b)), w = 1; w <= N; ++w) { var _ = s[u + w] | c[h + w] << 16, S = l[f + w] | d[p + w] << 16, P = L + _ + x + S + 524296, k = P + 2 * (_ + x) >> 3; A = k + L >> 1, L = (P = P + 2 * (L + S) >> 3) + _ >> 1, r(t[n + 2 * w - 1], 255 & A, A >> 16, g, m + (2 * w - 1) * i), r(t[n + 2 * w - 0], 255 & L, L >> 16, g, m + (2 * w - 0) * i), null != a && (A = P + x >> 1, L = k + S >> 1, r(a[o + 2 * w - 1], 255 & A, A >> 16, v, b + (2 * w - 1) * i), r(a[o + 2 * w + 0], 255 & L, L >> 16, v, b + (2 * w + 0) * i)), L = _, x = S; } 1 & y || (A = 3 * L + x + 131074 >> 2, r(t[n + y - 1], 255 & A, A >> 16, g, m + (y - 1) * i), null != a && (A = 3 * x + L + 131074 >> 2, r(a[o + y - 1], 255 & A, A >> 16, v, b + (y - 1) * i))); }; } function yn() { vi[Er] = bi, vi[qr] = wi, vi[Rr] = yi, vi[Tr] = Ni, vi[Dr] = Li, vi[Ur] = xi, vi[zr] = Ai, vi[Hr] = wi, vi[Wr] = Ni, vi[Vr] = Li, vi[Gr] = xi; } function wn(t) { return t & ~Ii ? 0 > t ? 0 : 255 : t >> Fi; } function Nn(t, e) { return wn((19077 * t >> 8) + (26149 * e >> 8) - 14234); } function Ln(t, e, n) { return wn((19077 * t >> 8) - (6419 * e >> 8) - (13320 * n >> 8) + 8708); } function xn(t, e) { return wn((19077 * t >> 8) + (33050 * e >> 8) - 17685); } function An(t, e, n, r, i) { r[i + 0] = Nn(t, n), r[i + 1] = Ln(t, e, n), r[i + 2] = xn(t, e); } function _n(t, e, n, r, i) { r[i + 0] = xn(t, e), r[i + 1] = Ln(t, e, n), r[i + 2] = Nn(t, n); } function Sn(t, e, n, r, i) { var a = Ln(t, e, n); e = a << 3 & 224 | xn(t, e) >> 3, r[i + 0] = 248 & Nn(t, n) | a >> 5, r[i + 1] = e; } function Pn(t, e, n, r, i) { var a = 240 & xn(t, e) | 15; r[i + 0] = 240 & Nn(t, n) | Ln(t, e, n) >> 4, r[i + 1] = a; } function kn(t, e, n, r, i) { r[i + 0] = 255, An(t, e, n, r, i + 1); } function Fn(t, e, n, r, i) { _n(t, e, n, r, i), r[i + 3] = 255; } function In(t, e, n, r, i) { An(t, e, n, r, i), r[i + 3] = 255; } function Vt(t, e) { return 0 > t ? 0 : t > e ? e : t; } function Cn(e, n, r) { t[e] = function (t, e, i, a, o, s, u, c, h) { for (var l = c + (-2 & h) * r; c != l;) { n(t[e + 0], i[a + 0], o[s + 0], u, c), n(t[e + 1], i[a + 0], o[s + 0], u, c + r), e += 2, ++a, ++s, c += 2 * r; } 1 & h && n(t[e + 0], i[a + 0], o[s + 0], u, c); }; } function jn(t, e, n) { return 0 == n ? 0 == t ? 0 == e ? 6 : 5 : 0 == e ? 4 : 0 : n; } function Bn(t, e, n, r, i) { switch (t >>> 30) { case 3: or(e, n, r, i, 0); break; case 2: sr(e, n, r, i); break; case 1: cr(e, n, r, i); } } function On(t, e) { var n, a, o = e.M, s = e.Nb, u = t.oc, c = t.pc + 40, h = t.oc, l = t.pc + 584, f = t.oc, d = t.pc + 600; for (n = 0; 16 > n; ++n) { u[c + 32 * n - 1] = 129; } for (n = 0; 8 > n; ++n) { h[l + 32 * n - 1] = 129, f[d + 32 * n - 1] = 129; } for (0 < o ? u[c - 1 - 32] = h[l - 1 - 32] = f[d - 1 - 32] = 129 : (i(u, c - 32 - 1, 127, 21), i(h, l - 32 - 1, 127, 9), i(f, d - 32 - 1, 127, 9)), a = 0; a < t.za; ++a) { var p = e.ya[e.aa + a]; if (0 < a) { for (n = -1; 16 > n; ++n) { r(u, c + 32 * n - 4, u, c + 32 * n + 12, 4); } for (n = -1; 8 > n; ++n) { r(h, l + 32 * n - 4, h, l + 32 * n + 4, 4), r(f, d + 32 * n - 4, f, d + 32 * n + 4, 4); } } var g = t.Gd, m = t.Hd + a, v = p.ad, b = p.Hc; if (0 < o && (r(u, c - 32, g[m].y, 0, 16), r(h, l - 32, g[m].f, 0, 8), r(f, d - 32, g[m].ea, 0, 8)), p.Za) { var y = u, w = c - 32 + 16; for (0 < o && (a >= t.za - 1 ? i(y, w, g[m].y[15], 4) : r(y, w, g[m + 1].y, 0, 4)), n = 0; 4 > n; n++) { y[w + 128 + n] = y[w + 256 + n] = y[w + 384 + n] = y[w + 0 + n]; } for (n = 0; 16 > n; ++n, b <<= 2) { y = u, w = c + Ri[n], fi[p.Ob[n]](y, w), Bn(b, v, 16 * +n, y, w); } } else if (y = jn(a, o, p.Ob[0]), li[y](u, c), 0 != b) for (n = 0; 16 > n; ++n, b <<= 2) { Bn(b, v, 16 * +n, u, c + Ri[n]); } for (n = p.Gc, y = jn(a, o, p.Dd), di[y](h, l), di[y](f, d), b = v, y = h, w = l, 255 & (p = n >> 0) && (170 & p ? ur(b, 256, y, w) : hr(b, 256, y, w)), p = f, b = d, 255 & (n >>= 8) && (170 & n ? ur(v, 320, p, b) : hr(v, 320, p, b)), o < t.Ub - 1 && (r(g[m].y, 0, u, c + 480, 16), r(g[m].f, 0, h, l + 224, 8), r(g[m].ea, 0, f, d + 224, 8)), n = 8 * s * t.B, g = t.sa, m = t.ta + 16 * a + 16 * s * t.R, v = t.qa, p = t.ra + 8 * a + n, b = t.Ha, y = t.Ia + 8 * a + n, n = 0; 16 > n; ++n) { r(g, m + n * t.R, u, c + 32 * n, 16); } for (n = 0; 8 > n; ++n) { r(v, p + n * t.B, h, l + 32 * n, 8), r(b, y + n * t.B, f, d + 32 * n, 8); } } } function Mn(t, r, i, a, o, s, u, c, h) { var l = [0], f = [0], d = 0, p = null != h ? h.kd : 0, g = null != h ? h : new rn(); if (null == t || 12 > i) return 7; g.data = t, g.w = r, g.ha = i, r = [r], i = [i], g.gb = [g.gb]; t: { var m = r, b = i, y = g.gb; if (e(null != t), e(null != b), e(null != y), y[0] = 0, 12 <= b[0] && !n(t, m[0], "RIFF")) { if (n(t, m[0] + 8, "WEBP")) { y = 3; break t; } var w = j(t, m[0] + 4); if (12 > w || 4294967286 < w) { y = 3; break t; } if (p && w > b[0] - 8) { y = 7; break t; } y[0] = w, m[0] += 12, b[0] -= 12; } y = 0; } if (0 != y) return y; for (w = 0 < g.gb[0], i = i[0];;) { t: { var L = t; b = r, y = i; var x = l, A = f, _ = m = [0]; if ((k = d = [d])[0] = 0, 8 > y[0]) y = 7;else { if (!n(L, b[0], "VP8X")) { if (10 != j(L, b[0] + 4)) { y = 3; break t; } if (18 > y[0]) { y = 7; break t; } var S = j(L, b[0] + 8), P = 1 + C(L, b[0] + 12); if (2147483648 <= P * (L = 1 + C(L, b[0] + 15))) { y = 3; break t; } null != _ && (_[0] = S), null != x && (x[0] = P), null != A && (A[0] = L), b[0] += 18, y[0] -= 18, k[0] = 1; } y = 0; } } if (d = d[0], m = m[0], 0 != y) return y; if (b = !!(2 & m), !w && d) return 3; if (null != s && (s[0] = !!(16 & m)), null != u && (u[0] = b), null != c && (c[0] = 0), u = l[0], m = f[0], d && b && null == h) { y = 0; break; } if (4 > i) { y = 7; break; } if (w && d || !w && !d && !n(t, r[0], "ALPH")) { i = [i], g.na = [g.na], g.P = [g.P], g.Sa = [g.Sa]; t: { S = t, y = r, w = i; var k = g.gb; x = g.na, A = g.P, _ = g.Sa; P = 22, e(null != S), e(null != w), L = y[0]; var F = w[0]; for (e(null != x), e(null != _), x[0] = null, A[0] = null, _[0] = 0;;) { if (y[0] = L, w[0] = F, 8 > F) { y = 7; break t; } var I = j(S, L + 4); if (4294967286 < I) { y = 3; break t; } var B = 8 + I + 1 & -2; if (P += B, 0 < k && P > k) { y = 3; break t; } if (!n(S, L, "VP8 ") || !n(S, L, "VP8L")) { y = 0; break t; } if (F[0] < B) { y = 7; break t; } n(S, L, "ALPH") || (x[0] = S, A[0] = L + 8, _[0] = I), L += B, F -= B; } } if (i = i[0], g.na = g.na[0], g.P = g.P[0], g.Sa = g.Sa[0], 0 != y) break; } i = [i], g.Ja = [g.Ja], g.xa = [g.xa]; t: if (k = t, y = r, w = i, x = g.gb[0], A = g.Ja, _ = g.xa, S = y[0], L = !n(k, S, "VP8 "), P = !n(k, S, "VP8L"), e(null != k), e(null != w), e(null != A), e(null != _), 8 > w[0]) y = 7;else { if (L || P) { if (k = j(k, S + 4), 12 <= x && k > x - 12) { y = 3; break t; } if (p && k > w[0] - 8) { y = 7; break t; } A[0] = k, y[0] += 8, w[0] -= 8, _[0] = P; } else _[0] = 5 <= w[0] && 47 == k[S + 0] && !(k[S + 4] >> 5), A[0] = w[0]; y = 0; } if (i = i[0], g.Ja = g.Ja[0], g.xa = g.xa[0], r = r[0], 0 != y) break; if (4294967286 < g.Ja) return 3; if (null == c || b || (c[0] = g.xa ? 2 : 1), u = [u], m = [m], g.xa) { if (5 > i) { y = 7; break; } c = u, p = m, b = s, null == t || 5 > i ? t = 0 : 5 <= i && 47 == t[r + 0] && !(t[r + 4] >> 5) ? (w = [0], k = [0], x = [0], v(A = new N(), t, r, i), gt(A, w, k, x) ? (null != c && (c[0] = w[0]), null != p && (p[0] = k[0]), null != b && (b[0] = x[0]), t = 1) : t = 0) : t = 0; } else { if (10 > i) { y = 7; break; } c = m, null == t || 10 > i || !Xt(t, r + 3, i - 3) ? t = 0 : (p = t[r + 0] | t[r + 1] << 8 | t[r + 2] << 16, b = 16383 & (t[r + 7] << 8 | t[r + 6]), t = 16383 & (t[r + 9] << 8 | t[r + 8]), 1 & p || 3 < (p >> 1 & 7) || !(p >> 4 & 1) || p >> 5 >= g.Ja || !b || !t ? t = 0 : (u && (u[0] = b), c && (c[0] = t), t = 1)); } if (!t) return 3; if (u = u[0], m = m[0], d && (l[0] != u || f[0] != m)) return 3; null != h && (h[0] = g, h.offset = r - h.w, e(4294967286 > r - h.w), e(h.offset == h.ha - i)); break; } return 0 == y || 7 == y && d && null == h ? (null != s && (s[0] |= null != g.na && 0 < g.na.length), null != a && (a[0] = u), null != o && (o[0] = m), 0) : y; } function En(t, e, n) { var r = e.width, i = e.height, a = 0, o = 0, s = r, u = i; if (e.Da = null != t && 0 < t.Da, e.Da && (s = t.cd, u = t.bd, a = t.v, o = t.j, 11 > n || (a &= -2, o &= -2), 0 > a || 0 > o || 0 >= s || 0 >= u || a + s > r || o + u > i)) return 0; if (e.v = a, e.j = o, e.va = a + s, e.o = o + u, e.U = s, e.T = u, e.da = null != t && 0 < t.da, e.da) { if (!E(s, u, n = [t.ib], a = [t.hb])) return 0; e.ib = n[0], e.hb = a[0]; } return e.ob = null != t && t.ob, e.Kb = null == t || !t.Sd, e.da && (e.ob = e.ib < 3 * r / 4 && e.hb < 3 * i / 4, e.Kb = 0), 1; } function qn(t) { if (null == t) return 2; if (11 > t.S) { var e = t.f.RGBA; e.fb += (t.height - 1) * e.A, e.A = -e.A; } else e = t.f.kb, t = t.height, e.O += (t - 1) * e.fa, e.fa = -e.fa, e.N += (t - 1 >> 1) * e.Ab, e.Ab = -e.Ab, e.W += (t - 1 >> 1) * e.Db, e.Db = -e.Db, null != e.F && (e.J += (t - 1) * e.lb, e.lb = -e.lb); return 0; } function Rn(t, e, n, r) { if (null == r || 0 >= t || 0 >= e) return 2; if (null != n) { if (n.Da) { var i = n.cd, o = n.bd, s = -2 & n.v, u = -2 & n.j; if (0 > s || 0 > u || 0 >= i || 0 >= o || s + i > t || u + o > e) return 2; t = i, e = o; } if (n.da) { if (!E(t, e, i = [n.ib], o = [n.hb])) return 2; t = i[0], e = o[0]; } } r.width = t, r.height = e; t: { var c = r.width, h = r.height; if (t = r.S, 0 >= c || 0 >= h || !(t >= Er && 13 > t)) t = 2;else { if (0 >= r.Rd && null == r.sd) { s = o = i = e = 0; var l = (u = c * zi[t]) * h; if (11 > t || (o = (h + 1) / 2 * (e = (c + 1) / 2), 12 == t && (s = (i = c) * h)), null == (h = a(l + 2 * o + s))) { t = 1; break t; } r.sd = h, 11 > t ? ((c = r.f.RGBA).eb = h, c.fb = 0, c.A = u, c.size = l) : ((c = r.f.kb).y = h, c.O = 0, c.fa = u, c.Fd = l, c.f = h, c.N = 0 + l, c.Ab = e, c.Cd = o, c.ea = h, c.W = 0 + l + o, c.Db = e, c.Ed = o, 12 == t && (c.F = h, c.J = 0 + l + 2 * o), c.Tc = s, c.lb = i); } if (e = 1, i = r.S, o = r.width, s = r.height, i >= Er && 13 > i) { if (11 > i) t = r.f.RGBA, e &= (u = Math.abs(t.A)) * (s - 1) + o <= t.size, e &= u >= o * zi[i], e &= null != t.eb;else { t = r.f.kb, u = (o + 1) / 2, l = (s + 1) / 2, c = Math.abs(t.fa); h = Math.abs(t.Ab); var f = Math.abs(t.Db), d = Math.abs(t.lb), p = d * (s - 1) + o; e &= c * (s - 1) + o <= t.Fd, e &= h * (l - 1) + u <= t.Cd, e = (e &= f * (l - 1) + u <= t.Ed) & c >= o & h >= u & f >= u, e &= null != t.y, e &= null != t.f, e &= null != t.ea, 12 == i && (e &= d >= o, e &= p <= t.Tc, e &= null != t.F); } } else e = 0; t = e ? 0 : 2; } } return 0 != t || null != n && n.fd && (t = qn(r)), t; } var Tn = 64, Dn = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215], Un = 24, zn = 32, Hn = 8, Wn = [0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]; T("Predictor0", "PredictorAdd0"), t.Predictor0 = function () { return 4278190080; }, t.Predictor1 = function (t) { return t; }, t.Predictor2 = function (t, e, n) { return e[n + 0]; }, t.Predictor3 = function (t, e, n) { return e[n + 1]; }, t.Predictor4 = function (t, e, n) { return e[n - 1]; }, t.Predictor5 = function (t, e, n) { return U(U(t, e[n + 1]), e[n + 0]); }, t.Predictor6 = function (t, e, n) { return U(t, e[n - 1]); }, t.Predictor7 = function (t, e, n) { return U(t, e[n + 0]); }, t.Predictor8 = function (t, e, n) { return U(e[n - 1], e[n + 0]); }, t.Predictor9 = function (t, e, n) { return U(e[n + 0], e[n + 1]); }, t.Predictor10 = function (t, e, n) { return U(U(t, e[n - 1]), U(e[n + 0], e[n + 1])); }, t.Predictor11 = function (t, e, n) { var r = e[n + 0]; return 0 >= W(r >> 24 & 255, t >> 24 & 255, (e = e[n - 1]) >> 24 & 255) + W(r >> 16 & 255, t >> 16 & 255, e >> 16 & 255) + W(r >> 8 & 255, t >> 8 & 255, e >> 8 & 255) + W(255 & r, 255 & t, 255 & e) ? r : t; }, t.Predictor12 = function (t, e, n) { var r = e[n + 0]; return (z((t >> 24 & 255) + (r >> 24 & 255) - ((e = e[n - 1]) >> 24 & 255)) << 24 | z((t >> 16 & 255) + (r >> 16 & 255) - (e >> 16 & 255)) << 16 | z((t >> 8 & 255) + (r >> 8 & 255) - (e >> 8 & 255)) << 8 | z((255 & t) + (255 & r) - (255 & e))) >>> 0; }, t.Predictor13 = function (t, e, n) { var r = e[n - 1]; return (H((t = U(t, e[n + 0])) >> 24 & 255, r >> 24 & 255) << 24 | H(t >> 16 & 255, r >> 16 & 255) << 16 | H(t >> 8 & 255, r >> 8 & 255) << 8 | H(t >> 0 & 255, r >> 0 & 255)) >>> 0; }; var Vn = t.PredictorAdd0; t.PredictorAdd1 = V, T("Predictor2", "PredictorAdd2"), T("Predictor3", "PredictorAdd3"), T("Predictor4", "PredictorAdd4"), T("Predictor5", "PredictorAdd5"), T("Predictor6", "PredictorAdd6"), T("Predictor7", "PredictorAdd7"), T("Predictor8", "PredictorAdd8"), T("Predictor9", "PredictorAdd9"), T("Predictor10", "PredictorAdd10"), T("Predictor11", "PredictorAdd11"), T("Predictor12", "PredictorAdd12"), T("Predictor13", "PredictorAdd13"); var Gn = t.PredictorAdd2; X("ColorIndexInverseTransform", "MapARGB", "32b", function (t) { return t >> 8 & 255; }, function (t) { return t; }), X("VP8LColorIndexInverseTransformAlpha", "MapAlpha", "8b", function (t) { return t; }, function (t) { return t >> 8 & 255; }); var Yn, Jn = t.ColorIndexInverseTransform, Xn = t.MapARGB, Kn = t.VP8LColorIndexInverseTransformAlpha, Zn = t.MapAlpha, $n = t.VP8LPredictorsAdd = []; $n.length = 16, (t.VP8LPredictors = []).length = 16, (t.VP8LPredictorsAdd_C = []).length = 16, (t.VP8LPredictors_C = []).length = 16; var Qn, tr, er, nr, rr, ir, ar, or, sr, ur, cr, hr, lr, fr, dr, pr, gr, mr, vr, br, yr, wr, Nr, Lr, xr, Ar, _r, Sr, Pr = a(511), kr = a(2041), Fr = a(225), Ir = a(767), Cr = 0, jr = kr, Br = Fr, Or = Ir, Mr = Pr, Er = 0, qr = 1, Rr = 2, Tr = 3, Dr = 4, Ur = 5, zr = 6, Hr = 7, Wr = 8, Vr = 9, Gr = 10, Yr = [2, 3, 7], Jr = [3, 3, 11], Xr = [280, 256, 256, 256, 40], Kr = [0, 1, 1, 1, 0], Zr = [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], $r = [24, 7, 23, 25, 40, 6, 39, 41, 22, 26, 38, 42, 56, 5, 55, 57, 21, 27, 54, 58, 37, 43, 72, 4, 71, 73, 20, 28, 53, 59, 70, 74, 36, 44, 88, 69, 75, 52, 60, 3, 87, 89, 19, 29, 86, 90, 35, 45, 68, 76, 85, 91, 51, 61, 104, 2, 103, 105, 18, 30, 102, 106, 34, 46, 84, 92, 67, 77, 101, 107, 50, 62, 120, 1, 119, 121, 83, 93, 17, 31, 100, 108, 66, 78, 118, 122, 33, 47, 117, 123, 49, 63, 99, 109, 82, 94, 0, 116, 124, 65, 79, 16, 32, 98, 110, 48, 115, 125, 81, 95, 64, 114, 126, 97, 111, 80, 113, 127, 96, 112], Qr = [2954, 2956, 2958, 2962, 2970, 2986, 3018, 3082, 3212, 3468, 3980, 5004], ti = 8, ei = [4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157], ni = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284], ri = null, ii = [[173, 148, 140, 0], [176, 155, 140, 135, 0], [180, 157, 141, 134, 130, 0], [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0]], ai = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15], oi = [-0, 1, -1, 2, -2, 3, 4, 6, -3, 5, -4, -5, -6, 7, -7, 8, -8, -9], si = [[[[128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]], [[253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128], [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128], [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128]], [[1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128], [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128], [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128]], [[1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128], [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128], [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128]], [[1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128], [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128], [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128]], [[1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128], [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128], [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128]], [[1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128], [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128], [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128]], [[1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]]], [[[198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62], [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1], [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128]], [[1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128], [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128], [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128]], [[1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128], [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128], [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128]], [[1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128], [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128], [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128]], [[1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128], [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128], [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128]], [[1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128], [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128], [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128]], [[1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128], [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128], [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128]], [[1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128], [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128], [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128]]], [[[253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128], [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128], [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128]], [[1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128], [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128], [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128]], [[1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128], [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128], [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128]], [[1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128], [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128], [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128]], [[1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128], [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128], [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128]], [[1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128], [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128], [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128]], [[1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128], [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128], [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128]], [[128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]]], [[[202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255], [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128], [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128]], [[1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128], [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128], [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128]], [[1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128], [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128], [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128]], [[1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128], [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128], [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128]], [[1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128], [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128], [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128]], [[1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128], [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128], [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128]], [[1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128], [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128], [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128]], [[1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128]]]], ui = [[[231, 120, 48, 89, 115, 113, 120, 152, 112], [152, 179, 64, 126, 170, 118, 46, 70, 95], [175, 69, 143, 80, 85, 82, 72, 155, 103], [56, 58, 10, 171, 218, 189, 17, 13, 152], [114, 26, 17, 163, 44, 195, 21, 10, 173], [121, 24, 80, 195, 26, 62, 44, 64, 85], [144, 71, 10, 38, 171, 213, 144, 34, 26], [170, 46, 55, 19, 136, 160, 33, 206, 71], [63, 20, 8, 114, 114, 208, 12, 9, 226], [81, 40, 11, 96, 182, 84, 29, 16, 36]], [[134, 183, 89, 137, 98, 101, 106, 165, 148], [72, 187, 100, 130, 157, 111, 32, 75, 80], [66, 102, 167, 99, 74, 62, 40, 234, 128], [41, 53, 9, 178, 241, 141, 26, 8, 107], [74, 43, 26, 146, 73, 166, 49, 23, 157], [65, 38, 105, 160, 51, 52, 31, 115, 128], [104, 79, 12, 27, 217, 255, 87, 17, 7], [87, 68, 71, 44, 114, 51, 15, 186, 23], [47, 41, 14, 110, 182, 183, 21, 17, 194], [66, 45, 25, 102, 197, 189, 23, 18, 22]], [[88, 88, 147, 150, 42, 46, 45, 196, 205], [43, 97, 183, 117, 85, 38, 35, 179, 61], [39, 53, 200, 87, 26, 21, 43, 232, 171], [56, 34, 51, 104, 114, 102, 29, 93, 77], [39, 28, 85, 171, 58, 165, 90, 98, 64], [34, 22, 116, 206, 23, 34, 43, 166, 73], [107, 54, 32, 26, 51, 1, 81, 43, 31], [68, 25, 106, 22, 64, 171, 36, 225, 114], [34, 19, 21, 102, 132, 188, 16, 76, 124], [62, 18, 78, 95, 85, 57, 50, 48, 51]], [[193, 101, 35, 159, 215, 111, 89, 46, 111], [60, 148, 31, 172, 219, 228, 21, 18, 111], [112, 113, 77, 85, 179, 255, 38, 120, 114], [40, 42, 1, 196, 245, 209, 10, 25, 109], [88, 43, 29, 140, 166, 213, 37, 43, 154], [61, 63, 30, 155, 67, 45, 68, 1, 209], [100, 80, 8, 43, 154, 1, 51, 26, 71], [142, 78, 78, 16, 255, 128, 34, 197, 171], [41, 40, 5, 102, 211, 183, 4, 1, 221], [51, 50, 17, 168, 209, 192, 23, 25, 82]], [[138, 31, 36, 171, 27, 166, 38, 44, 229], [67, 87, 58, 169, 82, 115, 26, 59, 179], [63, 59, 90, 180, 59, 166, 93, 73, 154], [40, 40, 21, 116, 143, 209, 34, 39, 175], [47, 15, 16, 183, 34, 223, 49, 45, 183], [46, 17, 33, 183, 6, 98, 15, 32, 183], [57, 46, 22, 24, 128, 1, 54, 17, 37], [65, 32, 73, 115, 28, 128, 23, 128, 205], [40, 3, 9, 115, 51, 192, 18, 6, 223], [87, 37, 9, 115, 59, 77, 64, 21, 47]], [[104, 55, 44, 218, 9, 54, 53, 130, 226], [64, 90, 70, 205, 40, 41, 23, 26, 57], [54, 57, 112, 184, 5, 41, 38, 166, 213], [30, 34, 26, 133, 152, 116, 10, 32, 134], [39, 19, 53, 221, 26, 114, 32, 73, 255], [31, 9, 65, 234, 2, 15, 1, 118, 73], [75, 32, 12, 51, 192, 255, 160, 43, 51], [88, 31, 35, 67, 102, 85, 55, 186, 85], [56, 21, 23, 111, 59, 205, 45, 37, 192], [55, 38, 70, 124, 73, 102, 1, 34, 98]], [[125, 98, 42, 88, 104, 85, 117, 175, 82], [95, 84, 53, 89, 128, 100, 113, 101, 45], [75, 79, 123, 47, 51, 128, 81, 171, 1], [57, 17, 5, 71, 102, 57, 53, 41, 49], [38, 33, 13, 121, 57, 73, 26, 1, 85], [41, 10, 67, 138, 77, 110, 90, 47, 114], [115, 21, 2, 10, 102, 255, 166, 23, 6], [101, 29, 16, 10, 85, 128, 101, 196, 26], [57, 18, 10, 102, 102, 213, 34, 20, 43], [117, 20, 15, 36, 163, 128, 68, 1, 26]], [[102, 61, 71, 37, 34, 53, 31, 243, 192], [69, 60, 71, 38, 73, 119, 28, 222, 37], [68, 45, 128, 34, 1, 47, 11, 245, 171], [62, 17, 19, 70, 146, 85, 55, 62, 70], [37, 43, 37, 154, 100, 163, 85, 160, 1], [63, 9, 92, 136, 28, 64, 32, 201, 85], [75, 15, 9, 9, 64, 255, 184, 119, 16], [86, 6, 28, 5, 64, 255, 25, 248, 1], [56, 8, 17, 132, 137, 255, 55, 116, 128], [58, 15, 20, 82, 135, 57, 26, 121, 40]], [[164, 50, 31, 137, 154, 133, 25, 35, 218], [51, 103, 44, 131, 131, 123, 31, 6, 158], [86, 40, 64, 135, 148, 224, 45, 183, 128], [22, 26, 17, 131, 240, 154, 14, 1, 209], [45, 16, 21, 91, 64, 222, 7, 1, 197], [56, 21, 39, 155, 60, 138, 23, 102, 213], [83, 12, 13, 54, 192, 255, 68, 47, 28], [85, 26, 85, 85, 128, 128, 32, 146, 171], [18, 11, 7, 63, 144, 171, 4, 4, 246], [35, 27, 10, 146, 174, 171, 12, 26, 128]], [[190, 80, 35, 99, 180, 80, 126, 54, 45], [85, 126, 47, 87, 176, 51, 41, 20, 32], [101, 75, 128, 139, 118, 146, 116, 128, 85], [56, 41, 15, 176, 236, 85, 37, 9, 62], [71, 30, 17, 119, 118, 255, 17, 18, 138], [101, 38, 60, 138, 55, 70, 43, 26, 142], [146, 36, 19, 30, 171, 255, 97, 27, 20], [138, 45, 61, 62, 219, 1, 81, 188, 64], [32, 41, 20, 117, 151, 142, 20, 21, 163], [112, 19, 12, 61, 195, 128, 48, 4, 24]]], ci = [[[[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255], [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255], [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255], [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255], [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255], [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255], [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]]], [[[217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255], [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255]], [[255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255]], [[255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255], [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]]], [[[186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255], [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255], [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255]], [[255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255]], [[255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]]], [[[248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255], [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255]], [[255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255]], [[255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255], [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255]], [[255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255], [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255], [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255], [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]], [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]]]], hi = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0], li = [], fi = [], di = [], pi = 1, gi = 2, mi = [], vi = []; bn("UpsampleRgbLinePair", An, 3), bn("UpsampleBgrLinePair", _n, 3), bn("UpsampleRgbaLinePair", In, 4), bn("UpsampleBgraLinePair", Fn, 4), bn("UpsampleArgbLinePair", kn, 4), bn("UpsampleRgba4444LinePair", Pn, 2), bn("UpsampleRgb565LinePair", Sn, 2); var bi = t.UpsampleRgbLinePair, yi = t.UpsampleBgrLinePair, wi = t.UpsampleRgbaLinePair, Ni = t.UpsampleBgraLinePair, Li = t.UpsampleArgbLinePair, xi = t.UpsampleRgba4444LinePair, Ai = t.UpsampleRgb565LinePair, _i = 16, Si = 1 << _i - 1, Pi = -227, ki = 482, Fi = 6, Ii = (256 << Fi) - 1, Ci = 0, ji = a(256), Bi = a(256), Oi = a(256), Mi = a(256), Ei = a(ki - Pi), qi = a(ki - Pi); Cn("YuvToRgbRow", An, 3), Cn("YuvToBgrRow", _n, 3), Cn("YuvToRgbaRow", In, 4), Cn("YuvToBgraRow", Fn, 4), Cn("YuvToArgbRow", kn, 4), Cn("YuvToRgba4444Row", Pn, 2), Cn("YuvToRgb565Row", Sn, 2); var Ri = [0, 4, 8, 12, 128, 132, 136, 140, 256, 260, 264, 268, 384, 388, 392, 396], Ti = [0, 2, 8], Di = [8, 7, 6, 4, 4, 2, 2, 2, 1, 1, 1, 1], Ui = 1; this.WebPDecodeRGBA = function (t, n, r, i, a) { var o = qr, s = new nn(), u = new ot(); s.ba = u, u.S = o, u.width = [u.width], u.height = [u.height]; var c = u.width, h = u.height, l = new st(); if (null == l || null == t) var f = 2;else e(null != l), f = Mn(t, n, r, l.width, l.height, l.Pd, l.Qd, l.format, null); if (0 != f ? c = 0 : (null != c && (c[0] = l.width[0]), null != h && (h[0] = l.height[0]), c = 1), c) { u.width = u.width[0], u.height = u.height[0], null != i && (i[0] = u.width), null != a && (a[0] = u.height); t: { if (i = new Gt(), (a = new rn()).data = t, a.w = n, a.ha = r, a.kd = 1, n = [0], e(null != a), (0 == (t = Mn(a.data, a.w, a.ha, null, null, null, n, null, a)) || 7 == t) && n[0] && (t = 4), 0 == (n = t)) { if (e(null != s), i.data = a.data, i.w = a.w + a.offset, i.ha = a.ha - a.offset, i.put = dt, i.ac = ft, i.bc = pt, i.ma = s, a.xa) { if (null == (t = kt())) { s = 1; break t; } if (function (t, n) { var r = [0], i = [0], a = [0]; e: for (;;) { if (null == t) return 0; if (null == n) return t.a = 2, 0; if (t.l = n, t.a = 0, v(t.m, n.data, n.w, n.ha), !gt(t.m, r, i, a)) { t.a = 3; break e; } if (t.xb = gi, n.width = r[0], n.height = i[0], !Ft(r[0], i[0], 1, t, null)) break e; return 1; } return e(0 != t.a), 0; }(t, i)) { if (i = 0 == (n = Rn(i.width, i.height, s.Oa, s.ba))) { e: { i = t; n: for (;;) { if (null == i) { i = 0; break e; } if (e(null != i.s.yc), e(null != i.s.Ya), e(0 < i.s.Wb), e(null != (r = i.l)), e(null != (a = r.ma)), 0 != i.xb) { if (i.ca = a.ba, i.tb = a.tb, e(null != i.ca), !En(a.Oa, r, Tr)) { i.a = 2; break n; } if (!It(i, r.width)) break n; if (r.da) break n; if ((r.da || rt(i.ca.S)) && vn(), 11 > i.ca.S || (alert("todo:WebPInitConvertARGBToYUV"), null != i.ca.f.kb.F && vn()), i.Pb && 0 < i.s.ua && null == i.s.vb.X && !B(i.s.vb, i.s.Wa.Xa)) { i.a = 1; break n; } i.xb = 0; } if (!St(i, i.V, i.Ba, i.c, i.i, r.o, Lt)) break n; a.Dc = i.Ma, i = 1; break e; } e(0 != i.a), i = 0; } i = !i; } i && (n = t.a); } else n = t.a; } else { if (null == (t = new Yt())) { s = 1; break t; } if (t.Fa = a.na, t.P = a.P, t.qc = a.Sa, Kt(t, i)) { if (0 == (n = Rn(i.width, i.height, s.Oa, s.ba))) { if (t.Aa = 0, r = s.Oa, e(null != (a = t)), null != r) { if (0 < (c = 0 > (c = r.Md) ? 0 : 100 < c ? 255 : 255 * c / 100)) { for (h = l = 0; 4 > h; ++h) { 12 > (f = a.pb[h]).lc && (f.ia = c * Di[0 > f.lc ? 0 : f.lc] >> 3), l |= f.ia; } l && (alert("todo:VP8InitRandom"), a.ia = 1); } a.Ga = r.Id, 100 < a.Ga ? a.Ga = 100 : 0 > a.Ga && (a.Ga = 0); } Qt(t, i) || (n = t.a); } } else n = t.a; } 0 == n && null != s.Oa && s.Oa.fd && (n = qn(s.ba)); } s = n; } o = 0 != s ? null : 11 > o ? u.f.RGBA.eb : u.f.kb.y; } else o = null; return o; }; var zi = [3, 4, 3, 4, 4, 2, 2, 4, 4, 4, 2, 1, 1]; })(); var l = [0], f = [0], d = [], p = new Et(), g = t, m = function (t, e) { var n = {}, r = 0, i = !1, a = 0, o = 0; if (n.frames = [], ! /** @license * Copyright (c) 2017 Dominik Homberger 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. https://webpjs.appspot.com WebPRiffParser dominikhlbg@gmail.com */ function (t, e, n, r) { for (var i = 0; i < r; i++) { if (t[e + i] != n.charCodeAt(i)) return !0; } return !1; }(t, e, "RIFF", 4)) { var s, l; h(t, e += 4); for (e += 8; e < t.length;) { var f = u(t, e), d = h(t, e += 4); e += 4; var p = d + (1 & d); switch (f) { case "VP8 ": case "VP8L": void 0 === n.frames[r] && (n.frames[r] = {}); (v = n.frames[r]).src_off = i ? o : e - 8, v.src_size = a + d + 8, r++, i && (i = !1, a = 0, o = 0); break; case "VP8X": (v = n.header = {}).feature_flags = t[e]; var g = e + 4; v.canvas_width = 1 + c(t, g); g += 3; v.canvas_height = 1 + c(t, g); g += 3; break; case "ALPH": i = !0, a = p + 8, o = e - 8; break; case "ANIM": (v = n.header).bgcolor = h(t, e); g = e + 4; v.loop_count = (s = t)[(l = g) + 0] << 0 | s[l + 1] << 8; g += 2; break; case "ANMF": var m, v; (v = n.frames[r] = {}).offset_x = 2 * c(t, e), e += 3, v.offset_y = 2 * c(t, e), e += 3, v.width = 1 + c(t, e), e += 3, v.height = 1 + c(t, e), e += 3, v.duration = c(t, e), e += 3, m = t[e++], v.dispose = 1 & m, v.blend = m >> 1 & 1; } "ANMF" != f && (e += p); } return n; } }(g, 0); m.response = g, m.rgbaoutput = !0, m.dataurl = !1; var v = m.header ? m.header : null, b = m.frames ? m.frames : null; if (v) { v.loop_counter = v.loop_count, l = [v.canvas_height], f = [v.canvas_width]; for (var y = 0; y < b.length && 0 != b[y].blend; y++) { } } var w = b[0], N = p.WebPDecodeRGBA(g, w.src_off, w.src_size, f, l); w.rgba = N, w.imgwidth = f[0], w.imgheight = l[0]; for (var L = 0; L < f[0] * l[0] * 4; L++) { d[L] = N[L]; } return this.width = f, this.height = l, this.data = d, this; } /** * @license * * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ==================================================================== */ !function (t) { var e = function e() { return !0; }, n = function n(e, _n2, a, h) { var l = 5, f = s; switch (h) { case t.image_compression.FAST: l = 3, f = o; break; case t.image_compression.MEDIUM: l = 6, f = u; break; case t.image_compression.SLOW: l = 9, f = c; } e = i(e, _n2, a, f); var d = new Uint8Array(r(l)), p = g.API.adler32cs.fromBuffer(e.buffer), m = new xt(l), v = m.append(e), b = m.flush(), y = d.length + v.length + b.length, w = new Uint8Array(y + 4); return w.set(d), w.set(v, d.length), w.set(b, d.length + v.length), w[y++] = p >>> 24 & 255, w[y++] = p >>> 16 & 255, w[y++] = p >>> 8 & 255, w[y++] = 255 & p, t.__addimage__.arrayBufferToBinaryString(w); }, r = function r(t) { var e = 30720; return e |= Math.min(3, (t - 1 & 255) >> 1) << 6, e |= 0, [120, 255 & (e += 31 - e % 31)]; }, i = function i(t, e, n, r) { for (var i, a, o, s = t.length / e, u = new Uint8Array(t.length + s), c = l(), h = 0; h < s; h += 1) { if (o = h * e, i = t.subarray(o, o + e), r) u.set(r(i, n, a), o + h);else { for (var d, p = c.length, g = []; d < p; d += 1) { g[d] = c[d](i, n, a); } var m = f(g.concat()); u.set(g[m], o + h); } a = i; } return u; }, a = function a(t) { var e = Array.apply([], t); return e.unshift(0), e; }, o = function o(t, e) { var n, r = [], i = t.length; r[0] = 1; for (var a = 0; a < i; a += 1) { n = t[a - e] || 0, r[a + 1] = t[a] - n + 256 & 255; } return r; }, s = function s(t, e, n) { var r, i = [], a = t.length; i[0] = 2; for (var o = 0; o < a; o += 1) { r = n && n[o] || 0, i[o + 1] = t[o] - r + 256 & 255; } return i; }, u = function u(t, e, n) { var r, i, a = [], o = t.length; a[0] = 3; for (var s = 0; s < o; s += 1) { r = t[s - e] || 0, i = n && n[s] || 0, a[s + 1] = t[s] + 256 - (r + i >>> 1) & 255; } return a; }, c = function c(t, e, n) { var r, i, a, o, s = [], u = t.length; s[0] = 4; for (var c = 0; c < u; c += 1) { r = t[c - e] || 0, i = n && n[c] || 0, a = n && n[c - e] || 0, o = h(r, i, a), s[c + 1] = t[c] - o + 256 & 255; } return s; }, h = function h(t, e, n) { if (t === e && e === n) return t; var r = Math.abs(e - n), i = Math.abs(t - n), a = Math.abs(t + e - n - n); return r <= i && r <= a ? t : i <= a ? e : n; }, l = function l() { return [a, o, s, u, c]; }, f = function f(t) { var e = t.map(function (t) { return t.reduce(function (t, e) { return t + Math.abs(e); }, 0); }); return e.indexOf(Math.min.apply(null, e)); }; t.processPNG = function (r, i, a, o) { var s, u, c, h, l, f, d, p, g, m, v, b, y, w, N, L = this.decode.FLATE_DECODE, x = ""; if (this.__addimage__.isArrayBuffer(r) && (r = new Uint8Array(r)), this.__addimage__.isArrayBufferView(r)) { if (r = (c = new Ct(r)).imgData, u = c.bits, s = c.colorSpace, l = c.colors, -1 !== [4, 6].indexOf(c.colorType)) { if (8 === c.bits) { g = (p = 32 == c.pixelBitlength ? new Uint32Array(c.decodePixels().buffer) : 16 == c.pixelBitlength ? new Uint16Array(c.decodePixels().buffer) : new Uint8Array(c.decodePixels().buffer)).length, v = new Uint8Array(g * c.colors), m = new Uint8Array(g); var A, _ = c.pixelBitlength - c.bits; for (w = 0, N = 0; w < g; w++) { for (y = p[w], A = 0; A < _;) { v[N++] = y >>> A & 255, A += c.bits; } m[w] = y >>> A & 255; } } if (16 === c.bits) { g = (p = new Uint32Array(c.decodePixels().buffer)).length, v = new Uint8Array(g * (32 / c.pixelBitlength) * c.colors), m = new Uint8Array(g * (32 / c.pixelBitlength)), b = c.colors > 1, w = 0, N = 0; for (var S = 0; w < g;) { y = p[w++], v[N++] = y >>> 0 & 255, b && (v[N++] = y >>> 16 & 255, y = p[w++], v[N++] = y >>> 0 & 255), m[S++] = y >>> 16 & 255; } u = 8; } o !== t.image_compression.NONE && e() ? (r = n(v, c.width * c.colors, c.colors, o), d = n(m, c.width, 1, o)) : (r = v, d = m, L = void 0); } if (3 === c.colorType && (s = this.color_spaces.INDEXED, f = c.palette, c.transparency.indexed)) { var P = c.transparency.indexed, k = 0; for (w = 0, g = P.length; w < g; ++w) { k += P[w]; } if ((k /= 255) === g - 1 && -1 !== P.indexOf(0)) h = [P.indexOf(0)];else if (k !== g) { for (p = c.decodePixels(), m = new Uint8Array(p.length), w = 0, g = p.length; w < g; w++) { m[w] = P[p[w]]; } d = n(m, c.width, 1); } } var F = function (e) { var n; switch (e) { case t.image_compression.FAST: n = 11; break; case t.image_compression.MEDIUM: n = 13; break; case t.image_compression.SLOW: n = 14; break; default: n = 12; } return n; }(o); return L === this.decode.FLATE_DECODE && (x = "/Predictor " + F + " "), x += "/Colors " + l + " /BitsPerComponent " + u + " /Columns " + c.width, (this.__addimage__.isArrayBuffer(r) || this.__addimage__.isArrayBufferView(r)) && (r = this.__addimage__.arrayBufferToBinaryString(r)), (d && this.__addimage__.isArrayBuffer(d) || this.__addimage__.isArrayBufferView(d)) && (d = this.__addimage__.arrayBufferToBinaryString(d)), { alias: a, data: r, index: i, filter: L, decodeParameters: x, transparency: h, palette: f, sMask: d, predictor: F, width: c.width, height: c.height, bitsPerComponent: u, colorSpace: s }; } }; }(g.API), function (t) { t.processGIF89A = function (e, n, r, i) { var a = new jt(e), o = a.width, s = a.height, u = []; a.decodeAndBlitFrameRGBA(0, u); var c = { data: u, width: o, height: s }, h = new Ot(100).encode(c, 100); return t.processJPEG.call(this, h, n, r, i); }, t.processGIF87A = t.processGIF89A; }(g.API), Mt.prototype.parseHeader = function () { if (this.fileSize = this.datav.getUint32(this.pos, !0), this.pos += 4, this.reserved = this.datav.getUint32(this.pos, !0), this.pos += 4, this.offset = this.datav.getUint32(this.pos, !0), this.pos += 4, this.headerSize = this.datav.getUint32(this.pos, !0), this.pos += 4, this.width = this.datav.getUint32(this.pos, !0), this.pos += 4, this.height = this.datav.getInt32(this.pos, !0), this.pos += 4, this.planes = this.datav.getUint16(this.pos, !0), this.pos += 2, this.bitPP = this.datav.getUint16(this.pos, !0), this.pos += 2, this.compress = this.datav.getUint32(this.pos, !0), this.pos += 4, this.rawSize = this.datav.getUint32(this.pos, !0), this.pos += 4, this.hr = this.datav.getUint32(this.pos, !0), this.pos += 4, this.vr = this.datav.getUint32(this.pos, !0), this.pos += 4, this.colors = this.datav.getUint32(this.pos, !0), this.pos += 4, this.importantColors = this.datav.getUint32(this.pos, !0), this.pos += 4, 16 === this.bitPP && this.is_with_alpha && (this.bitPP = 15), this.bitPP < 15) { var t = 0 === this.colors ? 1 << this.bitPP : this.colors; this.palette = new Array(t); for (var e = 0; e < t; e++) { var n = this.datav.getUint8(this.pos++, !0), r = this.datav.getUint8(this.pos++, !0), i = this.datav.getUint8(this.pos++, !0), a = this.datav.getUint8(this.pos++, !0); this.palette[e] = { red: i, green: r, blue: n, quad: a }; } } this.height < 0 && (this.height *= -1, this.bottom_up = !1); }, Mt.prototype.parseBGR = function () { this.pos = this.offset; try { var t = "bit" + this.bitPP, e = this.width * this.height * 4; this.data = new Uint8Array(e), this[t](); } catch (t) { n.log("bit decode error:" + t); } }, Mt.prototype.bit1 = function () { var t, e = Math.ceil(this.width / 8), n = e % 4; for (t = this.height - 1; t >= 0; t--) { for (var r = this.bottom_up ? t : this.height - 1 - t, i = 0; i < e; i++) { for (var a = this.datav.getUint8(this.pos++, !0), o = r * this.width * 4 + 8 * i * 4, s = 0; s < 8 && 8 * i + s < this.width; s++) { var u = this.palette[a >> 7 - s & 1]; this.data[o + 4 * s] = u.blue, this.data[o + 4 * s + 1] = u.green, this.data[o + 4 * s + 2] = u.red, this.data[o + 4 * s + 3] = 255; } } 0 !== n && (this.pos += 4 - n); } }, Mt.prototype.bit4 = function () { for (var t = Math.ceil(this.width / 2), e = t % 4, n = this.height - 1; n >= 0; n--) { for (var r = this.bottom_up ? n : this.height - 1 - n, i = 0; i < t; i++) { var a = this.datav.getUint8(this.pos++, !0), o = r * this.width * 4 + 2 * i * 4, s = a >> 4, u = 15 & a, c = this.palette[s]; if (this.data[o] = c.blue, this.data[o + 1] = c.green, this.data[o + 2] = c.red, this.data[o + 3] = 255, 2 * i + 1 >= this.width) break; c = this.palette[u], this.data[o + 4] = c.blue, this.data[o + 4 + 1] = c.green, this.data[o + 4 + 2] = c.red, this.data[o + 4 + 3] = 255; } 0 !== e && (this.pos += 4 - e); } }, Mt.prototype.bit8 = function () { for (var t = this.width % 4, e = this.height - 1; e >= 0; e--) { for (var n = this.bottom_up ? e : this.height - 1 - e, r = 0; r < this.width; r++) { var i = this.datav.getUint8(this.pos++, !0), a = n * this.width * 4 + 4 * r; if (i < this.palette.length) { var o = this.palette[i]; this.data[a] = o.red, this.data[a + 1] = o.green, this.data[a + 2] = o.blue, this.data[a + 3] = 255; } else this.data[a] = 255, this.data[a + 1] = 255, this.data[a + 2] = 255, this.data[a + 3] = 255; } 0 !== t && (this.pos += 4 - t); } }, Mt.prototype.bit15 = function () { for (var t = this.width % 3, e = parseInt("11111", 2), n = this.height - 1; n >= 0; n--) { for (var r = this.bottom_up ? n : this.height - 1 - n, i = 0; i < this.width; i++) { var a = this.datav.getUint16(this.pos, !0); this.pos += 2; var o = (a & e) / e * 255 | 0, s = (a >> 5 & e) / e * 255 | 0, u = (a >> 10 & e) / e * 255 | 0, c = a >> 15 ? 255 : 0, h = r * this.width * 4 + 4 * i; this.data[h] = u, this.data[h + 1] = s, this.data[h + 2] = o, this.data[h + 3] = c; } this.pos += t; } }, Mt.prototype.bit16 = function () { for (var t = this.width % 3, e = parseInt("11111", 2), n = parseInt("111111", 2), r = this.height - 1; r >= 0; r--) { for (var i = this.bottom_up ? r : this.height - 1 - r, a = 0; a < this.width; a++) { var o = this.datav.getUint16(this.pos, !0); this.pos += 2; var s = (o & e) / e * 255 | 0, u = (o >> 5 & n) / n * 255 | 0, c = (o >> 11) / e * 255 | 0, h = i * this.width * 4 + 4 * a; this.data[h] = c, this.data[h + 1] = u, this.data[h + 2] = s, this.data[h + 3] = 255; } this.pos += t; } }, Mt.prototype.bit24 = function () { for (var t = this.height - 1; t >= 0; t--) { for (var e = this.bottom_up ? t : this.height - 1 - t, n = 0; n < this.width; n++) { var r = this.datav.getUint8(this.pos++, !0), i = this.datav.getUint8(this.pos++, !0), a = this.datav.getUint8(this.pos++, !0), o = e * this.width * 4 + 4 * n; this.data[o] = a, this.data[o + 1] = i, this.data[o + 2] = r, this.data[o + 3] = 255; } this.pos += this.width % 4; } }, Mt.prototype.bit32 = function () { for (var t = this.height - 1; t >= 0; t--) { for (var e = this.bottom_up ? t : this.height - 1 - t, n = 0; n < this.width; n++) { var r = this.datav.getUint8(this.pos++, !0), i = this.datav.getUint8(this.pos++, !0), a = this.datav.getUint8(this.pos++, !0), o = this.datav.getUint8(this.pos++, !0), s = e * this.width * 4 + 4 * n; this.data[s] = a, this.data[s + 1] = i, this.data[s + 2] = r, this.data[s + 3] = o; } } }, Mt.prototype.getData = function () { return this.data; }, /** * @license * Copyright (c) 2018 Aras Abbasi * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { t.processBMP = function (e, n, r, i) { var a = new Mt(e, !1), o = a.width, s = a.height, u = { data: a.getData(), width: o, height: s }, c = new Ot(100).encode(u, 100); return t.processJPEG.call(this, c, n, r, i); }; }(g.API), Et.prototype.getData = function () { return this.data; }, /** * @license * Copyright (c) 2019 Aras Abbasi * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { t.processWEBP = function (e, n, r, i) { var a = new Et(e, !1), o = a.width, s = a.height, u = { data: a.getData(), width: o, height: s }, c = new Ot(100).encode(u, 100); return t.processJPEG.call(this, c, n, r, i); }; }(g.API), g.API.setLanguage = function (t) { return void 0 === this.internal.languageSettings && (this.internal.languageSettings = {}, this.internal.languageSettings.isSubscribed = !1), void 0 !== { af: "Afrikaans", sq: "Albanian", ar: "Arabic (Standard)", "ar-DZ": "Arabic (Algeria)", "ar-BH": "Arabic (Bahrain)", "ar-EG": "Arabic (Egypt)", "ar-IQ": "Arabic (Iraq)", "ar-JO": "Arabic (Jordan)", "ar-KW": "Arabic (Kuwait)", "ar-LB": "Arabic (Lebanon)", "ar-LY": "Arabic (Libya)", "ar-MA": "Arabic (Morocco)", "ar-OM": "Arabic (Oman)", "ar-QA": "Arabic (Qatar)", "ar-SA": "Arabic (Saudi Arabia)", "ar-SY": "Arabic (Syria)", "ar-TN": "Arabic (Tunisia)", "ar-AE": "Arabic (U.A.E.)", "ar-YE": "Arabic (Yemen)", an: "Aragonese", hy: "Armenian", as: "Assamese", ast: "Asturian", az: "Azerbaijani", eu: "Basque", be: "Belarusian", bn: "Bengali", bs: "Bosnian", br: "Breton", bg: "Bulgarian", my: "Burmese", ca: "Catalan", ch: "Chamorro", ce: "Chechen", zh: "Chinese", "zh-HK": "Chinese (Hong Kong)", "zh-CN": "Chinese (PRC)", "zh-SG": "Chinese (Singapore)", "zh-TW": "Chinese (Taiwan)", cv: "Chuvash", co: "Corsican", cr: "Cree", hr: "Croatian", cs: "Czech", da: "Danish", nl: "Dutch (Standard)", "nl-BE": "Dutch (Belgian)", en: "English", "en-AU": "English (Australia)", "en-BZ": "English (Belize)", "en-CA": "English (Canada)", "en-IE": "English (Ireland)", "en-JM": "English (Jamaica)", "en-NZ": "English (New Zealand)", "en-PH": "English (Philippines)", "en-ZA": "English (South Africa)", "en-TT": "English (Trinidad & Tobago)", "en-GB": "English (United Kingdom)", "en-US": "English (United States)", "en-ZW": "English (Zimbabwe)", eo: "Esperanto", et: "Estonian", fo: "Faeroese", fj: "Fijian", fi: "Finnish", fr: "French (Standard)", "fr-BE": "French (Belgium)", "fr-CA": "French (Canada)", "fr-FR": "French (France)", "fr-LU": "French (Luxembourg)", "fr-MC": "French (Monaco)", "fr-CH": "French (Switzerland)", fy: "Frisian", fur: "Friulian", gd: "Gaelic (Scots)", "gd-IE": "Gaelic (Irish)", gl: "Galacian", ka: "Georgian", de: "German (Standard)", "de-AT": "German (Austria)", "de-DE": "German (Germany)", "de-LI": "German (Liechtenstein)", "de-LU": "German (Luxembourg)", "de-CH": "German (Switzerland)", el: "Greek", gu: "Gujurati", ht: "Haitian", he: "Hebrew", hi: "Hindi", hu: "Hungarian", is: "Icelandic", id: "Indonesian", iu: "Inuktitut", ga: "Irish", it: "Italian (Standard)", "it-CH": "Italian (Switzerland)", ja: "Japanese", kn: "Kannada", ks: "Kashmiri", kk: "Kazakh", km: "Khmer", ky: "Kirghiz", tlh: "Klingon", ko: "Korean", "ko-KP": "Korean (North Korea)", "ko-KR": "Korean (South Korea)", la: "Latin", lv: "Latvian", lt: "Lithuanian", lb: "Luxembourgish", mk: "FYRO Macedonian", ms: "Malay", ml: "Malayalam", mt: "Maltese", mi: "Maori", mr: "Marathi", mo: "Moldavian", nv: "Navajo", ng: "Ndonga", ne: "Nepali", no: "Norwegian", nb: "Norwegian (Bokmal)", nn: "Norwegian (Nynorsk)", oc: "Occitan", or: "Oriya", om: "Oromo", fa: "Persian", "fa-IR": "Persian/Iran", pl: "Polish", pt: "Portuguese", "pt-BR": "Portuguese (Brazil)", pa: "Punjabi", "pa-IN": "Punjabi (India)", "pa-PK": "Punjabi (Pakistan)", qu: "Quechua", rm: "Rhaeto-Romanic", ro: "Romanian", "ro-MO": "Romanian (Moldavia)", ru: "Russian", "ru-MO": "Russian (Moldavia)", sz: "Sami (Lappish)", sg: "Sango", sa: "Sanskrit", sc: "Sardinian", sd: "Sindhi", si: "Singhalese", sr: "Serbian", sk: "Slovak", sl: "Slovenian", so: "Somani", sb: "Sorbian", es: "Spanish", "es-AR": "Spanish (Argentina)", "es-BO": "Spanish (Bolivia)", "es-CL": "Spanish (Chile)", "es-CO": "Spanish (Colombia)", "es-CR": "Spanish (Costa Rica)", "es-DO": "Spanish (Dominican Republic)", "es-EC": "Spanish (Ecuador)", "es-SV": "Spanish (El Salvador)", "es-GT": "Spanish (Guatemala)", "es-HN": "Spanish (Honduras)", "es-MX": "Spanish (Mexico)", "es-NI": "Spanish (Nicaragua)", "es-PA": "Spanish (Panama)", "es-PY": "Spanish (Paraguay)", "es-PE": "Spanish (Peru)", "es-PR": "Spanish (Puerto Rico)", "es-ES": "Spanish (Spain)", "es-UY": "Spanish (Uruguay)", "es-VE": "Spanish (Venezuela)", sx: "Sutu", sw: "Swahili", sv: "Swedish", "sv-FI": "Swedish (Finland)", "sv-SV": "Swedish (Sweden)", ta: "Tamil", tt: "Tatar", te: "Teluga", th: "Thai", tig: "Tigre", ts: "Tsonga", tn: "Tswana", tr: "Turkish", tk: "Turkmen", uk: "Ukrainian", hsb: "Upper Sorbian", ur: "Urdu", ve: "Venda", vi: "Vietnamese", vo: "Volapuk", wa: "Walloon", cy: "Welsh", xh: "Xhosa", ji: "Yiddish", zu: "Zulu" }[t] && (this.internal.languageSettings.languageCode = t, !1 === this.internal.languageSettings.isSubscribed && (this.internal.events.subscribe("putCatalog", function () { this.internal.write("/Lang (" + this.internal.languageSettings.languageCode + ")"); }), this.internal.languageSettings.isSubscribed = !0)), this; }, /** @license * MIT license. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com * 2014 Diego Casorran, https://github.com/diegocr * * 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. * ==================================================================== */ At = g.API, _t = At.getCharWidthsArray = function (t, e) { var n, r, i = (e = e || {}).font || this.internal.getFont(), a = e.fontSize || this.internal.getFontSize(), o = e.charSpace || this.internal.getCharSpace(), s = e.widths ? e.widths : i.metadata.Unicode.widths, u = s.fof ? s.fof : 1, c = e.kerning ? e.kerning : i.metadata.Unicode.kerning, h = c.fof ? c.fof : 1, l = !1 !== e.doKerning, f = 0, d = t.length, p = 0, g = s[0] || u, m = []; for (n = 0; n < d; n++) { r = t.charCodeAt(n), "function" == typeof i.metadata.widthOfString ? m.push((i.metadata.widthOfGlyph(i.metadata.characterToGlyph(r)) + o * (1e3 / a) || 0) / 1e3) : (f = l && "object" == _typeof(c[r]) && !isNaN(parseInt(c[r][p], 10)) ? c[r][p] / h : 0, m.push((s[r] || g) / u + f)), p = r; } return m; }, St = At.getStringUnitWidth = function (t, e) { var n = (e = e || {}).fontSize || this.internal.getFontSize(), r = e.font || this.internal.getFont(), i = e.charSpace || this.internal.getCharSpace(); return At.processArabic && (t = At.processArabic(t)), "function" == typeof r.metadata.widthOfString ? r.metadata.widthOfString(t, n, i) / n : _t.apply(this, arguments).reduce(function (t, e) { return t + e; }, 0); }, Pt = function Pt(t, e, n, r) { for (var i = [], a = 0, o = t.length, s = 0; a !== o && s + e[a] < n;) { s += e[a], a++; } i.push(t.slice(0, a)); var u = a; for (s = 0; a !== o;) { s + e[a] > r && (i.push(t.slice(u, a)), s = 0, u = a), s += e[a], a++; } return u !== a && i.push(t.slice(u, a)), i; }, kt = function kt(t, e, n) { n || (n = {}); var r, i, a, o, s, u, c, h = [], l = [h], f = n.textIndent || 0, d = 0, p = 0, g = t.split(" "), m = _t.apply(this, [" ", n])[0]; if (u = -1 === n.lineIndent ? g[0].length + 2 : n.lineIndent || 0) { var v = Array(u).join(" "), b = []; g.map(function (t) { (t = t.split(/\s*\n/)).length > 1 ? b = b.concat(t.map(function (t, e) { return (e && t.length ? "\n" : "") + t; })) : b.push(t[0]); }), g = b, u = St.apply(this, [v, n]); } for (a = 0, o = g.length; a < o; a++) { var y = 0; if (r = g[a], u && "\n" == r[0] && (r = r.substr(1), y = 1), f + d + (p = (i = _t.apply(this, [r, n])).reduce(function (t, e) { return t + e; }, 0)) > e || y) { if (p > e) { for (s = Pt.apply(this, [r, i, e - (f + d), e]), h.push(s.shift()), h = [s.pop()]; s.length;) { l.push([s.shift()]); } p = i.slice(r.length - (h[0] ? h[0].length : 0)).reduce(function (t, e) { return t + e; }, 0); } else h = [r]; l.push(h), f = p + u, d = m; } else h.push(r), f += d + p, d = m; } return c = u ? function (t, e) { return (e ? v : "") + t.join(" "); } : function (t) { return t.join(" "); }, l.map(c); }, At.splitTextToSize = function (t, e, n) { var r, i = (n = n || {}).fontSize || this.internal.getFontSize(), a = function (t) { if (t.widths && t.kerning) return { widths: t.widths, kerning: t.kerning }; var e = this.internal.getFont(t.fontName, t.fontStyle); return e.metadata.Unicode ? { widths: e.metadata.Unicode.widths || { 0: 1 }, kerning: e.metadata.Unicode.kerning || {} } : { font: e.metadata, fontSize: this.internal.getFontSize(), charSpace: this.internal.getCharSpace() }; }.call(this, n); r = Array.isArray(t) ? t : String(t).split(/\r?\n/); var o = 1 * this.internal.scaleFactor * e / i; a.textIndent = n.textIndent ? 1 * n.textIndent * this.internal.scaleFactor / i : 0, a.lineIndent = n.lineIndent; var s, u, c = []; for (s = 0, u = r.length; s < u; s++) { c = c.concat(kt.apply(this, [r[s], o, a])); } return c; }, /** @license jsPDF standard_fonts_metrics plugin * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com * MIT license. * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ==================================================================== */ function (t) { t.__fontmetrics__ = t.__fontmetrics__ || {}; for (var e = "klmnopqrstuvwxyz", n = {}, r = {}, i = 0; i < e.length; i++) { n[e[i]] = "0123456789abcdef"[i], r["0123456789abcdef"[i]] = e[i]; } var a = function a(t) { return "0x" + parseInt(t, 10).toString(16); }, o = t.__fontmetrics__.compress = function (t) { var e, n, i, s, u = ["{"]; for (var c in t) { if (e = t[c], isNaN(parseInt(c, 10)) ? n = "'" + c + "'" : (c = parseInt(c, 10), n = (n = a(c).slice(2)).slice(0, -1) + r[n.slice(-1)]), "number" == typeof e) e < 0 ? (i = a(e).slice(3), s = "-") : (i = a(e).slice(2), s = ""), i = s + i.slice(0, -1) + r[i.slice(-1)];else { if ("object" != _typeof(e)) throw new Error("Don't know what to do with value type " + _typeof(e) + "."); i = o(e); } u.push(n + i); } return u.push("}"), u.join(""); }, s = t.__fontmetrics__.uncompress = function (t) { if ("string" != typeof t) throw new Error("Invalid argument passed to uncompress."); for (var e, r, i, a, o = {}, s = 1, u = o, c = [], h = "", l = "", f = t.length - 1, d = 1; d < f; d += 1) { "'" == (a = t[d]) ? e ? (i = e.join(""), e = void 0) : e = [] : e ? e.push(a) : "{" == a ? (c.push([u, i]), u = {}, i = void 0) : "}" == a ? ((r = c.pop())[0][r[1]] = u, i = void 0, u = r[0]) : "-" == a ? s = -1 : void 0 === i ? n.hasOwnProperty(a) ? (h += n[a], i = parseInt(h, 16) * s, s = 1, h = "") : h += a : n.hasOwnProperty(a) ? (l += n[a], u[i] = parseInt(l, 16) * s, s = 1, i = void 0, l = "") : l += a; } return o; }, u = { codePages: ["WinAnsiEncoding"], WinAnsiEncoding: s("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}") }, c = { Unicode: { Courier: u, "Courier-Bold": u, "Courier-BoldOblique": u, "Courier-Oblique": u, Helvetica: u, "Helvetica-Bold": u, "Helvetica-BoldOblique": u, "Helvetica-Oblique": u, "Times-Roman": u, "Times-Bold": u, "Times-BoldItalic": u, "Times-Italic": u } }, h = { Unicode: { "Courier-Oblique": s("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Times-BoldItalic": s("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"), "Helvetica-Bold": s("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"), Courier: s("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Courier-BoldOblique": s("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Times-Bold": s("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}"), Symbol: s("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}"), Helvetica: s("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"), "Helvetica-BoldOblique": s("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"), ZapfDingbats: s("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}"), "Courier-Bold": s("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Times-Italic": s("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}fv{17su5tu5qs}fw{17su5tu5qs}}}"), "Times-Roman": s("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"), "Helvetica-Oblique": s("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}") } }; t.events.push(["addFont", function (t) { var e = t.font, n = h.Unicode[e.postScriptName]; n && (e.metadata.Unicode = {}, e.metadata.Unicode.widths = n.widths, e.metadata.Unicode.kerning = n.kerning); var r = c.Unicode[e.postScriptName]; r && (e.metadata.Unicode.encoding = r, e.encoding = r.codePages[0]); }]); }(g.API), /** * @license * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { var e = function e(t) { for (var e = t.length, n = new Uint8Array(e), r = 0; r < e; r++) { n[r] = t.charCodeAt(r); } return n; }; t.API.events.push(["addFont", function (n) { var r = void 0, i = n.font, a = n.instance; if (!i.isStandardFont) { if (void 0 === a) throw new Error("Font does not exist in vFS, import fonts or remove declaration doc.addFont('" + i.postScriptName + "')."); if ("string" != typeof (r = !1 === a.existsFileInVFS(i.postScriptName) ? a.loadFile(i.postScriptName) : a.getFileFromVFS(i.postScriptName))) throw new Error("Font is not stored as string-data in vFS, import fonts or remove declaration doc.addFont('" + i.postScriptName + "')."); !function (n, r) { r = /^\x00\x01\x00\x00/.test(r) ? e(r) : e(o(r)), n.metadata = t.API.TTFFont.open(r), n.metadata.Unicode = n.metadata.Unicode || { encoding: {}, kerning: {}, widths: [] }, n.metadata.glyIdsUsed = [0]; }(i, r); } }]); }(g), /** @license * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ==================================================================== */ function (e) { function r() { return (t.canvg ? Promise.resolve(t.canvg) : Promise.resolve().then(function () { return index_es; }))["catch"](function (t) { return Promise.reject(new Error("Could not load dompurify: " + t)); }).then(function (t) { return t["default"] ? t["default"] : t; }); } g.API.addSvgAsImage = function (t, e, i, a, o, s, u, c) { if (isNaN(e) || isNaN(i)) throw n.error("jsPDF.addSvgAsImage: Invalid coordinates", arguments), new Error("Invalid coordinates passed to jsPDF.addSvgAsImage"); if (isNaN(a) || isNaN(o)) throw n.error("jsPDF.addSvgAsImage: Invalid measurements", arguments), new Error("Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage"); var h = document.createElement("canvas"); h.width = a, h.height = o; var l = h.getContext("2d"); l.fillStyle = "#fff", l.fillRect(0, 0, h.width, h.height); var f = { ignoreMouse: !0, ignoreAnimation: !0, ignoreDimensions: !0 }, d = this; return r().then(function (e) { return e.Canvg.fromString(l, t, f); }, function () { return Promise.reject(new Error("Could not load canvg.")); }).then(function (t) { return t.render(f); }).then(function () { d.addImage(h.toDataURL("image/jpeg", 1), e, i, a, o, u, c); }); }; }(), g.API.putTotalPages = function (t) { var e, n = 0; parseInt(this.internal.getFont().id.substr(1), 10) < 15 ? (e = new RegExp(t, "g"), n = this.internal.getNumberOfPages()) : (e = new RegExp(this.pdfEscape16(t, this.internal.getFont()), "g"), n = this.pdfEscape16(this.internal.getNumberOfPages() + "", this.internal.getFont())); for (var r = 1; r <= this.internal.getNumberOfPages(); r++) { for (var i = 0; i < this.internal.pages[r].length; i++) { this.internal.pages[r][i] = this.internal.pages[r][i].replace(e, n); } } return this; }, g.API.viewerPreferences = function (t, e) { var n; t = t || {}, e = e || !1; var r, i, a, o = { HideToolbar: { defaultValue: !1, value: !1, type: "boolean", explicitSet: !1, valueSet: [!0, !1], pdfVersion: 1.3 }, HideMenubar: { defaultValue: !1, value: !1, type: "boolean", explicitSet: !1, valueSet: [!0, !1], pdfVersion: 1.3 }, HideWindowUI: { defaultValue: !1, value: !1, type: "boolean", explicitSet: !1, valueSet: [!0, !1], pdfVersion: 1.3 }, FitWindow: { defaultValue: !1, value: !1, type: "boolean", explicitSet: !1, valueSet: [!0, !1], pdfVersion: 1.3 }, CenterWindow: { defaultValue: !1, value: !1, type: "boolean", explicitSet: !1, valueSet: [!0, !1], pdfVersion: 1.3 }, DisplayDocTitle: { defaultValue: !1, value: !1, type: "boolean", explicitSet: !1, valueSet: [!0, !1], pdfVersion: 1.4 }, NonFullScreenPageMode: { defaultValue: "UseNone", value: "UseNone", type: "name", explicitSet: !1, valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"], pdfVersion: 1.3 }, Direction: { defaultValue: "L2R", value: "L2R", type: "name", explicitSet: !1, valueSet: ["L2R", "R2L"], pdfVersion: 1.3 }, ViewArea: { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: !1, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 }, ViewClip: { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: !1, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 }, PrintArea: { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: !1, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 }, PrintClip: { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: !1, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 }, PrintScaling: { defaultValue: "AppDefault", value: "AppDefault", type: "name", explicitSet: !1, valueSet: ["AppDefault", "None"], pdfVersion: 1.6 }, Duplex: { defaultValue: "", value: "none", type: "name", explicitSet: !1, valueSet: ["Simplex", "DuplexFlipShortEdge", "DuplexFlipLongEdge", "none"], pdfVersion: 1.7 }, PickTrayByPDFSize: { defaultValue: !1, value: !1, type: "boolean", explicitSet: !1, valueSet: [!0, !1], pdfVersion: 1.7 }, PrintPageRange: { defaultValue: "", value: "", type: "array", explicitSet: !1, valueSet: null, pdfVersion: 1.7 }, NumCopies: { defaultValue: 1, value: 1, type: "integer", explicitSet: !1, valueSet: null, pdfVersion: 1.7 } }, s = Object.keys(o), u = [], c = 0, h = 0, l = 0; function f(t, e) { var n, r = !1; for (n = 0; n < t.length; n += 1) { t[n] === e && (r = !0); } return r; } if (void 0 === this.internal.viewerpreferences && (this.internal.viewerpreferences = {}, this.internal.viewerpreferences.configuration = JSON.parse(JSON.stringify(o)), this.internal.viewerpreferences.isSubscribed = !1), n = this.internal.viewerpreferences.configuration, "reset" === t || !0 === e) { var d = s.length; for (l = 0; l < d; l += 1) { n[s[l]].value = n[s[l]].defaultValue, n[s[l]].explicitSet = !1; } } if ("object" == _typeof(t)) for (i in t) { if (a = t[i], f(s, i) && void 0 !== a) { if ("boolean" === n[i].type && "boolean" == typeof a) n[i].value = a;else if ("name" === n[i].type && f(n[i].valueSet, a)) n[i].value = a;else if ("integer" === n[i].type && Number.isInteger(a)) n[i].value = a;else if ("array" === n[i].type) { for (c = 0; c < a.length; c += 1) { if (r = !0, 1 === a[c].length && "number" == typeof a[c][0]) u.push(String(a[c] - 1));else if (a[c].length > 1) { for (h = 0; h < a[c].length; h += 1) { "number" != typeof a[c][h] && (r = !1); } !0 === r && u.push([a[c][0] - 1, a[c][1] - 1].join(" ")); } } n[i].value = "[" + u.join(" ") + "]"; } else n[i].value = n[i].defaultValue; n[i].explicitSet = !0; } } return !1 === this.internal.viewerpreferences.isSubscribed && (this.internal.events.subscribe("putCatalog", function () { var t, e = []; for (t in n) { !0 === n[t].explicitSet && ("name" === n[t].type ? e.push("/" + t + " /" + n[t].value) : e.push("/" + t + " " + n[t].value)); } 0 !== e.length && this.internal.write("/ViewerPreferences\n<<\n" + e.join("\n") + "\n>>"); }), this.internal.viewerpreferences.isSubscribed = !0), this.internal.viewerpreferences.configuration = n, this; }, /** ==================================================================== * @license * jsPDF XMP metadata plugin * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ==================================================================== */ function (t) { var e = function e() { var t = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:jspdf="' + this.internal.__metadata__.namespaceuri + '"><jspdf:metadata>', e = unescape(encodeURIComponent('<x:xmpmeta xmlns:x="adobe:ns:meta/">')), n = unescape(encodeURIComponent(t)), r = unescape(encodeURIComponent(this.internal.__metadata__.metadata)), i = unescape(encodeURIComponent("</jspdf:metadata></rdf:Description></rdf:RDF>")), a = unescape(encodeURIComponent("</x:xmpmeta>")), o = n.length + r.length + i.length + e.length + a.length; this.internal.__metadata__.metadata_object_number = this.internal.newObject(), this.internal.write("<< /Type /Metadata /Subtype /XML /Length " + o + " >>"), this.internal.write("stream"), this.internal.write(e + n + r + i + a), this.internal.write("endstream"), this.internal.write("endobj"); }, n = function n() { this.internal.__metadata__.metadata_object_number && this.internal.write("/Metadata " + this.internal.__metadata__.metadata_object_number + " 0 R"); }; t.addMetadata = function (t, r) { return void 0 === this.internal.__metadata__ && (this.internal.__metadata__ = { metadata: t, namespaceuri: r || "http://jspdf.default.namespaceuri/" }, this.internal.events.subscribe("putCatalog", n), this.internal.events.subscribe("postPutResources", e)), this; }; }(g.API), function (t) { var e = t.API, n = e.pdfEscape16 = function (t, e) { for (var n, r = e.metadata.Unicode.widths, i = ["", "0", "00", "000", "0000"], a = [""], o = 0, s = t.length; o < s; ++o) { if (n = e.metadata.characterToGlyph(t.charCodeAt(o)), e.metadata.glyIdsUsed.push(n), e.metadata.toUnicode[n] = t.charCodeAt(o), -1 == r.indexOf(n) && (r.push(n), r.push([parseInt(e.metadata.widthOfGlyph(n), 10)])), "0" == n) return a.join(""); n = n.toString(16), a.push(i[4 - n.length], n); } return a.join(""); }, r = function r(t) { var e, n, r, i, a, o, s; for (a = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange", r = [], o = 0, s = (n = Object.keys(t).sort(function (t, e) { return t - e; })).length; o < s; o++) { e = n[o], r.length >= 100 && (a += "\n" + r.length + " beginbfchar\n" + r.join("\n") + "\nendbfchar", r = []), void 0 !== t[e] && null !== t[e] && "function" == typeof t[e].toString && (i = ("0000" + t[e].toString(16)).slice(-4), e = ("0000" + (+e).toString(16)).slice(-4), r.push("<" + e + "><" + i + ">")); } return r.length && (a += "\n" + r.length + " beginbfchar\n" + r.join("\n") + "\nendbfchar\n"), a += "endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend"; }; e.events.push(["putFont", function (e) { !function (e) { var n = e.font, i = e.out, a = e.newObject, o = e.putStream, s = e.pdfEscapeWithNeededParanthesis; if (n.metadata instanceof t.API.TTFFont && "Identity-H" === n.encoding) { for (var u = n.metadata.Unicode.widths, c = n.metadata.subset.encode(n.metadata.glyIdsUsed, 1), h = "", l = 0; l < c.length; l++) { h += String.fromCharCode(c[l]); } var f = a(); o({ data: h, addLength1: !0 }), i("endobj"); var d = a(); o({ data: r(n.metadata.toUnicode), addLength1: !0 }), i("endobj"); var p = a(); i("<<"), i("/Type /FontDescriptor"), i("/FontName /" + s(n.fontName)), i("/FontFile2 " + f + " 0 R"), i("/FontBBox " + t.API.PDFObject.convert(n.metadata.bbox)), i("/Flags " + n.metadata.flags), i("/StemV " + n.metadata.stemV), i("/ItalicAngle " + n.metadata.italicAngle), i("/Ascent " + n.metadata.ascender), i("/Descent " + n.metadata.decender), i("/CapHeight " + n.metadata.capHeight), i(">>"), i("endobj"); var g = a(); i("<<"), i("/Type /Font"), i("/BaseFont /" + s(n.fontName)), i("/FontDescriptor " + p + " 0 R"), i("/W " + t.API.PDFObject.convert(u)), i("/CIDToGIDMap /Identity"), i("/DW 1000"), i("/Subtype /CIDFontType2"), i("/CIDSystemInfo"), i("<<"), i("/Supplement 0"), i("/Registry (Adobe)"), i("/Ordering (" + n.encoding + ")"), i(">>"), i(">>"), i("endobj"), n.objectNumber = a(), i("<<"), i("/Type /Font"), i("/Subtype /Type0"), i("/ToUnicode " + d + " 0 R"), i("/BaseFont /" + s(n.fontName)), i("/Encoding /" + n.encoding), i("/DescendantFonts [" + g + " 0 R]"), i(">>"), i("endobj"), n.isAlreadyPutted = !0; } }(e); }]); e.events.push(["putFont", function (e) { !function (e) { var n = e.font, i = e.out, a = e.newObject, o = e.putStream, s = e.pdfEscapeWithNeededParanthesis; if (n.metadata instanceof t.API.TTFFont && "WinAnsiEncoding" === n.encoding) { for (var u = n.metadata.rawData, c = "", h = 0; h < u.length; h++) { c += String.fromCharCode(u[h]); } var l = a(); o({ data: c, addLength1: !0 }), i("endobj"); var f = a(); o({ data: r(n.metadata.toUnicode), addLength1: !0 }), i("endobj"); var d = a(); i("<<"), i("/Descent " + n.metadata.decender), i("/CapHeight " + n.metadata.capHeight), i("/StemV " + n.metadata.stemV), i("/Type /FontDescriptor"), i("/FontFile2 " + l + " 0 R"), i("/Flags 96"), i("/FontBBox " + t.API.PDFObject.convert(n.metadata.bbox)), i("/FontName /" + s(n.fontName)), i("/ItalicAngle " + n.metadata.italicAngle), i("/Ascent " + n.metadata.ascender), i(">>"), i("endobj"), n.objectNumber = a(); for (var p = 0; p < n.metadata.hmtx.widths.length; p++) { n.metadata.hmtx.widths[p] = parseInt(n.metadata.hmtx.widths[p] * (1e3 / n.metadata.head.unitsPerEm)); } i("<</Subtype/TrueType/Type/Font/ToUnicode " + f + " 0 R/BaseFont/" + n.fontName + "/FontDescriptor " + d + " 0 R/Encoding/" + n.encoding + " /FirstChar 29 /LastChar 255 /Widths " + t.API.PDFObject.convert(n.metadata.hmtx.widths) + ">>"), i("endobj"), n.isAlreadyPutted = !0; } }(e); }]); var i = function i(t) { var e, r = t.text || "", i = t.x, a = t.y, o = t.options || {}, s = t.mutex || {}, u = s.pdfEscape, c = s.activeFontKey, h = s.fonts, l = c, f = "", d = 0, p = "", g = h[l].encoding; if ("Identity-H" !== h[l].encoding) return { text: r, x: i, y: a, options: o, mutex: s }; for (p = r, l = c, Array.isArray(r) && (p = r[0]), d = 0; d < p.length; d += 1) { h[l].metadata.hasOwnProperty("cmap") && (e = h[l].metadata.cmap.unicode.codeMap[p[d].charCodeAt(0)]), e || p[d].charCodeAt(0) < 256 && h[l].metadata.hasOwnProperty("Unicode") ? f += p[d] : f += ""; } var m = ""; return parseInt(l.slice(1)) < 14 || "WinAnsiEncoding" === g ? m = u(f, l).split("").map(function (t) { return t.charCodeAt(0).toString(16); }).join("") : "Identity-H" === g && (m = n(f, h[l])), s.isHex = !0, { text: m, x: i, y: a, options: o, mutex: s }; }; e.events.push(["postProcessText", function (t) { var e = t.text || "", n = [], r = { text: e, x: t.x, y: t.y, options: t.options, mutex: t.mutex }; if (Array.isArray(e)) { var a = 0; for (a = 0; a < e.length; a += 1) { Array.isArray(e[a]) && 3 === e[a].length ? n.push([i(Object.assign({}, r, { text: e[a][0] })).text, e[a][1], e[a][2]]) : n.push(i(Object.assign({}, r, { text: e[a] })).text); } t.text = n; } else t.text = i(Object.assign({}, r, { text: e })).text; }]); }(g), /** * @license * jsPDF virtual FileSystem functionality * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t) { var e = function e() { return void 0 === this.internal.vFS && (this.internal.vFS = {}), !0; }; t.existsFileInVFS = function (t) { return e.call(this), void 0 !== this.internal.vFS[t]; }, t.addFileToVFS = function (t, n) { return e.call(this), this.internal.vFS[t] = n, this; }, t.getFileFromVFS = function (t) { return e.call(this), void 0 !== this.internal.vFS[t] ? this.internal.vFS[t] : null; }; }(g.API), /** * @license * Unicode Bidi Engine based on the work of Alex Shensis (@asthensis) * MIT License */ function (t) { t.__bidiEngine__ = t.prototype.__bidiEngine__ = function (t) { var n, r, i, a, o, s, u, c = e, h = [[0, 3, 0, 1, 0, 0, 0], [0, 3, 0, 1, 2, 2, 0], [0, 3, 0, 17, 2, 0, 1], [0, 3, 5, 5, 4, 1, 0], [0, 3, 21, 21, 4, 0, 1], [0, 3, 5, 5, 4, 2, 0]], l = [[2, 0, 1, 1, 0, 1, 0], [2, 0, 1, 1, 0, 2, 0], [2, 0, 2, 1, 3, 2, 0], [2, 0, 2, 33, 3, 1, 1]], f = { L: 0, R: 1, EN: 2, AN: 3, N: 4, B: 5, S: 6 }, d = { 0: 0, 5: 1, 6: 2, 7: 3, 32: 4, 251: 5, 254: 6, 255: 7 }, p = ["(", ")", "(", "<", ">", "<", "[", "]", "[", "{", "}", "{", "«", "»", "«", "‹", "›", "‹", "⁅", "⁆", "⁅", "⁽", "⁾", "⁽", "₍", "₎", "₍", "≤", "≥", "≤", "〈", "〉", "〈", "﹙", "﹚", "﹙", "﹛", "﹜", "﹛", "﹝", "﹞", "﹝", "﹤", "﹥", "﹤"], g = new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/), m = !1, v = 0; this.__bidiEngine__ = {}; var b = function b(t) { var e = t.charCodeAt(), n = e >> 8, r = d[n]; return void 0 !== r ? c[256 * r + (255 & e)] : 252 === n || 253 === n ? "AL" : g.test(n) ? "L" : 8 === n ? "R" : "N"; }, y = function y(t) { for (var e, n = 0; n < t.length; n++) { if ("L" === (e = b(t.charAt(n)))) return !1; if ("R" === e) return !0; } return !1; }, w = function w(t, e, o, s) { var u, c, h, l, f = e[s]; switch (f) { case "L": case "R": m = !1; break; case "N": case "AN": break; case "EN": m && (f = "AN"); break; case "AL": m = !0, f = "R"; break; case "WS": f = "N"; break; case "CS": s < 1 || s + 1 >= e.length || "EN" !== (u = o[s - 1]) && "AN" !== u || "EN" !== (c = e[s + 1]) && "AN" !== c ? f = "N" : m && (c = "AN"), f = c === u ? c : "N"; break; case "ES": f = "EN" === (u = s > 0 ? o[s - 1] : "B") && s + 1 < e.length && "EN" === e[s + 1] ? "EN" : "N"; break; case "ET": if (s > 0 && "EN" === o[s - 1]) { f = "EN"; break; } if (m) { f = "N"; break; } for (h = s + 1, l = e.length; h < l && "ET" === e[h];) { h++; } f = h < l && "EN" === e[h] ? "EN" : "N"; break; case "NSM": if (i && !a) { for (l = e.length, h = s + 1; h < l && "NSM" === e[h];) { h++; } if (h < l) { var d = t[s], p = d >= 1425 && d <= 2303 || 64286 === d; if (u = e[h], p && ("R" === u || "AL" === u)) { f = "R"; break; } } } f = s < 1 || "B" === (u = e[s - 1]) ? "N" : o[s - 1]; break; case "B": m = !1, n = !0, f = v; break; case "S": r = !0, f = "N"; break; case "LRE": case "RLE": case "LRO": case "RLO": case "PDF": m = !1; break; case "BN": f = "N"; } return f; }, N = function N(t, e, n) { var r = t.split(""); return n && L(r, n, { hiLevel: v }), r.reverse(), e && e.reverse(), r.join(""); }, L = function L(t, e, i) { var a, o, s, u, c, d = -1, p = t.length, g = 0, y = [], N = v ? l : h, L = []; for (m = !1, n = !1, r = !1, o = 0; o < p; o++) { L[o] = b(t[o]); } for (s = 0; s < p; s++) { if (c = g, y[s] = w(t, L, y, s), a = 240 & (g = N[c][f[y[s]]]), g &= 15, e[s] = u = N[g][5], a > 0) if (16 === a) { for (o = d; o < s; o++) { e[o] = 1; } d = -1; } else d = -1; if (N[g][6]) -1 === d && (d = s);else if (d > -1) { for (o = d; o < s; o++) { e[o] = u; } d = -1; } "B" === L[s] && (e[s] = 0), i.hiLevel |= u; } r && function (t, e, n) { for (var r = 0; r < n; r++) { if ("S" === t[r]) { e[r] = v; for (var i = r - 1; i >= 0 && "WS" === t[i]; i--) { e[i] = v; } } } }(L, e, p); }, x = function x(t, e, r, i, a) { if (!(a.hiLevel < t)) { if (1 === t && 1 === v && !n) return e.reverse(), void (r && r.reverse()); for (var o, s, u, c, h = e.length, l = 0; l < h;) { if (i[l] >= t) { for (u = l + 1; u < h && i[u] >= t;) { u++; } for (c = l, s = u - 1; c < s; c++, s--) { o = e[c], e[c] = e[s], e[s] = o, r && (o = r[c], r[c] = r[s], r[s] = o); } l = u; } l++; } } }, A = function A(t, e, n) { var r = t.split(""), i = { hiLevel: v }; return n || (n = []), L(r, n, i), function (t, e, n) { if (0 !== n.hiLevel && u) for (var r, i = 0; i < t.length; i++) { 1 === e[i] && (r = p.indexOf(t[i])) >= 0 && (t[i] = p[r + 1]); } }(r, n, i), x(2, r, e, n, i), x(1, r, e, n, i), r.join(""); }; return this.__bidiEngine__.doBidiReorder = function (t, e, n) { if (function (t, e) { if (e) for (var n = 0; n < t.length; n++) { e[n] = n; } void 0 === a && (a = y(t)), void 0 === s && (s = y(t)); }(t, e), i || !o || s) { if (i && o && a ^ s) v = a ? 1 : 0, t = N(t, e, n);else if (!i && o && s) v = a ? 1 : 0, t = A(t, e, n), t = N(t, e);else if (!i || a || o || s) { if (i && !o && a ^ s) t = N(t, e), a ? (v = 0, t = A(t, e, n)) : (v = 1, t = A(t, e, n), t = N(t, e));else if (i && a && !o && s) v = 1, t = A(t, e, n), t = N(t, e);else if (!i && !o && a ^ s) { var r = u; a ? (v = 1, t = A(t, e, n), v = 0, u = !1, t = A(t, e, n), u = r) : (v = 0, t = A(t, e, n), t = N(t, e), v = 1, u = !1, t = A(t, e, n), u = r, t = N(t, e)); } } else v = 0, t = A(t, e, n); } else v = a ? 1 : 0, t = A(t, e, n); return t; }, this.__bidiEngine__.setOptions = function (t) { t && (i = t.isInputVisual, o = t.isOutputVisual, a = t.isInputRtl, s = t.isOutputRtl, u = t.isSymmetricSwapping); }, this.__bidiEngine__.setOptions(t), this.__bidiEngine__; }; var e = ["BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "S", "B", "S", "WS", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "B", "B", "B", "S", "WS", "N", "N", "ET", "ET", "ET", "N", "N", "N", "N", "N", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "BN", "BN", "BN", "BN", "BN", "BN", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "CS", "N", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "L", "N", "N", "BN", "N", "N", "ET", "ET", "EN", "EN", "N", "L", "N", "N", "N", "EN", "L", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "N", "N", "N", "N", "N", "ET", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "R", "NSM", "R", "NSM", "NSM", "R", "NSM", "NSM", "R", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "AN", "AN", "AN", "AN", "AN", "AN", "N", "N", "AL", "ET", "ET", "AL", "CS", "AL", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "ET", "AN", "AN", "AL", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "NSM", "NSM", "N", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "R", "R", "N", "N", "N", "N", "R", "N", "N", "N", "N", "N", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "BN", "BN", "BN", "L", "R", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "WS", "B", "LRE", "RLE", "PDF", "LRO", "RLO", "CS", "ET", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "CS", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "WS", "BN", "BN", "BN", "BN", "BN", "N", "LRI", "RLI", "FSI", "PDI", "BN", "BN", "BN", "BN", "BN", "BN", "EN", "L", "N", "N", "EN", "EN", "EN", "EN", "EN", "EN", "ES", "ES", "N", "N", "N", "L", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "ES", "ES", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "R", "NSM", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "ES", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "N", "R", "R", "R", "R", "R", "N", "R", "N", "R", "R", "N", "R", "R", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "CS", "N", "CS", "N", "N", "CS", "N", "N", "N", "N", "N", "N", "N", "N", "N", "ET", "N", "N", "ES", "ES", "N", "N", "N", "N", "N", "ET", "ET", "N", "N", "N", "N", "N", "AL", "AL", "AL", "AL", "AL", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "N", "BN", "N", "N", "N", "ET", "ET", "ET", "N", "N", "N", "N", "N", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "N", "N", "N", "ET", "ET", "N", "N", "N", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N"], n = new t.__bidiEngine__({ isInputVisual: !0 }); t.API.events.push(["postProcessText", function (t) { var e = t.text, r = (t.x, t.y, t.options || {}), i = (t.mutex, r.lang, []); if (r.isInputVisual = "boolean" != typeof r.isInputVisual || r.isInputVisual, n.setOptions(r), "[object Array]" === Object.prototype.toString.call(e)) { var a = 0; for (i = [], a = 0; a < e.length; a += 1) { "[object Array]" === Object.prototype.toString.call(e[a]) ? i.push([n.doBidiReorder(e[a][0]), e[a][1], e[a][2]]) : i.push([n.doBidiReorder(e[a])]); } t.text = i; } else t.text = n.doBidiReorder(e); n.setOptions({ isInputVisual: !0 }); }]); }(g), g.API.TTFFont = function () { function t(t) { var e; if (this.rawData = t, e = this.contents = new Rt(t), this.contents.pos = 4, "ttcf" === e.readString(4)) throw new Error("TTCF not supported."); e.pos = 0, this.parse(), this.subset = new re$1(this), this.registerTTF(); } return t.open = function (e) { return new t(e); }, t.prototype.parse = function () { return this.directory = new Tt(this.contents), this.head = new zt(this), this.name = new Xt(this), this.cmap = new Wt(this), this.toUnicode = {}, this.hhea = new Vt(this), this.maxp = new Kt(this), this.hmtx = new Zt(this), this.post = new Yt(this), this.os2 = new Gt(this), this.loca = new ne(this), this.glyf = new Qt(this), this.ascender = this.os2.exists && this.os2.ascender || this.hhea.ascender, this.decender = this.os2.exists && this.os2.decender || this.hhea.decender, this.lineGap = this.os2.exists && this.os2.lineGap || this.hhea.lineGap, this.bbox = [this.head.xMin, this.head.yMin, this.head.xMax, this.head.yMax]; }, t.prototype.registerTTF = function () { var t, e, n, r, i; if (this.scaleFactor = 1e3 / this.head.unitsPerEm, this.bbox = function () { var e, n, r, i; for (i = [], e = 0, n = (r = this.bbox).length; e < n; e++) { t = r[e], i.push(Math.round(t * this.scaleFactor)); } return i; }.call(this), this.stemV = 0, this.post.exists ? (n = 255 & (r = this.post.italic_angle), 0 != (32768 & (e = r >> 16)) && (e = -(1 + (65535 ^ e))), this.italicAngle = +(e + "." + n)) : this.italicAngle = 0, this.ascender = Math.round(this.ascender * this.scaleFactor), this.decender = Math.round(this.decender * this.scaleFactor), this.lineGap = Math.round(this.lineGap * this.scaleFactor), this.capHeight = this.os2.exists && this.os2.capHeight || this.ascender, this.xHeight = this.os2.exists && this.os2.xHeight || 0, this.familyClass = (this.os2.exists && this.os2.familyClass || 0) >> 8, this.isSerif = 1 === (i = this.familyClass) || 2 === i || 3 === i || 4 === i || 5 === i || 7 === i, this.isScript = 10 === this.familyClass, this.flags = 0, this.post.isFixedPitch && (this.flags |= 1), this.isSerif && (this.flags |= 2), this.isScript && (this.flags |= 8), 0 !== this.italicAngle && (this.flags |= 64), this.flags |= 32, !this.cmap.unicode) throw new Error("No unicode cmap for font"); }, t.prototype.characterToGlyph = function (t) { var e; return (null != (e = this.cmap.unicode) ? e.codeMap[t] : void 0) || 0; }, t.prototype.widthOfGlyph = function (t) { var e; return e = 1e3 / this.head.unitsPerEm, this.hmtx.forGlyph(t).advance * e; }, t.prototype.widthOfString = function (t, e, n) { var r, i, a, o; for (a = 0, i = 0, o = (t = "" + t).length; 0 <= o ? i < o : i > o; i = 0 <= o ? ++i : --i) { r = t.charCodeAt(i), a += this.widthOfGlyph(this.characterToGlyph(r)) + n * (1e3 / e) || 0; } return a * (e / 1e3); }, t.prototype.lineHeight = function (t, e) { var n; return null == e && (e = !1), n = e ? this.lineGap : 0, (this.ascender + n - this.decender) / 1e3 * t; }, t; }(); var qt, Rt = function () { function t(t) { this.data = null != t ? t : [], this.pos = 0, this.length = this.data.length; } return t.prototype.readByte = function () { return this.data[this.pos++]; }, t.prototype.writeByte = function (t) { return this.data[this.pos++] = t; }, t.prototype.readUInt32 = function () { return 16777216 * this.readByte() + (this.readByte() << 16) + (this.readByte() << 8) + this.readByte(); }, t.prototype.writeUInt32 = function (t) { return this.writeByte(t >>> 24 & 255), this.writeByte(t >> 16 & 255), this.writeByte(t >> 8 & 255), this.writeByte(255 & t); }, t.prototype.readInt32 = function () { var t; return (t = this.readUInt32()) >= 2147483648 ? t - 4294967296 : t; }, t.prototype.writeInt32 = function (t) { return t < 0 && (t += 4294967296), this.writeUInt32(t); }, t.prototype.readUInt16 = function () { return this.readByte() << 8 | this.readByte(); }, t.prototype.writeUInt16 = function (t) { return this.writeByte(t >> 8 & 255), this.writeByte(255 & t); }, t.prototype.readInt16 = function () { var t; return (t = this.readUInt16()) >= 32768 ? t - 65536 : t; }, t.prototype.writeInt16 = function (t) { return t < 0 && (t += 65536), this.writeUInt16(t); }, t.prototype.readString = function (t) { var e, n; for (n = [], e = 0; 0 <= t ? e < t : e > t; e = 0 <= t ? ++e : --e) { n[e] = String.fromCharCode(this.readByte()); } return n.join(""); }, t.prototype.writeString = function (t) { var e, n, r; for (r = [], e = 0, n = t.length; 0 <= n ? e < n : e > n; e = 0 <= n ? ++e : --e) { r.push(this.writeByte(t.charCodeAt(e))); } return r; }, t.prototype.readShort = function () { return this.readInt16(); }, t.prototype.writeShort = function (t) { return this.writeInt16(t); }, t.prototype.readLongLong = function () { var t, e, n, r, i, a, o, s; return t = this.readByte(), e = this.readByte(), n = this.readByte(), r = this.readByte(), i = this.readByte(), a = this.readByte(), o = this.readByte(), s = this.readByte(), 128 & t ? -1 * (72057594037927940 * (255 ^ t) + 281474976710656 * (255 ^ e) + 1099511627776 * (255 ^ n) + 4294967296 * (255 ^ r) + 16777216 * (255 ^ i) + 65536 * (255 ^ a) + 256 * (255 ^ o) + (255 ^ s) + 1) : 72057594037927940 * t + 281474976710656 * e + 1099511627776 * n + 4294967296 * r + 16777216 * i + 65536 * a + 256 * o + s; }, t.prototype.writeLongLong = function (t) { var e, n; return e = Math.floor(t / 4294967296), n = 4294967295 & t, this.writeByte(e >> 24 & 255), this.writeByte(e >> 16 & 255), this.writeByte(e >> 8 & 255), this.writeByte(255 & e), this.writeByte(n >> 24 & 255), this.writeByte(n >> 16 & 255), this.writeByte(n >> 8 & 255), this.writeByte(255 & n); }, t.prototype.readInt = function () { return this.readInt32(); }, t.prototype.writeInt = function (t) { return this.writeInt32(t); }, t.prototype.read = function (t) { var e, n; for (e = [], n = 0; 0 <= t ? n < t : n > t; n = 0 <= t ? ++n : --n) { e.push(this.readByte()); } return e; }, t.prototype.write = function (t) { var e, n, r, i; for (i = [], n = 0, r = t.length; n < r; n++) { e = t[n], i.push(this.writeByte(e)); } return i; }, t; }(), Tt = function () { var t; function e(t) { var e, n, r; for (this.scalarType = t.readInt(), this.tableCount = t.readShort(), this.searchRange = t.readShort(), this.entrySelector = t.readShort(), this.rangeShift = t.readShort(), this.tables = {}, n = 0, r = this.tableCount; 0 <= r ? n < r : n > r; n = 0 <= r ? ++n : --n) { e = { tag: t.readString(4), checksum: t.readInt(), offset: t.readInt(), length: t.readInt() }, this.tables[e.tag] = e; } } return e.prototype.encode = function (e) { var n, r, i, a, o, s, u, c, h, l, f, d, p; for (p in f = Object.keys(e).length, s = Math.log(2), h = 16 * Math.floor(Math.log(f) / s), a = Math.floor(h / s), c = 16 * f - h, (r = new Rt()).writeInt(this.scalarType), r.writeShort(f), r.writeShort(h), r.writeShort(a), r.writeShort(c), i = 16 * f, u = r.pos + i, o = null, d = [], e) { for (l = e[p], r.writeString(p), r.writeInt(t(l)), r.writeInt(u), r.writeInt(l.length), d = d.concat(l), "head" === p && (o = u), u += l.length; u % 4;) { d.push(0), u++; } } return r.write(d), n = 2981146554 - t(r.data), r.pos = o + 8, r.writeUInt32(n), r.data; }, t = function t(_t2) { var e, n, r, i; for (_t2 = $t.call(_t2); _t2.length % 4;) { _t2.push(0); } for (r = new Rt(_t2), n = 0, e = 0, i = _t2.length; e < i; e = e += 4) { n += r.readUInt32(); } return 4294967295 & n; }, e; }(), Dt = {}.hasOwnProperty, Ut = function Ut(t, e) { for (var n in e) { Dt.call(e, n) && (t[n] = e[n]); } function r() { this.constructor = t; } return r.prototype = e.prototype, t.prototype = new r(), t.__super__ = e.prototype, t; }; qt = function () { function t(t) { var e; this.file = t, e = this.file.directory.tables[this.tag], this.exists = !!e, e && (this.offset = e.offset, this.length = e.length, this.parse(this.file.contents)); } return t.prototype.parse = function () {}, t.prototype.encode = function () {}, t.prototype.raw = function () { return this.exists ? (this.file.contents.pos = this.offset, this.file.contents.read(this.length)) : null; }, t; }(); var zt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "head", e.prototype.parse = function (t) { return t.pos = this.offset, this.version = t.readInt(), this.revision = t.readInt(), this.checkSumAdjustment = t.readInt(), this.magicNumber = t.readInt(), this.flags = t.readShort(), this.unitsPerEm = t.readShort(), this.created = t.readLongLong(), this.modified = t.readLongLong(), this.xMin = t.readShort(), this.yMin = t.readShort(), this.xMax = t.readShort(), this.yMax = t.readShort(), this.macStyle = t.readShort(), this.lowestRecPPEM = t.readShort(), this.fontDirectionHint = t.readShort(), this.indexToLocFormat = t.readShort(), this.glyphDataFormat = t.readShort(); }, e.prototype.encode = function (t) { var e; return (e = new Rt()).writeInt(this.version), e.writeInt(this.revision), e.writeInt(this.checkSumAdjustment), e.writeInt(this.magicNumber), e.writeShort(this.flags), e.writeShort(this.unitsPerEm), e.writeLongLong(this.created), e.writeLongLong(this.modified), e.writeShort(this.xMin), e.writeShort(this.yMin), e.writeShort(this.xMax), e.writeShort(this.yMax), e.writeShort(this.macStyle), e.writeShort(this.lowestRecPPEM), e.writeShort(this.fontDirectionHint), e.writeShort(t), e.writeShort(this.glyphDataFormat), e.data; }, e; }(), Ht = function () { function t(t, e) { var n, r, i, a, o, s, u, c, h, l, f, d, p, g, m, v, b; switch (this.platformID = t.readUInt16(), this.encodingID = t.readShort(), this.offset = e + t.readInt(), h = t.pos, t.pos = this.offset, this.format = t.readUInt16(), this.length = t.readUInt16(), this.language = t.readUInt16(), this.isUnicode = 3 === this.platformID && 1 === this.encodingID && 4 === this.format || 0 === this.platformID && 4 === this.format, this.codeMap = {}, this.format) { case 0: for (s = 0; s < 256; ++s) { this.codeMap[s] = t.readByte(); } break; case 4: for (f = t.readUInt16(), l = f / 2, t.pos += 6, i = function () { var e, n; for (n = [], s = e = 0; 0 <= l ? e < l : e > l; s = 0 <= l ? ++e : --e) { n.push(t.readUInt16()); } return n; }(), t.pos += 2, p = function () { var e, n; for (n = [], s = e = 0; 0 <= l ? e < l : e > l; s = 0 <= l ? ++e : --e) { n.push(t.readUInt16()); } return n; }(), u = function () { var e, n; for (n = [], s = e = 0; 0 <= l ? e < l : e > l; s = 0 <= l ? ++e : --e) { n.push(t.readUInt16()); } return n; }(), c = function () { var e, n; for (n = [], s = e = 0; 0 <= l ? e < l : e > l; s = 0 <= l ? ++e : --e) { n.push(t.readUInt16()); } return n; }(), r = (this.length - t.pos + this.offset) / 2, o = function () { var e, n; for (n = [], s = e = 0; 0 <= r ? e < r : e > r; s = 0 <= r ? ++e : --e) { n.push(t.readUInt16()); } return n; }(), s = m = 0, b = i.length; m < b; s = ++m) { for (g = i[s], n = v = d = p[s]; d <= g ? v <= g : v >= g; n = d <= g ? ++v : --v) { 0 === c[s] ? a = n + u[s] : 0 !== (a = o[c[s] / 2 + (n - d) - (l - s)] || 0) && (a += u[s]), this.codeMap[n] = 65535 & a; } } } t.pos = h; } return t.encode = function (t, e) { var n, r, i, a, o, s, u, c, h, l, f, d, p, g, m, v, b, y, w, N, L, x, A, _, S, P, k, F, I, C, j, B, O, M, E, q, R, T, D, U, z, H, W, V, G, Y; switch (F = new Rt(), a = Object.keys(t).sort(function (t, e) { return t - e; }), e) { case "macroman": for (p = 0, g = function () { var t = []; for (d = 0; d < 256; ++d) { t.push(0); } return t; }(), v = { 0: 0 }, i = {}, I = 0, O = a.length; I < O; I++) { null == v[W = t[r = a[I]]] && (v[W] = ++p), i[r] = { old: t[r], "new": v[t[r]] }, g[r] = v[t[r]]; } return F.writeUInt16(1), F.writeUInt16(0), F.writeUInt32(12), F.writeUInt16(0), F.writeUInt16(262), F.writeUInt16(0), F.write(g), { charMap: i, subtable: F.data, maxGlyphID: p + 1 }; case "unicode": for (P = [], h = [], b = 0, v = {}, n = {}, m = u = null, C = 0, M = a.length; C < M; C++) { null == v[w = t[r = a[C]]] && (v[w] = ++b), n[r] = { old: w, "new": v[w] }, o = v[w] - r, null != m && o === u || (m && h.push(m), P.push(r), u = o), m = r; } for (m && h.push(m), h.push(65535), P.push(65535), _ = 2 * (A = P.length), x = 2 * Math.pow(Math.log(A) / Math.LN2, 2), l = Math.log(x / 2) / Math.LN2, L = 2 * A - x, s = [], N = [], f = [], d = j = 0, E = P.length; j < E; d = ++j) { if (S = P[d], c = h[d], 65535 === S) { s.push(0), N.push(0); break; } if (S - (k = n[S]["new"]) >= 32768) for (s.push(0), N.push(2 * (f.length + A - d)), r = B = S; S <= c ? B <= c : B >= c; r = S <= c ? ++B : --B) { f.push(n[r]["new"]); } else s.push(k - S), N.push(0); } for (F.writeUInt16(3), F.writeUInt16(1), F.writeUInt32(12), F.writeUInt16(4), F.writeUInt16(16 + 8 * A + 2 * f.length), F.writeUInt16(0), F.writeUInt16(_), F.writeUInt16(x), F.writeUInt16(l), F.writeUInt16(L), z = 0, q = h.length; z < q; z++) { r = h[z], F.writeUInt16(r); } for (F.writeUInt16(0), H = 0, R = P.length; H < R; H++) { r = P[H], F.writeUInt16(r); } for (V = 0, T = s.length; V < T; V++) { o = s[V], F.writeUInt16(o); } for (G = 0, D = N.length; G < D; G++) { y = N[G], F.writeUInt16(y); } for (Y = 0, U = f.length; Y < U; Y++) { p = f[Y], F.writeUInt16(p); } return { charMap: n, subtable: F.data, maxGlyphID: b + 1 }; } }, t; }(), Wt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "cmap", e.prototype.parse = function (t) { var e, n, r; for (t.pos = this.offset, this.version = t.readUInt16(), r = t.readUInt16(), this.tables = [], this.unicode = null, n = 0; 0 <= r ? n < r : n > r; n = 0 <= r ? ++n : --n) { e = new Ht(t, this.offset), this.tables.push(e), e.isUnicode && null == this.unicode && (this.unicode = e); } return !0; }, e.encode = function (t, e) { var n, r; return null == e && (e = "macroman"), n = Ht.encode(t, e), (r = new Rt()).writeUInt16(0), r.writeUInt16(1), n.table = r.data.concat(n.subtable), n; }, e; }(), Vt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "hhea", e.prototype.parse = function (t) { return t.pos = this.offset, this.version = t.readInt(), this.ascender = t.readShort(), this.decender = t.readShort(), this.lineGap = t.readShort(), this.advanceWidthMax = t.readShort(), this.minLeftSideBearing = t.readShort(), this.minRightSideBearing = t.readShort(), this.xMaxExtent = t.readShort(), this.caretSlopeRise = t.readShort(), this.caretSlopeRun = t.readShort(), this.caretOffset = t.readShort(), t.pos += 8, this.metricDataFormat = t.readShort(), this.numberOfMetrics = t.readUInt16(); }, e; }(), Gt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "OS/2", e.prototype.parse = function (t) { if (t.pos = this.offset, this.version = t.readUInt16(), this.averageCharWidth = t.readShort(), this.weightClass = t.readUInt16(), this.widthClass = t.readUInt16(), this.type = t.readShort(), this.ySubscriptXSize = t.readShort(), this.ySubscriptYSize = t.readShort(), this.ySubscriptXOffset = t.readShort(), this.ySubscriptYOffset = t.readShort(), this.ySuperscriptXSize = t.readShort(), this.ySuperscriptYSize = t.readShort(), this.ySuperscriptXOffset = t.readShort(), this.ySuperscriptYOffset = t.readShort(), this.yStrikeoutSize = t.readShort(), this.yStrikeoutPosition = t.readShort(), this.familyClass = t.readShort(), this.panose = function () { var e, n; for (n = [], e = 0; e < 10; ++e) { n.push(t.readByte()); } return n; }(), this.charRange = function () { var e, n; for (n = [], e = 0; e < 4; ++e) { n.push(t.readInt()); } return n; }(), this.vendorID = t.readString(4), this.selection = t.readShort(), this.firstCharIndex = t.readShort(), this.lastCharIndex = t.readShort(), this.version > 0 && (this.ascent = t.readShort(), this.descent = t.readShort(), this.lineGap = t.readShort(), this.winAscent = t.readShort(), this.winDescent = t.readShort(), this.codePageRange = function () { var e, n; for (n = [], e = 0; e < 2; e = ++e) { n.push(t.readInt()); } return n; }(), this.version > 1)) return this.xHeight = t.readShort(), this.capHeight = t.readShort(), this.defaultChar = t.readShort(), this.breakChar = t.readShort(), this.maxContext = t.readShort(); }, e; }(), Yt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "post", e.prototype.parse = function (t) { var e, n, r; switch (t.pos = this.offset, this.format = t.readInt(), this.italicAngle = t.readInt(), this.underlinePosition = t.readShort(), this.underlineThickness = t.readShort(), this.isFixedPitch = t.readInt(), this.minMemType42 = t.readInt(), this.maxMemType42 = t.readInt(), this.minMemType1 = t.readInt(), this.maxMemType1 = t.readInt(), this.format) { case 65536: break; case 131072: var i; for (n = t.readUInt16(), this.glyphNameIndex = [], i = 0; 0 <= n ? i < n : i > n; i = 0 <= n ? ++i : --i) { this.glyphNameIndex.push(t.readUInt16()); } for (this.names = [], r = []; t.pos < this.offset + this.length;) { e = t.readByte(), r.push(this.names.push(t.readString(e))); } return r; case 151552: return n = t.readUInt16(), this.offsets = t.read(n); case 196608: break; case 262144: return this.map = function () { var e, n, r; for (r = [], i = e = 0, n = this.file.maxp.numGlyphs; 0 <= n ? e < n : e > n; i = 0 <= n ? ++e : --e) { r.push(t.readUInt32()); } return r; }.call(this); } }, e; }(), Jt = function Jt(t, e) { this.raw = t, this.length = t.length, this.platformID = e.platformID, this.encodingID = e.encodingID, this.languageID = e.languageID; }, Xt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "name", e.prototype.parse = function (t) { var e, n, r, i, a, o, s, u, c, h, l; for (t.pos = this.offset, t.readShort(), e = t.readShort(), o = t.readShort(), n = [], i = 0; 0 <= e ? i < e : i > e; i = 0 <= e ? ++i : --i) { n.push({ platformID: t.readShort(), encodingID: t.readShort(), languageID: t.readShort(), nameID: t.readShort(), length: t.readShort(), offset: this.offset + o + t.readShort() }); } for (s = {}, i = c = 0, h = n.length; c < h; i = ++c) { r = n[i], t.pos = r.offset, u = t.readString(r.length), a = new Jt(u, r), null == s[l = r.nameID] && (s[l] = []), s[r.nameID].push(a); } this.strings = s, this.copyright = s[0], this.fontFamily = s[1], this.fontSubfamily = s[2], this.uniqueSubfamily = s[3], this.fontName = s[4], this.version = s[5]; try { this.postscriptName = s[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g, ""); } catch (t) { this.postscriptName = s[4][0].raw.replace(/[\x00-\x19\x80-\xff]/g, ""); } return this.trademark = s[7], this.manufacturer = s[8], this.designer = s[9], this.description = s[10], this.vendorUrl = s[11], this.designerUrl = s[12], this.license = s[13], this.licenseUrl = s[14], this.preferredFamily = s[15], this.preferredSubfamily = s[17], this.compatibleFull = s[18], this.sampleText = s[19]; }, e; }(), Kt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "maxp", e.prototype.parse = function (t) { return t.pos = this.offset, this.version = t.readInt(), this.numGlyphs = t.readUInt16(), this.maxPoints = t.readUInt16(), this.maxContours = t.readUInt16(), this.maxCompositePoints = t.readUInt16(), this.maxComponentContours = t.readUInt16(), this.maxZones = t.readUInt16(), this.maxTwilightPoints = t.readUInt16(), this.maxStorage = t.readUInt16(), this.maxFunctionDefs = t.readUInt16(), this.maxInstructionDefs = t.readUInt16(), this.maxStackElements = t.readUInt16(), this.maxSizeOfInstructions = t.readUInt16(), this.maxComponentElements = t.readUInt16(), this.maxComponentDepth = t.readUInt16(); }, e; }(), Zt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "hmtx", e.prototype.parse = function (t) { var e, n, r, i, a, o, s; for (t.pos = this.offset, this.metrics = [], e = 0, o = this.file.hhea.numberOfMetrics; 0 <= o ? e < o : e > o; e = 0 <= o ? ++e : --e) { this.metrics.push({ advance: t.readUInt16(), lsb: t.readInt16() }); } for (r = this.file.maxp.numGlyphs - this.file.hhea.numberOfMetrics, this.leftSideBearings = function () { var n, i; for (i = [], e = n = 0; 0 <= r ? n < r : n > r; e = 0 <= r ? ++n : --n) { i.push(t.readInt16()); } return i; }(), this.widths = function () { var t, e, n, r; for (r = [], t = 0, e = (n = this.metrics).length; t < e; t++) { i = n[t], r.push(i.advance); } return r; }.call(this), n = this.widths[this.widths.length - 1], s = [], e = a = 0; 0 <= r ? a < r : a > r; e = 0 <= r ? ++a : --a) { s.push(this.widths.push(n)); } return s; }, e.prototype.forGlyph = function (t) { return t in this.metrics ? this.metrics[t] : { advance: this.metrics[this.metrics.length - 1].advance, lsb: this.leftSideBearings[t - this.metrics.length] }; }, e; }(), $t = [].slice, Qt = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "glyf", e.prototype.parse = function () { return this.cache = {}; }, e.prototype.glyphFor = function (t) { var e, n, r, i, a, o, s, u, c, h; return t in this.cache ? this.cache[t] : (i = this.file.loca, e = this.file.contents, n = i.indexOf(t), 0 === (r = i.lengthOf(t)) ? this.cache[t] = null : (e.pos = this.offset + n, a = (o = new Rt(e.read(r))).readShort(), u = o.readShort(), h = o.readShort(), s = o.readShort(), c = o.readShort(), this.cache[t] = -1 === a ? new ee(o, u, h, s, c) : new te(o, a, u, h, s, c), this.cache[t])); }, e.prototype.encode = function (t, e, n) { var r, i, a, o, s; for (a = [], i = [], o = 0, s = e.length; o < s; o++) { r = t[e[o]], i.push(a.length), r && (a = a.concat(r.encode(n))); } return i.push(a.length), { table: a, offsets: i }; }, e; }(), te = function () { function t(t, e, n, r, i, a) { this.raw = t, this.numberOfContours = e, this.xMin = n, this.yMin = r, this.xMax = i, this.yMax = a, this.compound = !1; } return t.prototype.encode = function () { return this.raw.data; }, t; }(), ee = function () { function t(t, e, n, r, i) { var a, o; for (this.raw = t, this.xMin = e, this.yMin = n, this.xMax = r, this.yMax = i, this.compound = !0, this.glyphIDs = [], this.glyphOffsets = [], a = this.raw; o = a.readShort(), this.glyphOffsets.push(a.pos), this.glyphIDs.push(a.readUInt16()), 32 & o;) { a.pos += 1 & o ? 4 : 2, 128 & o ? a.pos += 8 : 64 & o ? a.pos += 4 : 8 & o && (a.pos += 2); } } return t.prototype.encode = function () { var t, e, n; for (e = new Rt($t.call(this.raw.data)), t = 0, n = this.glyphIDs.length; t < n; ++t) { e.pos = this.glyphOffsets[t]; } return e.data; }, t; }(), ne = function (t) { function e() { return e.__super__.constructor.apply(this, arguments); } return Ut(e, qt), e.prototype.tag = "loca", e.prototype.parse = function (t) { var e, n; return t.pos = this.offset, e = this.file.head.indexToLocFormat, this.offsets = 0 === e ? function () { var e, r; for (r = [], n = 0, e = this.length; n < e; n += 2) { r.push(2 * t.readUInt16()); } return r; }.call(this) : function () { var e, r; for (r = [], n = 0, e = this.length; n < e; n += 4) { r.push(t.readUInt32()); } return r; }.call(this); }, e.prototype.indexOf = function (t) { return this.offsets[t]; }, e.prototype.lengthOf = function (t) { return this.offsets[t + 1] - this.offsets[t]; }, e.prototype.encode = function (t, e) { for (var n = new Uint32Array(this.offsets.length), r = 0, i = 0, a = 0; a < n.length; ++a) { if (n[a] = r, i < e.length && e[i] == a) { ++i, n[a] = r; var o = this.offsets[a], s = this.offsets[a + 1] - o; s > 0 && (r += s); } } for (var u = new Array(4 * n.length), c = 0; c < n.length; ++c) { u[4 * c + 3] = 255 & n[c], u[4 * c + 2] = (65280 & n[c]) >> 8, u[4 * c + 1] = (16711680 & n[c]) >> 16, u[4 * c] = (4278190080 & n[c]) >> 24; } return u; }, e; }(), re$1 = function () { function t(t) { this.font = t, this.subset = {}, this.unicodes = {}, this.next = 33; } return t.prototype.generateCmap = function () { var t, e, n, r, i; for (e in r = this.font.cmap.tables[0].codeMap, t = {}, i = this.subset) { n = i[e], t[e] = r[n]; } return t; }, t.prototype.glyphsFor = function (t) { var e, n, r, i, a, o, s; for (r = {}, a = 0, o = t.length; a < o; a++) { r[i = t[a]] = this.font.glyf.glyphFor(i); } for (i in e = [], r) { (null != (n = r[i]) ? n.compound : void 0) && e.push.apply(e, n.glyphIDs); } if (e.length > 0) for (i in s = this.glyphsFor(e)) { n = s[i], r[i] = n; } return r; }, t.prototype.encode = function (t, e) { var n, r, i, a, o, s, u, c, h, l, f, d, p, g, m; for (r in n = Wt.encode(this.generateCmap(), "unicode"), a = this.glyphsFor(t), f = { 0: 0 }, m = n.charMap) { f[(s = m[r]).old] = s["new"]; } for (d in l = n.maxGlyphID, a) { d in f || (f[d] = l++); } return c = function (t) { var e, n; for (e in n = {}, t) { n[t[e]] = e; } return n; }(f), h = Object.keys(c).sort(function (t, e) { return t - e; }), p = function () { var t, e, n; for (n = [], t = 0, e = h.length; t < e; t++) { o = h[t], n.push(c[o]); } return n; }(), i = this.font.glyf.encode(a, p, f), u = this.font.loca.encode(i.offsets, p), g = { cmap: this.font.cmap.raw(), glyf: i.table, loca: u, hmtx: this.font.hmtx.raw(), hhea: this.font.hhea.raw(), maxp: this.font.maxp.raw(), post: this.font.post.raw(), name: this.font.name.raw(), head: this.font.head.encode(e) }, this.font.os2.exists && (g["OS/2"] = this.font.os2.raw()), this.font.directory.encode(g); }, t; }(); g.API.PDFObject = function () { var t; function e() {} return t = function t(_t3, e) { return (Array(e + 1).join("0") + _t3).slice(-e); }, e.convert = function (n) { var r, i, a, o; if (Array.isArray(n)) return "[" + function () { var t, i, a; for (a = [], t = 0, i = n.length; t < i; t++) { r = n[t], a.push(e.convert(r)); } return a; }().join(" ") + "]"; if ("string" == typeof n) return "/" + n; if (null != n ? n.isString : void 0) return "(" + n + ")"; if (n instanceof Date) return "(D:" + t(n.getUTCFullYear(), 4) + t(n.getUTCMonth(), 2) + t(n.getUTCDate(), 2) + t(n.getUTCHours(), 2) + t(n.getUTCMinutes(), 2) + t(n.getUTCSeconds(), 2) + "Z)"; if ("[object Object]" === {}.toString.call(n)) { for (i in a = ["<<"], n) { o = n[i], a.push("/" + i + " " + e.convert(o)); } return a.push(">>"), a.join("\n"); } return "" + n; }, e; }(), /** * @license * Copyright (c) 2012 chick307 <chick307@gmail.com> * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ function (t, e) { t.API.adler32cs = function () { var t = "function" == typeof ArrayBuffer && "function" == typeof Uint8Array, e = null, n = function () { if (!t) return function () { return !1; }; try { var n = {}; "function" == typeof n.Buffer && (e = n.Buffer); } catch (t) {} return function (t) { return t instanceof ArrayBuffer || null !== e && t instanceof e; }; }(), r = null !== e ? function (t) { return new e(t, "utf8").toString("binary"); } : function (t) { return unescape(encodeURIComponent(t)); }, i = function i(t, e) { for (var n = 65535 & t, r = t >>> 16, i = 0, a = e.length; i < a; i++) { r = (r + (n = (n + (255 & e.charCodeAt(i))) % 65521)) % 65521; } return (r << 16 | n) >>> 0; }, a = function a(t, e) { for (var n = 65535 & t, r = t >>> 16, i = 0, a = e.length; i < a; i++) { r = (r + (n = (n + e[i]) % 65521)) % 65521; } return (r << 16 | n) >>> 0; }, o = {}, s = o.Adler32 = (_l = function l(t) { if (!(this instanceof _l)) throw new TypeError("Constructor cannot called be as a function."); if (!isFinite(t = null === t ? 1 : +t)) throw new Error("First arguments needs to be a finite number."); this.checksum = t >>> 0; }, f = _l.prototype = {}, f.constructor = _l, _l.from = ((u = function u(t) { if (!(this instanceof _l)) throw new TypeError("Constructor cannot called be as a function."); if (null === t) throw new Error("First argument needs to be a string."); this.checksum = i(1, t.toString()); }).prototype = f, u), _l.fromUtf8 = ((c = function c(t) { if (!(this instanceof _l)) throw new TypeError("Constructor cannot called be as a function."); if (null === t) throw new Error("First argument needs to be a string."); var e = r(t.toString()); this.checksum = i(1, e); }).prototype = f, c), t && (_l.fromBuffer = ((h = function h(t) { if (!(this instanceof _l)) throw new TypeError("Constructor cannot called be as a function."); if (!n(t)) throw new Error("First argument needs to be ArrayBuffer."); var e = new Uint8Array(t); return this.checksum = a(1, e); }).prototype = f, h)), f.update = function (t) { if (null === t) throw new Error("First argument needs to be a string."); return t = t.toString(), this.checksum = i(this.checksum, t); }, f.updateUtf8 = function (t) { if (null === t) throw new Error("First argument needs to be a string."); var e = r(t.toString()); return this.checksum = i(this.checksum, e); }, t && (f.updateBuffer = function (t) { if (!n(t)) throw new Error("First argument needs to be ArrayBuffer."); var e = new Uint8Array(t); return this.checksum = a(this.checksum, e); }), f.clone = function () { return new s(this.checksum); }, _l); var u, c, h, _l, f; o.from = function (t) { if (null === t) throw new Error("First argument needs to be a string."); return i(1, t.toString()); }, o.fromUtf8 = function (t) { if (null === t) throw new Error("First argument needs to be a string."); var e = r(t.toString()); return i(1, e); }, t && (o.fromBuffer = function (t) { if (!n(t)) throw new Error("First argument need to be ArrayBuffer."); var e = new Uint8Array(t); return a(1, e); }); return o; }(); }(g); /*! https://mths.be/cssesc v3.0.0 by @mathias */ var object = {}; var hasOwnProperty$1 = object.hasOwnProperty; var merge = function merge(options, defaults) { if (!options) { return defaults; } var result = {}; for (var key in defaults) { // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since // only recognized option names are used. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key]; } return result; }; var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/; var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/; var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g; // https://mathiasbynens.be/notes/css-escapes#css var cssesc = function cssesc(string, options) { options = merge(options, cssesc.options); if (options.quotes != 'single' && options.quotes != 'double') { options.quotes = 'single'; } var quote = options.quotes == 'double' ? '"' : '\''; var isIdentifier = options.isIdentifier; var firstChar = string.charAt(0); var output = ''; var counter = 0; var length = string.length; while (counter < length) { var character = string.charAt(counter++); var codePoint = character.charCodeAt(); var value = void 0; // If it’s not a printable ASCII character… if (codePoint < 0x20 || codePoint > 0x7E) { if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) { // It’s a high surrogate, and there is a next character. var extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // next character is low surrogate codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000; } else { // It’s an unmatched surrogate; only append this code unit, in case // the next code unit is the high surrogate of a surrogate pair. counter--; } } value = '\\' + codePoint.toString(16).toUpperCase() + ' '; } else { if (options.escapeEverything) { if (regexAnySingleEscape.test(character)) { value = '\\' + character; } else { value = '\\' + codePoint.toString(16).toUpperCase() + ' '; } } else if (/[\t\n\f\r\x0B]/.test(character)) { value = '\\' + codePoint.toString(16).toUpperCase() + ' '; } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) { value = '\\' + character; } else { value = character; } } output += value; } if (isIdentifier) { if (/^-[-\d]/.test(output)) { output = '\\-' + output.slice(1); } else if (/\d/.test(firstChar)) { output = '\\3' + firstChar + ' ' + output.slice(1); } } // Remove spaces after `\HEX` escapes that are not followed by a hex digit, // since they’re redundant. Note that this is only possible if the escape // sequence isn’t preceded by an odd number of backslashes. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) { if ($1 && $1.length % 2) { // It’s not safe to remove the space, so don’t. return $0; } // Strip the space. return ($1 || '') + $2; }); if (!isIdentifier && options.wrap) { return quote + output + quote; } return output; }; // Expose default options (so they can be overridden globally). cssesc.options = { 'escapeEverything': false, 'isIdentifier': false, 'quotes': 'single', 'wrap': false }; cssesc.version = '3.0.0'; var cssesc_1 = cssesc; // parse // ===== // states // ------ var PLAIN = 0; var STRINGS = 1; var ESCAPING = 2; var IDENTIFIER = 3; var SEPARATING = 4; var SPACEAFTERIDENTIFIER = 5; // patterns // -------- var identifierPattern = /[a-z0-9_-]/i; var spacePattern = /[\s\t]/; // --- var parse = function parse(str) { // vars // ---- var starting = true; var state = PLAIN; var buffer = ''; var i = 0; var quote; var c; // result // ------ var names = []; // parse // ----- while (true) { c = str[i]; if (state === PLAIN) { if (!c && starting) { break; } else if (!c && !starting) { throw new Error('Parse error'); } else if (c === '"' || c === "'") { quote = c; state = STRINGS; starting = false; } else if (spacePattern.test(c)) ; else if (identifierPattern.test(c)) { state = IDENTIFIER; starting = false; i--; } else { throw new Error('Parse error'); } } else if (state === STRINGS) { if (!c) { throw new Error('Parse Error'); } else if (c === "\\") { state = ESCAPING; } else if (c === quote) { names.push(buffer); buffer = ''; state = SEPARATING; } else { buffer += c; } } else if (state === ESCAPING) { if (c === quote || c === "\\") { buffer += c; state = STRINGS; } else { throw new Error('Parse error'); } } else if (state === IDENTIFIER) { if (!c) { names.push(buffer); break; } else if (identifierPattern.test(c)) { buffer += c; } else if (c === ',') { names.push(buffer); buffer = ''; state = PLAIN; } else if (spacePattern.test(c)) { state = SPACEAFTERIDENTIFIER; } else { throw new Error('Parse error'); } } else if (state === SPACEAFTERIDENTIFIER) { if (!c) { names.push(buffer); break; } else if (identifierPattern.test(c)) { buffer += ' ' + c; state = IDENTIFIER; } else if (c === ',') { names.push(buffer); buffer = ''; state = PLAIN; } else if (spacePattern.test(c)) ; else { throw new Error('Parse error'); } } else if (state === SEPARATING) { if (!c) { break; } else if (c === ',') { state = PLAIN; } else if (spacePattern.test(c)) ; else { throw new Error('Parse error'); } } i++; } // result // ------ return names; }; // stringify // ========= // pattern // ------- var stringsPattern = /[^a-z0-9_-]/i; // --- var stringify = function stringify(names, options) { // quote // ----- var quote = options && options.quote || '"'; if (quote !== '"' && quote !== "'") { throw new Error('Quote must be `\'` or `"`'); } var quotePattern = new RegExp(quote, 'g'); // stringify // --------- var safeNames = []; for (var i = 0; i < names.length; ++i) { var name = names[i]; if (stringsPattern.test(name)) { name = name.replace(/\\/g, "\\\\").replace(quotePattern, "\\" + quote); name = quote + name + quote; } safeNames.push(name); } // result // ------ return safeNames.join(', '); }; // export // ====== var fontFamilyPapandreou = { parse: parse, stringify: stringify }; var paramCounts = { a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0 }; var SPECIAL_SPACES = [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; function isSpace(ch) { return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029 || // Line terminators // White spaces ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && SPECIAL_SPACES.indexOf(ch) >= 0; } function isCommand(code) { /*eslint-disable no-bitwise*/ switch (code | 0x20) { case 0x6D /* m */ : case 0x7A /* z */ : case 0x6C /* l */ : case 0x68 /* h */ : case 0x76 /* v */ : case 0x63 /* c */ : case 0x73 /* s */ : case 0x71 /* q */ : case 0x74 /* t */ : case 0x61 /* a */ : case 0x72 /* r */ : return true; } return false; } function isArc(code) { return (code | 0x20) === 0x61; } function isDigit(code) { return code >= 48 && code <= 57; // 0..9 } function isDigitStart(code) { return code >= 48 && code <= 57 || /* 0..9 */ code === 0x2B || /* + */ code === 0x2D || /* - */ code === 0x2E; /* . */ } function State(path) { this.index = 0; this.path = path; this.max = path.length; this.result = []; this.param = 0.0; this.err = ''; this.segmentStart = 0; this.data = []; } function skipSpaces(state) { while (state.index < state.max && isSpace(state.path.charCodeAt(state.index))) { state.index++; } } function scanFlag(state) { var ch = state.path.charCodeAt(state.index); if (ch === 0x30 /* 0 */ ) { state.param = 0; state.index++; return; } if (ch === 0x31 /* 1 */ ) { state.param = 1; state.index++; return; } state.err = 'SvgPath: arc flag can be 0 or 1 only (at pos ' + state.index + ')'; } function scanParam(state) { var start = state.index, index = start, max = state.max, zeroFirst = false, hasCeiling = false, hasDecimal = false, hasDot = false, ch; if (index >= max) { state.err = 'SvgPath: missed param (at pos ' + index + ')'; return; } ch = state.path.charCodeAt(index); if (ch === 0x2B /* + */ || ch === 0x2D /* - */ ) { index++; ch = index < max ? state.path.charCodeAt(index) : 0; } // This logic is shamelessly borrowed from Esprima // https://github.com/ariya/esprimas // if (!isDigit(ch) && ch !== 0x2E /* . */ ) { state.err = 'SvgPath: param should start with 0..9 or `.` (at pos ' + index + ')'; return; } if (ch !== 0x2E /* . */ ) { zeroFirst = ch === 0x30 /* 0 */ ; index++; ch = index < max ? state.path.charCodeAt(index) : 0; if (zeroFirst && index < max) { // decimal number starts with '0' such as '09' is illegal. if (ch && isDigit(ch)) { state.err = 'SvgPath: numbers started with `0` such as `09` are illegal (at pos ' + start + ')'; return; } } while (index < max && isDigit(state.path.charCodeAt(index))) { index++; hasCeiling = true; } ch = index < max ? state.path.charCodeAt(index) : 0; } if (ch === 0x2E /* . */ ) { hasDot = true; index++; while (isDigit(state.path.charCodeAt(index))) { index++; hasDecimal = true; } ch = index < max ? state.path.charCodeAt(index) : 0; } if (ch === 0x65 /* e */ || ch === 0x45 /* E */ ) { if (hasDot && !hasCeiling && !hasDecimal) { state.err = 'SvgPath: invalid float exponent (at pos ' + index + ')'; return; } index++; ch = index < max ? state.path.charCodeAt(index) : 0; if (ch === 0x2B /* + */ || ch === 0x2D /* - */ ) { index++; } if (index < max && isDigit(state.path.charCodeAt(index))) { while (index < max && isDigit(state.path.charCodeAt(index))) { index++; } } else { state.err = 'SvgPath: invalid float exponent (at pos ' + index + ')'; return; } } state.index = index; state.param = parseFloat(state.path.slice(start, index)) + 0.0; } function finalizeSegment(state) { var cmd, cmdLC; // Process duplicated commands (without comand name) // This logic is shamelessly borrowed from Raphael // https://github.com/DmitryBaranovskiy/raphael/ // cmd = state.path[state.segmentStart]; cmdLC = cmd.toLowerCase(); var params = state.data; if (cmdLC === 'm' && params.length > 2) { state.result.push([cmd, params[0], params[1]]); params = params.slice(2); cmdLC = 'l'; cmd = cmd === 'm' ? 'l' : 'L'; } if (cmdLC === 'r') { state.result.push([cmd].concat(params)); } else { while (params.length >= paramCounts[cmdLC]) { state.result.push([cmd].concat(params.splice(0, paramCounts[cmdLC]))); if (!paramCounts[cmdLC]) { break; } } } } function scanSegment(state) { var max = state.max, cmdCode, is_arc, comma_found, need_params, i; state.segmentStart = state.index; cmdCode = state.path.charCodeAt(state.index); is_arc = isArc(cmdCode); if (!isCommand(cmdCode)) { state.err = 'SvgPath: bad command ' + state.path[state.index] + ' (at pos ' + state.index + ')'; return; } need_params = paramCounts[state.path[state.index].toLowerCase()]; state.index++; skipSpaces(state); state.data = []; if (!need_params) { // Z finalizeSegment(state); return; } comma_found = false; for (;;) { for (i = need_params; i > 0; i--) { if (is_arc && (i === 3 || i === 4)) scanFlag(state);else scanParam(state); if (state.err.length) { return; } state.data.push(state.param); skipSpaces(state); comma_found = false; if (state.index < max && state.path.charCodeAt(state.index) === 0x2C /* , */ ) { state.index++; skipSpaces(state); comma_found = true; } } // after ',' param is mandatory if (comma_found) { continue; } if (state.index >= state.max) { break; } // Stop on next segment if (!isDigitStart(state.path.charCodeAt(state.index))) { break; } } finalizeSegment(state); } /* Returns array of segments: * * [ * [ command, coord1, coord2, ... ] * ] */ var path_parse = function pathParse(svgPath) { var state = new State(svgPath); var max = state.max; skipSpaces(state); while (state.index < max && !state.err.length) { scanSegment(state); } if (state.err.length) { state.result = []; } else if (state.result.length) { if ('mM'.indexOf(state.result[0][0]) < 0) { state.err = 'SvgPath: string should start with `M` or `m`'; state.result = []; } else { state.result[0][0] = 'M'; } } return { err: state.err, segments: state.result }; }; // m1, m2 - [a, b, c, d, e, g] // function combine(m1, m2) { return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]]; } function Matrix() { if (!(this instanceof Matrix)) { return new Matrix(); } this.queue = []; // list of matrixes to apply this.cache = null; // combined matrix cache } Matrix.prototype.matrix = function (m) { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0) { return this; } this.cache = null; this.queue.push(m); return this; }; Matrix.prototype.translate = function (tx, ty) { if (tx !== 0 || ty !== 0) { this.cache = null; this.queue.push([1, 0, 0, 1, tx, ty]); } return this; }; Matrix.prototype.scale = function (sx, sy) { if (sx !== 1 || sy !== 1) { this.cache = null; this.queue.push([sx, 0, 0, sy, 0, 0]); } return this; }; Matrix.prototype.rotate = function (angle, rx, ry) { var rad, cos, sin; if (angle !== 0) { this.translate(rx, ry); rad = angle * Math.PI / 180; cos = Math.cos(rad); sin = Math.sin(rad); this.queue.push([cos, sin, -sin, cos, 0, 0]); this.cache = null; this.translate(-rx, -ry); } return this; }; Matrix.prototype.skewX = function (angle) { if (angle !== 0) { this.cache = null; this.queue.push([1, 0, Math.tan(angle * Math.PI / 180), 1, 0, 0]); } return this; }; Matrix.prototype.skewY = function (angle) { if (angle !== 0) { this.cache = null; this.queue.push([1, Math.tan(angle * Math.PI / 180), 0, 1, 0, 0]); } return this; }; // Flatten queue // Matrix.prototype.toArray = function () { if (this.cache) { return this.cache; } if (!this.queue.length) { this.cache = [1, 0, 0, 1, 0, 0]; return this.cache; } this.cache = this.queue[0]; if (this.queue.length === 1) { return this.cache; } for (var i = 1; i < this.queue.length; i++) { this.cache = combine(this.cache, this.queue[i]); } return this.cache; }; // Apply list of matrixes to (x,y) point. // If `isRelative` set, `translate` component of matrix will be skipped // Matrix.prototype.calc = function (x, y, isRelative) { var m; // Don't change point on empty transforms queue if (!this.queue.length) { return [x, y]; } // Calculate final matrix, if not exists // // NB. if you deside to apply transforms to point one-by-one, // they should be taken in reverse order if (!this.cache) { this.cache = this.toArray(); } m = this.cache; // Apply matrix to point return [x * m[0] + y * m[2] + (isRelative ? 0 : m[4]), x * m[1] + y * m[3] + (isRelative ? 0 : m[5])]; }; var matrix = Matrix; var operations = { matrix: true, scale: true, rotate: true, translate: true, skewX: true, skewY: true }; var CMD_SPLIT_RE = /\s*(matrix|translate|scale|rotate|skewX|skewY)\s*\(\s*(.+?)\s*\)[\s,]*/; var PARAMS_SPLIT_RE = /[\s,]+/; var transform_parse = function transformParse(transformString) { var matrix$1 = new matrix(); var cmd, params; // Split value into ['', 'translate', '10 50', '', 'scale', '2', '', 'rotate', '-45', ''] transformString.split(CMD_SPLIT_RE).forEach(function (item) { // Skip empty elements if (!item.length) { return; } // remember operation if (typeof operations[item] !== 'undefined') { cmd = item; return; } // extract params & att operation to matrix params = item.split(PARAMS_SPLIT_RE).map(function (i) { return +i || 0; }); // If params count is not correct - ignore command switch (cmd) { case 'matrix': if (params.length === 6) { matrix$1.matrix(params); } return; case 'scale': if (params.length === 1) { matrix$1.scale(params[0], params[0]); } else if (params.length === 2) { matrix$1.scale(params[0], params[1]); } return; case 'rotate': if (params.length === 1) { matrix$1.rotate(params[0], 0, 0); } else if (params.length === 3) { matrix$1.rotate(params[0], params[1], params[2]); } return; case 'translate': if (params.length === 1) { matrix$1.translate(params[0], 0); } else if (params.length === 2) { matrix$1.translate(params[0], params[1]); } return; case 'skewX': if (params.length === 1) { matrix$1.skewX(params[0]); } return; case 'skewY': if (params.length === 1) { matrix$1.skewY(params[0]); } return; } }); return matrix$1; }; // Convert an arc to a sequence of cubic bézier curves var TAU = Math.PI * 2; /* eslint-disable space-infix-ops */ // Calculate an angle between two unit vectors // // Since we measure angle between radii of circular arcs, // we can use simplified math (without length normalization) // function unit_vector_angle(ux, uy, vx, vy) { var sign = ux * vy - uy * vx < 0 ? -1 : 1; var dot = ux * vx + uy * vy; // Add this to work with arbitrary vectors: // dot /= Math.sqrt(ux * ux + uy * uy) * Math.sqrt(vx * vx + vy * vy); // rounding errors, e.g. -1.0000000000000002 can screw up this if (dot > 1.0) { dot = 1.0; } if (dot < -1.0) { dot = -1.0; } return sign * Math.acos(dot); } // Convert from endpoint to center parameterization, // see http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // // Return [cx, cy, theta1, delta_theta] // function get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi) { // Step 1. // // Moving an ellipse so origin will be the middlepoint between our two // points. After that, rotate it to line up ellipse axes with coordinate // axes. // var x1p = cos_phi * (x1 - x2) / 2 + sin_phi * (y1 - y2) / 2; var y1p = -sin_phi * (x1 - x2) / 2 + cos_phi * (y1 - y2) / 2; var rx_sq = rx * rx; var ry_sq = ry * ry; var x1p_sq = x1p * x1p; var y1p_sq = y1p * y1p; // Step 2. // // Compute coordinates of the centre of this ellipse (cx', cy') // in the new coordinate system. // var radicant = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq; if (radicant < 0) { // due to rounding errors it might be e.g. -1.3877787807814457e-17 radicant = 0; } radicant /= rx_sq * y1p_sq + ry_sq * x1p_sq; radicant = Math.sqrt(radicant) * (fa === fs ? -1 : 1); var cxp = radicant * rx / ry * y1p; var cyp = radicant * -ry / rx * x1p; // Step 3. // // Transform back to get centre coordinates (cx, cy) in the original // coordinate system. // var cx = cos_phi * cxp - sin_phi * cyp + (x1 + x2) / 2; var cy = sin_phi * cxp + cos_phi * cyp + (y1 + y2) / 2; // Step 4. // // Compute angles (theta1, delta_theta). // var v1x = (x1p - cxp) / rx; var v1y = (y1p - cyp) / ry; var v2x = (-x1p - cxp) / rx; var v2y = (-y1p - cyp) / ry; var theta1 = unit_vector_angle(1, 0, v1x, v1y); var delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y); if (fs === 0 && delta_theta > 0) { delta_theta -= TAU; } if (fs === 1 && delta_theta < 0) { delta_theta += TAU; } return [cx, cy, theta1, delta_theta]; } // // Approximate one unit arc segment with bézier curves, // see http://math.stackexchange.com/questions/873224 // function approximate_unit_arc(theta1, delta_theta) { var alpha = 4 / 3 * Math.tan(delta_theta / 4); var x1 = Math.cos(theta1); var y1 = Math.sin(theta1); var x2 = Math.cos(theta1 + delta_theta); var y2 = Math.sin(theta1 + delta_theta); return [x1, y1, x1 - y1 * alpha, y1 + x1 * alpha, x2 + y2 * alpha, y2 - x2 * alpha, x2, y2]; } var a2c = function a2c(x1, y1, x2, y2, fa, fs, rx, ry, phi) { var sin_phi = Math.sin(phi * TAU / 360); var cos_phi = Math.cos(phi * TAU / 360); // Make sure radii are valid // var x1p = cos_phi * (x1 - x2) / 2 + sin_phi * (y1 - y2) / 2; var y1p = -sin_phi * (x1 - x2) / 2 + cos_phi * (y1 - y2) / 2; if (x1p === 0 && y1p === 0) { // we're asked to draw line to itself return []; } if (rx === 0 || ry === 0) { // one of the radii is zero return []; } // Compensate out-of-range radii // rx = Math.abs(rx); ry = Math.abs(ry); var lambda = x1p * x1p / (rx * rx) + y1p * y1p / (ry * ry); if (lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); } // Get center parameters (cx, cy, theta1, delta_theta) // var cc = get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi); var result = []; var theta1 = cc[2]; var delta_theta = cc[3]; // Split an arc to multiple segments, so each segment // will be less than τ/4 (= 90°) // var segments = Math.max(Math.ceil(Math.abs(delta_theta) / (TAU / 4)), 1); delta_theta /= segments; for (var i = 0; i < segments; i++) { result.push(approximate_unit_arc(theta1, delta_theta)); theta1 += delta_theta; } // We have a bezier approximation of a unit circle, // now need to transform back to the original ellipse // return result.map(function (curve) { for (var i = 0; i < curve.length; i += 2) { var x = curve[i + 0]; var y = curve[i + 1]; // scale x *= rx; y *= ry; // rotate var xp = cos_phi * x - sin_phi * y; var yp = sin_phi * x + cos_phi * y; // translate curve[i + 0] = xp + cc[0]; curve[i + 1] = yp + cc[1]; } return curve; }); }; /* eslint-disable space-infix-ops */ // The precision used to consider an ellipse as a circle // var epsilon = 0.0000000001; // To convert degree in radians // var torad = Math.PI / 180; // Class constructor : // an ellipse centred at 0 with radii rx,ry and x - axis - angle ax. // function Ellipse(rx, ry, ax) { if (!(this instanceof Ellipse)) { return new Ellipse(rx, ry, ax); } this.rx = rx; this.ry = ry; this.ax = ax; } // Apply a linear transform m to the ellipse // m is an array representing a matrix : // - - // | m[0] m[2] | // | m[1] m[3] | // - - // Ellipse.prototype.transform = function (m) { // We consider the current ellipse as image of the unit circle // by first scale(rx,ry) and then rotate(ax) ... // So we apply ma = m x rotate(ax) x scale(rx,ry) to the unit circle. var c = Math.cos(this.ax * torad), s = Math.sin(this.ax * torad); var ma = [this.rx * (m[0] * c + m[2] * s), this.rx * (m[1] * c + m[3] * s), this.ry * (-m[0] * s + m[2] * c), this.ry * (-m[1] * s + m[3] * c)]; // ma * transpose(ma) = [ J L ] // [ L K ] // L is calculated later (if the image is not a circle) var J = ma[0] * ma[0] + ma[2] * ma[2], K = ma[1] * ma[1] + ma[3] * ma[3]; // the discriminant of the characteristic polynomial of ma * transpose(ma) var D = ((ma[0] - ma[3]) * (ma[0] - ma[3]) + (ma[2] + ma[1]) * (ma[2] + ma[1])) * ((ma[0] + ma[3]) * (ma[0] + ma[3]) + (ma[2] - ma[1]) * (ma[2] - ma[1])); // the "mean eigenvalue" var JK = (J + K) / 2; // check if the image is (almost) a circle if (D < epsilon * JK) { // if it is this.rx = this.ry = Math.sqrt(JK); this.ax = 0; return this; } // if it is not a circle var L = ma[0] * ma[1] + ma[2] * ma[3]; D = Math.sqrt(D); // {l1,l2} = the two eigen values of ma * transpose(ma) var l1 = JK + D / 2, l2 = JK - D / 2; // the x - axis - rotation angle is the argument of the l1 - eigenvector /*eslint-disable indent*/ this.ax = Math.abs(L) < epsilon && Math.abs(l1 - K) < epsilon ? 90 : Math.atan(Math.abs(L) > Math.abs(l1 - K) ? (l1 - J) / L : L / (l1 - K)) * 180 / Math.PI; /*eslint-enable indent*/ // if ax > 0 => rx = sqrt(l1), ry = sqrt(l2), else exchange axes and ax += 90 if (this.ax >= 0) { // if ax in [0,90] this.rx = Math.sqrt(l1); this.ry = Math.sqrt(l2); } else { // if ax in ]-90,0[ => exchange axes this.ax += 90; this.rx = Math.sqrt(l2); this.ry = Math.sqrt(l1); } return this; }; // Check if the ellipse is (almost) degenerate, i.e. rx = 0 or ry = 0 // Ellipse.prototype.isDegenerate = function () { return this.rx < epsilon * this.ry || this.ry < epsilon * this.rx; }; var ellipse = Ellipse; // function SvgPath(path) { if (!(this instanceof SvgPath)) { return new SvgPath(path); } var pstate = path_parse(path); // Array of path segments. // Each segment is array [command, param1, param2, ...] this.segments = pstate.segments; // Error message on parse error. this.err = pstate.err; // Transforms stack for lazy evaluation this.__stack = []; } SvgPath.from = function (src) { if (typeof src === 'string') return new SvgPath(src); if (src instanceof SvgPath) { // Create empty object var s = new SvgPath(''); // Clone properies s.err = src.err; s.segments = src.segments.map(function (sgm) { return sgm.slice(); }); s.__stack = src.__stack.map(function (m) { return matrix().matrix(m.toArray()); }); return s; } throw new Error('SvgPath.from: invalid param type ' + src); }; SvgPath.prototype.__matrix = function (m) { var self = this, i; // Quick leave for empty matrix if (!m.queue.length) { return; } this.iterate(function (s, index, x, y) { var p, result, name, isRelative; switch (s[0]) { // Process 'assymetric' commands separately case 'v': p = m.calc(0, s[1], true); result = p[0] === 0 ? ['v', p[1]] : ['l', p[0], p[1]]; break; case 'V': p = m.calc(x, s[1], false); result = p[0] === m.calc(x, y, false)[0] ? ['V', p[1]] : ['L', p[0], p[1]]; break; case 'h': p = m.calc(s[1], 0, true); result = p[1] === 0 ? ['h', p[0]] : ['l', p[0], p[1]]; break; case 'H': p = m.calc(s[1], y, false); result = p[1] === m.calc(x, y, false)[1] ? ['H', p[0]] : ['L', p[0], p[1]]; break; case 'a': case 'A': // ARC is: ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y] // Drop segment if arc is empty (end point === start point) /*if ((s[0] === 'A' && s[6] === x && s[7] === y) || (s[0] === 'a' && s[6] === 0 && s[7] === 0)) { return []; }*/ // Transform rx, ry and the x-axis-rotation var ma = m.toArray(); var e = ellipse(s[1], s[2], s[3]).transform(ma); // flip sweep-flag if matrix is not orientation-preserving if (ma[0] * ma[3] - ma[1] * ma[2] < 0) { s[5] = s[5] ? '0' : '1'; } // Transform end point as usual (without translation for relative notation) p = m.calc(s[6], s[7], s[0] === 'a'); // Empty arcs can be ignored by renderer, but should not be dropped // to avoid collisions with `S A S` and so on. Replace with empty line. if (s[0] === 'A' && s[6] === x && s[7] === y || s[0] === 'a' && s[6] === 0 && s[7] === 0) { result = [s[0] === 'a' ? 'l' : 'L', p[0], p[1]]; break; } // if the resulting ellipse is (almost) a segment ... if (e.isDegenerate()) { // replace the arc by a line result = [s[0] === 'a' ? 'l' : 'L', p[0], p[1]]; } else { // if it is a real ellipse // s[0], s[4] and s[5] are not modified result = [s[0], e.rx, e.ry, e.ax, s[4], s[5], p[0], p[1]]; } break; case 'm': // Edge case. The very first `m` should be processed as absolute, if happens. // Make sense for coord shift transforms. isRelative = index > 0; p = m.calc(s[1], s[2], isRelative); result = ['m', p[0], p[1]]; break; default: name = s[0]; result = [name]; isRelative = name.toLowerCase() === name; // Apply transformations to the segment for (i = 1; i < s.length; i += 2) { p = m.calc(s[i], s[i + 1], isRelative); result.push(p[0], p[1]); } } self.segments[index] = result; }, true); }; // Apply stacked commands // SvgPath.prototype.__evaluateStack = function () { var m, i; if (!this.__stack.length) { return; } if (this.__stack.length === 1) { this.__matrix(this.__stack[0]); this.__stack = []; return; } m = matrix(); i = this.__stack.length; while (--i >= 0) { m.matrix(this.__stack[i].toArray()); } this.__matrix(m); this.__stack = []; }; // Convert processed SVG Path back to string // SvgPath.prototype.toString = function () { var elements = [], skipCmd, cmd; this.__evaluateStack(); for (var i = 0; i < this.segments.length; i++) { // remove repeating commands names cmd = this.segments[i][0]; skipCmd = i > 0 && cmd !== 'm' && cmd !== 'M' && cmd === this.segments[i - 1][0]; elements = elements.concat(skipCmd ? this.segments[i].slice(1) : this.segments[i]); } return elements.join(' ') // Optimizations: remove spaces around commands & before `-` // // We could also remove leading zeros for `0.5`-like values, // but their count is too small to spend time for. .replace(/ ?([achlmqrstvz]) ?/gi, '$1').replace(/ \-/g, '-') // workaround for FontForge SVG importing bug .replace(/zm/g, 'z m'); }; // Translate path to (x [, y]) // SvgPath.prototype.translate = function (x, y) { this.__stack.push(matrix().translate(x, y || 0)); return this; }; // Scale path to (sx [, sy]) // sy = sx if not defined // SvgPath.prototype.scale = function (sx, sy) { this.__stack.push(matrix().scale(sx, !sy && sy !== 0 ? sx : sy)); return this; }; // Rotate path around point (sx [, sy]) // sy = sx if not defined // SvgPath.prototype.rotate = function (angle, rx, ry) { this.__stack.push(matrix().rotate(angle, rx || 0, ry || 0)); return this; }; // Skew path along the X axis by `degrees` angle // SvgPath.prototype.skewX = function (degrees) { this.__stack.push(matrix().skewX(degrees)); return this; }; // Skew path along the Y axis by `degrees` angle // SvgPath.prototype.skewY = function (degrees) { this.__stack.push(matrix().skewY(degrees)); return this; }; // Apply matrix transform (array of 6 elements) // SvgPath.prototype.matrix = function (m) { this.__stack.push(matrix().matrix(m)); return this; }; // Transform path according to "transform" attr of SVG spec // SvgPath.prototype.transform = function (transformString) { if (!transformString.trim()) { return this; } this.__stack.push(transform_parse(transformString)); return this; }; // Round coords with given decimal precition. // 0 by default (to integers) // SvgPath.prototype.round = function (d) { var contourStartDeltaX = 0, contourStartDeltaY = 0, deltaX = 0, deltaY = 0, l; d = d || 0; this.__evaluateStack(); this.segments.forEach(function (s) { var isRelative = s[0].toLowerCase() === s[0]; switch (s[0]) { case 'H': case 'h': if (isRelative) { s[1] += deltaX; } deltaX = s[1] - s[1].toFixed(d); s[1] = +s[1].toFixed(d); return; case 'V': case 'v': if (isRelative) { s[1] += deltaY; } deltaY = s[1] - s[1].toFixed(d); s[1] = +s[1].toFixed(d); return; case 'Z': case 'z': deltaX = contourStartDeltaX; deltaY = contourStartDeltaY; return; case 'M': case 'm': if (isRelative) { s[1] += deltaX; s[2] += deltaY; } deltaX = s[1] - s[1].toFixed(d); deltaY = s[2] - s[2].toFixed(d); contourStartDeltaX = deltaX; contourStartDeltaY = deltaY; s[1] = +s[1].toFixed(d); s[2] = +s[2].toFixed(d); return; case 'A': case 'a': // [cmd, rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y] if (isRelative) { s[6] += deltaX; s[7] += deltaY; } deltaX = s[6] - s[6].toFixed(d); deltaY = s[7] - s[7].toFixed(d); s[1] = +s[1].toFixed(d); s[2] = +s[2].toFixed(d); s[3] = +s[3].toFixed(d + 2); // better precision for rotation s[6] = +s[6].toFixed(d); s[7] = +s[7].toFixed(d); return; default: // a c l q s t l = s.length; if (isRelative) { s[l - 2] += deltaX; s[l - 1] += deltaY; } deltaX = s[l - 2] - s[l - 2].toFixed(d); deltaY = s[l - 1] - s[l - 1].toFixed(d); s.forEach(function (val, i) { if (!i) { return; } s[i] = +s[i].toFixed(d); }); return; } }); return this; }; // Apply iterator function to all segments. If function returns result, // current segment will be replaced to array of returned segments. // If empty array is returned, current regment will be deleted. // SvgPath.prototype.iterate = function (iterator, keepLazyStack) { var segments = this.segments, replacements = {}, needReplace = false, lastX = 0, lastY = 0, countourStartX = 0, countourStartY = 0; var i, j, newSegments; if (!keepLazyStack) { this.__evaluateStack(); } segments.forEach(function (s, index) { var res = iterator(s, index, lastX, lastY); if (Array.isArray(res)) { replacements[index] = res; needReplace = true; } var isRelative = s[0] === s[0].toLowerCase(); // calculate absolute X and Y switch (s[0]) { case 'm': case 'M': lastX = s[1] + (isRelative ? lastX : 0); lastY = s[2] + (isRelative ? lastY : 0); countourStartX = lastX; countourStartY = lastY; return; case 'h': case 'H': lastX = s[1] + (isRelative ? lastX : 0); return; case 'v': case 'V': lastY = s[1] + (isRelative ? lastY : 0); return; case 'z': case 'Z': // That make sence for multiple contours lastX = countourStartX; lastY = countourStartY; return; default: lastX = s[s.length - 2] + (isRelative ? lastX : 0); lastY = s[s.length - 1] + (isRelative ? lastY : 0); } }); // Replace segments if iterator return results if (!needReplace) { return this; } newSegments = []; for (i = 0; i < segments.length; i++) { if (typeof replacements[i] !== 'undefined') { for (j = 0; j < replacements[i].length; j++) { newSegments.push(replacements[i][j]); } } else { newSegments.push(segments[i]); } } this.segments = newSegments; return this; }; // Converts segments from relative to absolute // SvgPath.prototype.abs = function () { this.iterate(function (s, index, x, y) { var name = s[0], nameUC = name.toUpperCase(), i; // Skip absolute commands if (name === nameUC) { return; } s[0] = nameUC; switch (name) { case 'v': // v has shifted coords parity s[1] += y; return; case 'a': // ARC is: ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y] // touch x, y only s[6] += x; s[7] += y; return; default: for (i = 1; i < s.length; i++) { s[i] += i % 2 ? x : y; // odd values are X, even - Y } } }, true); return this; }; // Converts segments from absolute to relative // SvgPath.prototype.rel = function () { this.iterate(function (s, index, x, y) { var name = s[0], nameLC = name.toLowerCase(), i; // Skip relative commands if (name === nameLC) { return; } // Don't touch the first M to avoid potential confusions. if (index === 0 && name === 'M') { return; } s[0] = nameLC; switch (name) { case 'V': // V has shifted coords parity s[1] -= y; return; case 'A': // ARC is: ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y] // touch x, y only s[6] -= x; s[7] -= y; return; default: for (i = 1; i < s.length; i++) { s[i] -= i % 2 ? x : y; // odd values are X, even - Y } } }, true); return this; }; // Converts arcs to cubic bézier curves // SvgPath.prototype.unarc = function () { this.iterate(function (s, index, x, y) { var new_segments, nextX, nextY, result = [], name = s[0]; // Skip anything except arcs if (name !== 'A' && name !== 'a') { return null; } if (name === 'a') { // convert relative arc coordinates to absolute nextX = x + s[6]; nextY = y + s[7]; } else { nextX = s[6]; nextY = s[7]; } new_segments = a2c(x, y, nextX, nextY, s[4], s[5], s[1], s[2], s[3]); // Degenerated arcs can be ignored by renderer, but should not be dropped // to avoid collisions with `S A S` and so on. Replace with empty line. if (new_segments.length === 0) { return [[s[0] === 'a' ? 'l' : 'L', s[6], s[7]]]; } new_segments.forEach(function (s) { result.push(['C', s[2], s[3], s[4], s[5], s[6], s[7]]); }); return result; }); return this; }; // Converts smooth curves (with missed control point) to generic curves // SvgPath.prototype.unshort = function () { var segments = this.segments; var prevControlX, prevControlY, prevSegment; var curControlX, curControlY; // TODO: add lazy evaluation flag when relative commands supported this.iterate(function (s, idx, x, y) { var name = s[0], nameUC = name.toUpperCase(), isRelative; // First command MUST be M|m, it's safe to skip. // Protect from access to [-1] for sure. if (!idx) { return; } if (nameUC === 'T') { // quadratic curve isRelative = name === 't'; prevSegment = segments[idx - 1]; if (prevSegment[0] === 'Q') { prevControlX = prevSegment[1] - x; prevControlY = prevSegment[2] - y; } else if (prevSegment[0] === 'q') { prevControlX = prevSegment[1] - prevSegment[3]; prevControlY = prevSegment[2] - prevSegment[4]; } else { prevControlX = 0; prevControlY = 0; } curControlX = -prevControlX; curControlY = -prevControlY; if (!isRelative) { curControlX += x; curControlY += y; } segments[idx] = [isRelative ? 'q' : 'Q', curControlX, curControlY, s[1], s[2]]; } else if (nameUC === 'S') { // cubic curve isRelative = name === 's'; prevSegment = segments[idx - 1]; if (prevSegment[0] === 'C') { prevControlX = prevSegment[3] - x; prevControlY = prevSegment[4] - y; } else if (prevSegment[0] === 'c') { prevControlX = prevSegment[3] - prevSegment[5]; prevControlY = prevSegment[4] - prevSegment[6]; } else { prevControlX = 0; prevControlY = 0; } curControlX = -prevControlX; curControlY = -prevControlY; if (!isRelative) { curControlX += x; curControlY += y; } segments[idx] = [isRelative ? 'c' : 'C', curControlX, curControlY, s[1], s[2], s[3], s[4]]; } }); return this; }; var svgpath = SvgPath; var svgpath$1 = svgpath; // Calculate the specificity for a selector by dividing it into simple selectors and counting them /** * Calculates the specificity of CSS selectors * http://www.w3.org/TR/css3-selectors/#specificity * * Returns an object with the following properties: * - selector: the input * - specificity: e.g. 0,1,0,0 * - parts: array with details about each part of the selector that counts towards the specificity * - specificityArray: e.g. [0, 1, 0, 0] */ var calculateSingle = function calculateSingle(input) { var selector = input, findMatch, typeCount = { 'a': 0, 'b': 0, 'c': 0 }, parts = [], // The following regular expressions assume that selectors matching the preceding regular expressions have been removed attributeRegex = /(\[[^\]]+\])/g, idRegex = /(#[^\#\s\+>~\.\[:\)]+)/g, classRegex = /(\.[^\s\+>~\.\[:\)]+)/g, pseudoElementRegex = /(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi, // A regex for pseudo classes with brackets - :nth-child(), :nth-last-child(), :nth-of-type(), :nth-last-type(), :lang() // The negation psuedo class (:not) is filtered out because specificity is calculated on its argument // :global and :local are filtered out - they look like psuedo classes but are an identifier for CSS Modules pseudoClassWithBracketsRegex = /(:(?!not|global|local)[\w-]+\([^\)]*\))/gi, // A regex for other pseudo classes, which don't have brackets pseudoClassRegex = /(:(?!not|global|local)[^\s\+>~\.\[:]+)/g, elementRegex = /([^\s\+>~\.\[:]+)/g; // Find matches for a regular expression in a string and push their details to parts // Type is "a" for IDs, "b" for classes, attributes and pseudo-classes and "c" for elements and pseudo-elements findMatch = function findMatch(regex, type) { var matches, i, len, match, index, length; if (regex.test(selector)) { matches = selector.match(regex); for (i = 0, len = matches.length; i < len; i += 1) { typeCount[type] += 1; match = matches[i]; index = selector.indexOf(match); length = match.length; parts.push({ selector: input.substr(index, length), type: type, index: index, length: length }); // Replace this simple selector with whitespace so it won't be counted in further simple selectors selector = selector.replace(match, Array(length + 1).join(' ')); } } }; // Replace escaped characters with plain text, using the "A" character // https://www.w3.org/TR/CSS21/syndata.html#characters (function () { var replaceWithPlainText = function replaceWithPlainText(regex) { var matches, i, len, match; if (regex.test(selector)) { matches = selector.match(regex); for (i = 0, len = matches.length; i < len; i += 1) { match = matches[i]; selector = selector.replace(match, Array(match.length + 1).join('A')); } } }, // Matches a backslash followed by six hexadecimal digits followed by an optional single whitespace character escapeHexadecimalRegex = /\\[0-9A-Fa-f]{6}\s?/g, // Matches a backslash followed by fewer than six hexadecimal digits followed by a mandatory single whitespace character escapeHexadecimalRegex2 = /\\[0-9A-Fa-f]{1,5}\s/g, // Matches a backslash followed by any character escapeSpecialCharacter = /\\./g; replaceWithPlainText(escapeHexadecimalRegex); replaceWithPlainText(escapeHexadecimalRegex2); replaceWithPlainText(escapeSpecialCharacter); })(); // Remove anything after a left brace in case a user has pasted in a rule, not just a selector (function () { var regex = /{[^]*/gm, matches, i, len, match; if (regex.test(selector)) { matches = selector.match(regex); for (i = 0, len = matches.length; i < len; i += 1) { match = matches[i]; selector = selector.replace(match, Array(match.length + 1).join(' ')); } } })(); // Add attribute selectors to parts collection (type b) findMatch(attributeRegex, 'b'); // Add ID selectors to parts collection (type a) findMatch(idRegex, 'a'); // Add class selectors to parts collection (type b) findMatch(classRegex, 'b'); // Add pseudo-element selectors to parts collection (type c) findMatch(pseudoElementRegex, 'c'); // Add pseudo-class selectors to parts collection (type b) findMatch(pseudoClassWithBracketsRegex, 'b'); findMatch(pseudoClassRegex, 'b'); // Remove universal selector and separator characters selector = selector.replace(/[\*\s\+>~]/g, ' '); // Remove any stray dots or hashes which aren't attached to words // These may be present if the user is live-editing this selector selector = selector.replace(/[#\.]/g, ' '); // Remove the negation psuedo-class (:not) but leave its argument because specificity is calculated on its argument // Remove non-standard :local and :global CSS Module identifiers because they do not effect the specificity selector = selector.replace(/:not/g, ' '); selector = selector.replace(/:local/g, ' '); selector = selector.replace(/:global/g, ' '); selector = selector.replace(/[\(\)]/g, ' '); // The only things left should be element selectors (type c) findMatch(elementRegex, 'c'); // Order the parts in the order they appear in the original selector // This is neater for external apps to deal with parts.sort(function (a, b) { return a.index - b.index; }); return { selector: input, specificity: '0,' + typeCount.a.toString() + ',' + typeCount.b.toString() + ',' + typeCount.c.toString(), specificityArray: [0, typeCount.a, typeCount.b, typeCount.c], parts: parts }; }; /** * Compares two CSS selectors for specificity * Alternatively you can replace one of the CSS selectors with a specificity array * * - it returns -1 if a has a lower specificity than b * - it returns 1 if a has a higher specificity than b * - it returns 0 if a has the same specificity than b */ var compare = function compare(a, b) { var aSpecificity, bSpecificity, i; if (typeof a === 'string') { if (a.indexOf(',') !== -1) { throw 'Invalid CSS selector'; } else { aSpecificity = calculateSingle(a)['specificityArray']; } } else if (Array.isArray(a)) { if (a.filter(function (e) { return typeof e === 'number'; }).length !== 4) { throw 'Invalid specificity array'; } else { aSpecificity = a; } } else { throw 'Invalid CSS selector or specificity array'; } if (typeof b === 'string') { if (b.indexOf(',') !== -1) { throw 'Invalid CSS selector'; } else { bSpecificity = calculateSingle(b)['specificityArray']; } } else if (Array.isArray(b)) { if (b.filter(function (e) { return typeof e === 'number'; }).length !== 4) { throw 'Invalid specificity array'; } else { bSpecificity = b; } } else { throw 'Invalid CSS selector or specificity array'; } for (i = 0; i < 4; i += 1) { if (aSpecificity[i] < bSpecificity[i]) { return -1; } else if (aSpecificity[i] > bSpecificity[i]) { return 1; } } return 0; }; /*! ***************************************************************************** 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 */ var _extendStatics = function extendStatics(d, b) { _extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) d[p] = b[p]; } }; return _extendStatics(d, b); }; function __extends(d, b) { _extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var _assign = function __assign() { _assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } } return t; }; return _assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function sent() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) { try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var RGBColor$1 = /** @class */ function () { function RGBColor(colorString) { this.a = undefined; this.r = 0; this.g = 0; this.b = 0; this.simpleColors = {}; this.colorDefs = []; this.ok = false; if (!colorString) { return; } // strip any leading # if (colorString.charAt(0) == '#') { // remove # if any colorString = colorString.substr(1, 6); } colorString = colorString.replace(/ /g, ''); colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches // and overwrite the input this.simpleColors = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000', blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgrey: 'a9a9a9', darkgreen: '006400', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkslategrey: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dimgrey: '696969', dodgerblue: '1e90ff', feldspar: 'd19275', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', grey: '808080', green: '008000', greenyellow: 'adff2f', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred: 'cd5c5c', indigo: '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgray: 'd3d3d3', lightgrey: 'd3d3d3', lightgreen: '90ee90', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslateblue: '8470ff', lightslategray: '778899', lightslategrey: '778899', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370d8', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'd87093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', slategrey: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', violetred: 'd02090', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5', yellow: 'ffff00', yellowgreen: '9acd32' }; for (var key in this.simpleColors) { if (colorString == key) { colorString = this.simpleColors[key]; } } // emd of simple type-in colors // array of color definition objects this.colorDefs = [{ re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], process: function process(bits) { return [parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3])]; } }, { re: /^(\w{2})(\w{2})(\w{2})$/, example: ['#00ff00', '336699'], process: function process(bits) { return [parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16)]; } }, { re: /^(\w{1})(\w{1})(\w{1})$/, example: ['#fb0', 'f0f'], process: function process(bits) { return [parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16)]; } }]; // search through the definitions to find a match for (var i = 0; i < this.colorDefs.length; i++) { var re = this.colorDefs[i].re; var processor = this.colorDefs[i].process; var bits = re.exec(colorString); if (bits) { var channels = processor(bits); this.r = channels[0]; this.g = channels[1]; this.b = channels[2]; this.ok = true; } } // validate/cleanup values this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r; this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g; this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b; } RGBColor.prototype.toRGB = function () { return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; }; RGBColor.prototype.toHex = function () { var r = this.r.toString(16); var g = this.g.toString(16); var b = this.b.toString(16); if (r.length == 1) r = '0' + r; if (g.length == 1) g = '0' + g; if (b.length == 1) b = '0' + b; return '#' + r + g + b; }; // help RGBColor.prototype.getHelpXML = function () { var examples = []; // add regexps for (var i = 0; i < this.colorDefs.length; i++) { var example = this.colorDefs[i].example; for (var j = 0; j < example.length; j++) { examples[examples.length] = example[j]; } } // add type-in colors for (var sc in this.simpleColors) { examples[examples.length] = sc; } var xml = document.createElement('ul'); xml.setAttribute('id', 'rgbcolor-examples'); for (var i = 0; i < examples.length; i++) { try { var listItem = document.createElement('li'); var listColor = new RGBColor(examples[i]); var exampleDiv = document.createElement('div'); exampleDiv.style.cssText = 'margin: 3px; ' + 'border: 1px solid black; ' + 'background:' + listColor.toHex() + '; ' + 'color:' + listColor.toHex(); exampleDiv.appendChild(document.createTextNode('test')); var listItemValue = document.createTextNode(' ' + examples[i] + ' -> ' + listColor.toRGB() + ' -> ' + listColor.toHex()); listItem.appendChild(exampleDiv); listItem.appendChild(listItemValue); xml.appendChild(listItem); } catch (e) {} } return xml; }; return RGBColor; }(); var ColorFill = /** @class */ function () { function ColorFill(color) { this.color = color; } ColorFill.prototype.getFillData = function (forNode, context) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/ , undefined]; }); }); }; return ColorFill; }(); var AttributeState = /** @class */ function () { function AttributeState() { this.xmlSpace = ''; this.fill = null; this.fillOpacity = 1.0; // public fillRule: string = null this.fontFamily = ''; this.fontSize = 16; this.fontStyle = ''; // public fontVariant: string this.fontWeight = ''; this.opacity = 1.0; this.stroke = null; this.strokeDasharray = null; this.strokeDashoffset = 0; this.strokeLinecap = ''; this.strokeLinejoin = ''; this.strokeMiterlimit = 4.0; this.strokeOpacity = 1.0; this.strokeWidth = 1.0; // public textAlign: string this.alignmentBaseline = ''; this.textAnchor = ''; this.visibility = ''; } AttributeState.prototype.clone = function () { var clone = new AttributeState(); clone.xmlSpace = this.xmlSpace; clone.fill = this.fill; clone.fillOpacity = this.fillOpacity; // clone.fillRule = this.fillRule; clone.fontFamily = this.fontFamily; clone.fontSize = this.fontSize; clone.fontStyle = this.fontStyle; // clone.fontVariant = this.fontVariant; clone.fontWeight = this.fontWeight; clone.opacity = this.opacity; clone.stroke = this.stroke; clone.strokeDasharray = this.strokeDasharray; clone.strokeDashoffset = this.strokeDashoffset; clone.strokeLinecap = this.strokeLinecap; clone.strokeLinejoin = this.strokeLinejoin; clone.strokeMiterlimit = this.strokeMiterlimit; clone.strokeOpacity = this.strokeOpacity; clone.strokeWidth = this.strokeWidth; // clone.textAlign = this.textAlign; clone.textAnchor = this.textAnchor; clone.alignmentBaseline = this.alignmentBaseline; clone.visibility = this.visibility; return clone; }; AttributeState["default"] = function () { var attributeState = new AttributeState(); attributeState.xmlSpace = 'default'; attributeState.fill = new ColorFill(new RGBColor$1('rgb(0, 0, 0)')); attributeState.fillOpacity = 1.0; // attributeState.fillRule = "nonzero"; attributeState.fontFamily = 'times'; attributeState.fontSize = 16; attributeState.fontStyle = 'normal'; // attributeState.fontVariant = "normal"; attributeState.fontWeight = 'normal'; attributeState.opacity = 1.0; attributeState.stroke = null; attributeState.strokeDasharray = null; attributeState.strokeDashoffset = 0; attributeState.strokeLinecap = 'butt'; attributeState.strokeLinejoin = 'miter'; attributeState.strokeMiterlimit = 4.0; attributeState.strokeOpacity = 1.0; attributeState.strokeWidth = 1.0; // attributeState.textAlign = "start"; attributeState.alignmentBaseline = 'baseline'; attributeState.textAnchor = 'start'; attributeState.visibility = 'visible'; return attributeState; }; return AttributeState; }(); var iriReference = /url\(["']?#([^"']+)["']?\)/; var alignmentBaselineMap = { bottom: 'bottom', 'text-bottom': 'bottom', top: 'top', 'text-top': 'top', hanging: 'hanging', middle: 'middle', central: 'middle', center: 'middle', mathematical: 'middle', ideographic: 'ideographic', alphabetic: 'alphabetic', baseline: 'alphabetic' }; var svgNamespaceURI = 'http://www.w3.org/2000/svg'; var TextMeasure = /** @class */ function () { function TextMeasure() { this.measureMethods = {}; } TextMeasure.prototype.getTextOffset = function (text, attributeState) { var textAnchor = attributeState.textAnchor; if (textAnchor === 'start') { return 0; } var width = this.measureTextWidth(text, attributeState); var xOffset = 0; switch (textAnchor) { case 'end': xOffset = width; break; case 'middle': xOffset = width / 2; break; } return xOffset; }; TextMeasure.prototype.measureTextWidth = function (text, attributeState) { if (text.length === 0) { return 0; } var fontFamily = attributeState.fontFamily; var measure = this.getMeasureFunction(fontFamily); return measure.call(this, text, attributeState.fontFamily, attributeState.fontSize + 'px', attributeState.fontStyle, attributeState.fontWeight); }; TextMeasure.prototype.getMeasurementTextNode = function () { if (!this.textMeasuringTextElement) { this.textMeasuringTextElement = document.createElementNS(svgNamespaceURI, 'text'); var svg = document.createElementNS(svgNamespaceURI, 'svg'); svg.appendChild(this.textMeasuringTextElement); svg.style.setProperty('position', 'absolute'); svg.style.setProperty('visibility', 'hidden'); document.body.appendChild(svg); } return this.textMeasuringTextElement; }; TextMeasure.prototype.canvasTextMeasure = function (text, fontFamily, fontSize, fontStyle, fontWeight) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); if (context != null) { context.font = [fontStyle, fontWeight, fontSize, fontFamily].join(' '); return context.measureText(text).width; } return 0; }; TextMeasure.prototype.svgTextMeasure = function (text, fontFamily, fontSize, fontStyle, fontWeight, measurementTextNode) { if (measurementTextNode === void 0) { measurementTextNode = this.getMeasurementTextNode(); } var textNode = measurementTextNode; textNode.setAttribute('font-family', fontFamily); textNode.setAttribute('font-size', fontSize); textNode.setAttribute('font-style', fontStyle); textNode.setAttribute('font-weight', fontWeight); textNode.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve'); textNode.textContent = text; return textNode.getBBox().width; }; /** * Canvas text measuring is a lot faster than svg measuring. However, it is inaccurate for some fonts. So test each * font once and decide if canvas is accurate enough. */ TextMeasure.prototype.getMeasureFunction = function (fontFamily) { var method = this.measureMethods[fontFamily]; if (!method) { var fontSize = '16px'; var fontStyle = 'normal'; var fontWeight = 'normal'; var canvasWidth = this.canvasTextMeasure(TextMeasure.testString, fontFamily, fontSize, fontStyle, fontWeight); var svgWidth = this.svgTextMeasure(TextMeasure.testString, fontFamily, fontSize, fontStyle, fontWeight); method = Math.abs(canvasWidth - svgWidth) < TextMeasure.epsilon ? this.canvasTextMeasure : this.svgTextMeasure; this.measureMethods[fontFamily] = method; } return method; }; TextMeasure.prototype.cleanupTextMeasuring = function () { if (this.textMeasuringTextElement) { var parentNode = this.textMeasuringTextElement.parentNode; if (parentNode) { document.body.removeChild(parentNode); } this.textMeasuringTextElement = undefined; } }; TextMeasure.testString = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789!"$%&/()=?\'\\+*-_.:,;^}][{#~|<>'; TextMeasure.epsilon = 0.1; return TextMeasure; }(); /** * * @package * @param values * @constructor * @property pdf * @property attributeState Keeps track of parent attributes that are inherited automatically * @property refsHandler The handler that will render references on demand * @property styleSheets * @property textMeasure * @property transform The current transformation matrix * @property withinClipPath */ var Context = /** @class */ function () { function Context(pdf, values) { var _a, _b, _c, _d, _e, _f; this.pdf = pdf; this.svg2pdfParameters = values.svg2pdfParameters; this.attributeState = values.attributeState ? values.attributeState.clone() : AttributeState["default"](); this.viewport = values.viewport; this.refsHandler = (_a = values.refsHandler) !== null && _a !== void 0 ? _a : null; this.styleSheets = (_b = values.styleSheets) !== null && _b !== void 0 ? _b : null; this.textMeasure = (_c = values.textMeasure) !== null && _c !== void 0 ? _c : new TextMeasure(); this.transform = (_d = values.transform) !== null && _d !== void 0 ? _d : this.pdf.unitMatrix; this.withinClipPath = (_e = values.withinClipPath) !== null && _e !== void 0 ? _e : false; this.withinUse = (_f = values.withinUse) !== null && _f !== void 0 ? _f : false; } Context.prototype.clone = function (values) { var _a, _b, _c, _d, _e, _f, _g, _h; if (values === void 0) { values = {}; } return new Context(this.pdf, { svg2pdfParameters: (_a = values.svg2pdfParameters) !== null && _a !== void 0 ? _a : this.svg2pdfParameters, attributeState: values.attributeState ? values.attributeState.clone() : this.attributeState.clone(), viewport: (_b = values.viewport) !== null && _b !== void 0 ? _b : this.viewport, refsHandler: (_c = values.refsHandler) !== null && _c !== void 0 ? _c : this.refsHandler, styleSheets: (_d = values.styleSheets) !== null && _d !== void 0 ? _d : this.styleSheets, textMeasure: (_e = values.textMeasure) !== null && _e !== void 0 ? _e : this.textMeasure, transform: (_f = values.transform) !== null && _f !== void 0 ? _f : this.transform, withinClipPath: (_g = values.withinClipPath) !== null && _g !== void 0 ? _g : this.withinClipPath, withinUse: (_h = values.withinUse) !== null && _h !== void 0 ? _h : this.withinUse }); }; return Context; }(); var ReferencesHandler = /** @class */ function () { function ReferencesHandler(idMap) { this.renderedElements = {}; this.idMap = idMap; } ReferencesHandler.prototype.getRendered = function (id, renderCallback) { return __awaiter(this, void 0, void 0, function () { var svgNode; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.renderedElements.hasOwnProperty(id)) { return [2 /*return*/ , this.renderedElements[id]]; } svgNode = this.get(id); this.renderedElements[id] = svgNode; return [4 /*yield*/ , renderCallback(svgNode)]; case 1: _a.sent(); return [2 /*return*/ , svgNode]; } }); }); }; ReferencesHandler.prototype.get = function (id) { return this.idMap[cssesc_1(id, { isIdentifier: true })]; }; return ReferencesHandler; }(); function getAngle(from, to) { return Math.atan2(to[1] - from[1], to[0] - from[0]); } var cToQ = 2 / 3; // ratio to convert quadratic bezier curves to cubic ones // transforms a cubic bezier control point to a quadratic one: returns from + (2/3) * (to - from) function toCubic(from, to) { return [cToQ * (to[0] - from[0]) + from[0], cToQ * (to[1] - from[1]) + from[1]]; } function normalize$1(v) { var length = Math.sqrt(v[0] * v[0] + v[1] * v[1]); return [v[0] / length, v[1] / length]; } function getDirectionVector(from, to) { var v = [to[0] - from[0], to[1] - from[1]]; return normalize$1(v); } function addVectors(v1, v2) { return [v1[0] + v2[0], v1[1] + v2[1]]; } // multiplies a vector with a matrix: vec' = vec * matrix function multVecMatrix(vec, matrix) { var x = vec[0]; var y = vec[1]; return [matrix.a * x + matrix.c * y + matrix.e, matrix.b * x + matrix.d * y + matrix.f]; } var Path = /** @class */ function () { function Path() { this.segments = []; } Path.prototype.moveTo = function (x, y) { this.segments.push(new MoveTo(x, y)); return this; }; Path.prototype.lineTo = function (x, y) { this.segments.push(new LineTo(x, y)); return this; }; Path.prototype.curveTo = function (x1, y1, x2, y2, x, y) { this.segments.push(new CurveTo(x1, y1, x2, y2, x, y)); return this; }; Path.prototype.close = function () { this.segments.push(new Close()); return this; }; /** * Transforms the path in place */ Path.prototype.transform = function (matrix) { this.segments.forEach(function (seg) { if (seg instanceof MoveTo || seg instanceof LineTo || seg instanceof CurveTo) { var p = multVecMatrix([seg.x, seg.y], matrix); seg.x = p[0]; seg.y = p[1]; } if (seg instanceof CurveTo) { var p1 = multVecMatrix([seg.x1, seg.y1], matrix); var p2 = multVecMatrix([seg.x2, seg.y2], matrix); seg.x1 = p1[0]; seg.y1 = p1[1]; seg.x2 = p2[0]; seg.y2 = p2[1]; } }); }; Path.prototype.draw = function (context) { var p = context.pdf; this.segments.forEach(function (s) { if (s instanceof MoveTo) { p.moveTo(s.x, s.y); } else if (s instanceof LineTo) { p.lineTo(s.x, s.y); } else if (s instanceof CurveTo) { p.curveTo(s.x1, s.y1, s.x2, s.y2, s.x, s.y); } else { p.close(); } }); }; return Path; }(); var MoveTo = /** @class */ function () { function MoveTo(x, y) { this.x = x; this.y = y; } return MoveTo; }(); var LineTo = /** @class */ function () { function LineTo(x, y) { this.x = x; this.y = y; } return LineTo; }(); var CurveTo = /** @class */ function () { function CurveTo(x1, y1, x2, y2, x, y) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.x = x; this.y = y; } return CurveTo; }(); var Close = /** @class */ function () { function Close() {} return Close; }(); function nodeIs(node, tagsString) { return tagsString.split(',').indexOf((node.nodeName || node.tagName).toLowerCase()) >= 0; } function forEachChild(node, fn) { // copy list of children, as the original might be modified var children = []; for (var i = 0; i < node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeName.charAt(0) !== '#') children.push(childNode); } for (var i = 0; i < children.length; i++) { fn(i, children[i]); } } // returns an attribute of a node, either from the node directly or from css function getAttribute(node, styleSheets, propertyNode, propertyCss) { if (propertyCss === void 0) { propertyCss = propertyNode; } var attribute = node.style.getPropertyValue(propertyCss); if (attribute) { return attribute; } else if (styleSheets.getPropertyValue(node, propertyCss)) { return styleSheets.getPropertyValue(node, propertyCss); } else if (node.hasAttribute(propertyNode)) { return node.getAttribute(propertyNode) || undefined; } else { return undefined; } } function svgNodeIsVisible(svgNode, parentVisible, context) { if (getAttribute(svgNode.element, context.styleSheets, 'display') === 'none') { return false; } var visible = parentVisible; var visibility = getAttribute(svgNode.element, context.styleSheets, 'visibility'); if (visibility) { visible = visibility !== 'hidden'; } return visible; } function svgNodeAndChildrenVisible(svgNode, parentVisible, context) { var visible = svgNodeIsVisible(svgNode, parentVisible, context); if (svgNode.element.childNodes.length === 0) { return false; } svgNode.children.forEach(function (child) { if (child.isVisible(visible, context)) { visible = true; } }); return visible; } /** * @constructor * @property {Marker[]} markers */ var MarkerList = /** @class */ function () { function MarkerList() { this.markers = []; } MarkerList.prototype.addMarker = function (markers) { this.markers.push(markers); }; MarkerList.prototype.draw = function (context) { return __awaiter(this, void 0, void 0, function () { var i, marker, tf, angle, anchor, cos, sin; return __generator(this, function (_a) { switch (_a.label) { case 0: i = 0; _a.label = 1; case 1: if (!(i < this.markers.length)) return [3 /*break*/ , 4]; marker = this.markers[i]; tf = void 0; angle = marker.angle, anchor = marker.anchor; cos = Math.cos(angle); sin = Math.sin(angle); // position at and rotate around anchor tf = context.pdf.Matrix(cos, sin, -sin, cos, anchor[0], anchor[1]); // scale with stroke-width tf = context.pdf.matrixMult(context.pdf.Matrix(context.attributeState.strokeWidth, 0, 0, context.attributeState.strokeWidth, 0, 0), tf); tf = context.pdf.matrixMult(tf, context.transform); // as the marker is already scaled by the current line width we must not apply the line width twice! context.pdf.saveGraphicsState(); context.pdf.setLineWidth(1.0); return [4 /*yield*/ , context.refsHandler.getRendered(marker.id, function (node) { return node.apply(context); })]; case 2: _a.sent(); context.pdf.doFormObject(marker.id, tf); context.pdf.restoreGraphicsState(); _a.label = 3; case 3: i++; return [3 /*break*/ , 1]; case 4: return [2 /*return*/ ]; } }); }); }; return MarkerList; }(); /** * @param {string} id * @param {[number,number]} anchor * @param {number} angle */ var Marker = /** @class */ function () { function Marker(id, anchor, angle) { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.id = id; this.anchor = anchor; this.angle = angle; } return Marker; }(); /** * Convert em, px and bare number attributes to pixel values * @param {string} value * @param {number} pdfFontSize */ function toPixels(value, pdfFontSize) { var match; // em match = value && value.toString().match(/^([\-0-9.]+)em$/); if (match) { return parseFloat(match[1]) * pdfFontSize; } // pixels match = value && value.toString().match(/^([\-0-9.]+)(px|)$/); if (match) { return parseFloat(match[1]); } return 0; } function mapAlignmentBaseline(value) { return alignmentBaselineMap[value] || 'alphabetic'; } /** * parses a comma, sign and/or whitespace separated string of floats and returns * the single floats in an array */ function parseFloats(str) { var floats = []; var regex = /[+-]?(?:(?:\d+\.?\d*)|(?:\d*\.?\d+))(?:[eE][+-]?\d+)?/g; var match; while (match = regex.exec(str)) { floats.push(parseFloat(match[0])); } return floats; } // extends RGBColor by rgba colors as RGBColor is not capable of it function parseColor(colorString) { if (colorString === 'transparent') { var transparent = new RGBColor$1('rgb(0,0,0)'); transparent.a = 0; return transparent; } var match = /\s*rgba\(((?:[^,\)]*,){3}[^,\)]*)\)\s*/.exec(colorString); if (match) { var floats = parseFloats(match[1]); var color = new RGBColor$1('rgb(' + floats.slice(0, 3).join(',') + ')'); color.a = floats[3]; return color; } else { return new RGBColor$1(colorString); } } var fontAliases = { 'sans-serif': 'helvetica', verdana: 'helvetica', arial: 'helvetica', fixed: 'courier', monospace: 'courier', terminal: 'courier', serif: 'times', cursive: 'times', fantasy: 'times' }; function findFirstAvailableFontFamily(attributeState, fontFamilies, context) { var fontType = ''; if (attributeState.fontWeight === 'bold') { fontType = 'bold'; } if (attributeState.fontStyle === 'italic') { fontType += 'italic'; } if (fontType === '') { fontType = 'normal'; } var availableFonts = context.pdf.getFontList(); var firstAvailable = ''; var fontIsAvailable = fontFamilies.some(function (font) { var availableStyles = availableFonts[font]; if (availableStyles && availableStyles.indexOf(fontType) >= 0) { firstAvailable = font; return true; } font = font.toLowerCase(); if (fontAliases.hasOwnProperty(font)) { firstAvailable = font; return true; } return false; }); if (!fontIsAvailable) { firstAvailable = 'times'; } return firstAvailable; } function getBoundingBoxByChildren(context, svgnode) { if (getAttribute(svgnode.element, context.styleSheets, 'display') === 'none') { return [0, 0, 0, 0]; } var boundingBox = [0, 0, 0, 0]; svgnode.children.forEach(function (child) { var nodeBox = child.getBoundingBox(context); boundingBox = [Math.min(boundingBox[0], nodeBox[0]), Math.min(boundingBox[1], nodeBox[1]), Math.max(boundingBox[0] + boundingBox[2], nodeBox[0] + nodeBox[2]) - Math.min(boundingBox[0], nodeBox[0]), Math.max(boundingBox[1] + boundingBox[3], nodeBox[1] + nodeBox[3]) - Math.min(boundingBox[1], nodeBox[1])]; }); return boundingBox; } function defaultBoundingBox(element, context) { var pf = parseFloat; // TODO: check if there are other possible coordinate attributes var x1 = pf(element.getAttribute('x1')) || pf(getAttribute(element, context.styleSheets, 'x')) || pf(getAttribute(element, context.styleSheets, 'cx')) - pf(getAttribute(element, context.styleSheets, 'r')) || 0; var x2 = pf(element.getAttribute('x2')) || x1 + pf(getAttribute(element, context.styleSheets, 'width')) || pf(getAttribute(element, context.styleSheets, 'cx')) + pf(getAttribute(element, context.styleSheets, 'r')) || 0; var y1 = pf(element.getAttribute('y1')) || pf(getAttribute(element, context.styleSheets, 'y')) || pf(getAttribute(element, context.styleSheets, 'cy')) - pf(getAttribute(element, context.styleSheets, 'r')) || 0; var y2 = pf(element.getAttribute('y2')) || y1 + pf(getAttribute(element, context.styleSheets, 'height')) || pf(getAttribute(element, context.styleSheets, 'cy')) + pf(getAttribute(element, context.styleSheets, 'r')) || 0; return [Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2) - Math.min(x1, x2), Math.max(y1, y2) - Math.min(y1, y2)]; } function computeViewBoxTransform(node, viewBox, eX, eY, eWidth, eHeight, context, noTranslate) { if (noTranslate === void 0) { noTranslate = false; } var vbX = viewBox[0]; var vbY = viewBox[1]; var vbWidth = viewBox[2]; var vbHeight = viewBox[3]; var scaleX = eWidth / vbWidth; var scaleY = eHeight / vbHeight; var align, meetOrSlice; var preserveAspectRatio = node.getAttribute('preserveAspectRatio'); if (preserveAspectRatio) { var alignAndMeetOrSlice = preserveAspectRatio.split(' '); if (alignAndMeetOrSlice[0] === 'defer') { alignAndMeetOrSlice = alignAndMeetOrSlice.slice(1); } align = alignAndMeetOrSlice[0]; meetOrSlice = alignAndMeetOrSlice[1] || 'meet'; } else { align = 'xMidYMid'; meetOrSlice = 'meet'; } if (align !== 'none') { if (meetOrSlice === 'meet') { // uniform scaling with min scale scaleX = scaleY = Math.min(scaleX, scaleY); } else if (meetOrSlice === 'slice') { // uniform scaling with max scale scaleX = scaleY = Math.max(scaleX, scaleY); } } if (noTranslate) { return context.pdf.Matrix(scaleX, 0, 0, scaleY, 0, 0); } var translateX = eX - vbX * scaleX; var translateY = eY - vbY * scaleY; if (align.indexOf('xMid') >= 0) { translateX += (eWidth - vbWidth * scaleX) / 2; } else if (align.indexOf('xMax') >= 0) { translateX += eWidth - vbWidth * scaleX; } if (align.indexOf('YMid') >= 0) { translateY += (eHeight - vbHeight * scaleY) / 2; } else if (align.indexOf('YMax') >= 0) { translateY += eHeight - vbHeight * scaleY; } var translate = context.pdf.Matrix(1, 0, 0, 1, translateX, translateY); var scale = context.pdf.Matrix(scaleX, 0, 0, scaleY, 0, 0); return context.pdf.matrixMult(scale, translate); } // parses the "transform" string function parseTransform(transformString, context) { if (!transformString || transformString === 'none') return context.pdf.unitMatrix; var mRegex = /^[\s,]*matrix\(([^\)]+)\)\s*/, tRegex = /^[\s,]*translate\(([^\)]+)\)\s*/, rRegex = /^[\s,]*rotate\(([^\)]+)\)\s*/, sRegex = /^[\s,]*scale\(([^\)]+)\)\s*/, sXRegex = /^[\s,]*skewX\(([^\)]+)\)\s*/, sYRegex = /^[\s,]*skewY\(([^\)]+)\)\s*/; var resultMatrix = context.pdf.unitMatrix; var m; var tSLength; while (transformString.length > 0 && transformString.length !== tSLength) { tSLength = transformString.length; var match = mRegex.exec(transformString); if (match) { m = parseFloats(match[1]); resultMatrix = context.pdf.matrixMult(context.pdf.Matrix(m[0], m[1], m[2], m[3], m[4], m[5]), resultMatrix); transformString = transformString.substr(match[0].length); } match = rRegex.exec(transformString); if (match) { m = parseFloats(match[1]); var a = Math.PI * m[0] / 180; resultMatrix = context.pdf.matrixMult(context.pdf.Matrix(Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0), resultMatrix); if (m[1] || m[2]) { var t1 = context.pdf.Matrix(1, 0, 0, 1, m[1], m[2]); var t2 = context.pdf.Matrix(1, 0, 0, 1, -m[1], -m[2]); resultMatrix = context.pdf.matrixMult(t2, context.pdf.matrixMult(resultMatrix, t1)); } transformString = transformString.substr(match[0].length); } match = tRegex.exec(transformString); if (match) { m = parseFloats(match[1]); resultMatrix = context.pdf.matrixMult(context.pdf.Matrix(1, 0, 0, 1, m[0], m[1] || 0), resultMatrix); transformString = transformString.substr(match[0].length); } match = sRegex.exec(transformString); if (match) { m = parseFloats(match[1]); if (!m[1]) m[1] = m[0]; resultMatrix = context.pdf.matrixMult(context.pdf.Matrix(m[0], 0, 0, m[1], 0, 0), resultMatrix); transformString = transformString.substr(match[0].length); } match = sXRegex.exec(transformString); if (match) { m = parseFloat(match[1]); m *= Math.PI / 180; resultMatrix = context.pdf.matrixMult(context.pdf.Matrix(1, 0, Math.tan(m), 1, 0, 0), resultMatrix); transformString = transformString.substr(match[0].length); } match = sYRegex.exec(transformString); if (match) { m = parseFloat(match[1]); m *= Math.PI / 180; resultMatrix = context.pdf.matrixMult(context.pdf.Matrix(1, Math.tan(m), 0, 1, 0, 0), resultMatrix); transformString = transformString.substr(match[0].length); } } return resultMatrix; } var SvgNode = /** @class */ function () { function SvgNode(element, children) { this.element = element; this.children = children; } SvgNode.prototype.getBoundingBox = function (context) { if (getAttribute(this.element, context.styleSheets, 'display') === 'none') { return [0, 0, 0, 0]; } return this.getBoundingBoxCore(context); }; SvgNode.prototype.computeNodeTransform = function (context) { var nodeTransform = this.computeNodeTransformCore(context); var transformString = getAttribute(this.element, context.styleSheets, 'transform'); if (!transformString) return nodeTransform;else return context.pdf.matrixMult(nodeTransform, parseTransform(transformString, context)); }; return SvgNode; }(); var NonRenderedNode = /** @class */ function (_super) { __extends(NonRenderedNode, _super); function NonRenderedNode() { return _super !== null && _super.apply(this, arguments) || this; } NonRenderedNode.prototype.render = function (parentContext) { return Promise.resolve(); }; NonRenderedNode.prototype.getBoundingBoxCore = function (context) { return []; }; NonRenderedNode.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; return NonRenderedNode; }(SvgNode); var Gradient = /** @class */ function (_super) { __extends(Gradient, _super); function Gradient(pdfGradientType, element, children) { var _this = _super.call(this, element, children) || this; _this.pdfGradientType = pdfGradientType; return _this; } Gradient.prototype.apply = function (context) { return __awaiter(this, void 0, void 0, function () { var id, colors, opacitySum, hasOpacity, gState, pattern; return __generator(this, function (_a) { id = this.element.getAttribute('id'); if (!id) { return [2 /*return*/ ]; } colors = []; opacitySum = 0; hasOpacity = false; this.children.forEach(function (stop) { if (stop.element.tagName.toLowerCase() === 'stop') { var color = new RGBColor$1(getAttribute(stop.element, context.styleSheets, 'stop-color')); colors.push({ offset: Gradient.parseGradientOffset(stop.element.getAttribute('offset') || '0'), color: [color.r, color.g, color.b] }); var opacity = getAttribute(stop.element, context.styleSheets, 'stop-opacity'); if (opacity && opacity !== '1') { opacitySum += parseFloat(opacity); hasOpacity = true; } } }); if (hasOpacity) { gState = new l({ opacity: opacitySum / colors.length }); } pattern = new d(this.pdfGradientType, this.getCoordinates(), colors, gState); context.pdf.addShadingPattern(id, pattern); return [2 /*return*/ ]; }); }); }; Gradient.prototype.getBoundingBoxCore = function (context) { return defaultBoundingBox(this.element, context); }; Gradient.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; Gradient.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; /** * Convert percentage to decimal */ Gradient.parseGradientOffset = function (value) { var parsedValue = parseFloat(value); if (!isNaN(parsedValue) && value.indexOf('%') >= 0) { return parsedValue / 100; } return parsedValue; }; return Gradient; }(NonRenderedNode); var LinearGradient = /** @class */ function (_super) { __extends(LinearGradient, _super); function LinearGradient(element, children) { return _super.call(this, 'axial', element, children) || this; } LinearGradient.prototype.getCoordinates = function () { return [parseFloat(this.element.getAttribute('x1') || '0'), parseFloat(this.element.getAttribute('y1') || '0'), parseFloat(this.element.getAttribute('x2') || '1'), parseFloat(this.element.getAttribute('y2') || '0')]; }; return LinearGradient; }(Gradient); var RadialGradient = /** @class */ function (_super) { __extends(RadialGradient, _super); function RadialGradient(element, children) { return _super.call(this, 'radial', element, children) || this; } RadialGradient.prototype.getCoordinates = function () { var cx = this.element.getAttribute('cx'); var cy = this.element.getAttribute('cy'); var fx = this.element.getAttribute('fx'); var fy = this.element.getAttribute('fy'); return [parseFloat(fx || cx || '0.5'), parseFloat(fy || cy || '0.5'), 0, parseFloat(cx || '0.5'), parseFloat(cy || '0.5'), parseFloat(this.element.getAttribute('r') || '0.5')]; }; return RadialGradient; }(Gradient); var GradientFill = /** @class */ function () { function GradientFill(key, gradient) { this.key = key; this.gradient = gradient; } GradientFill.prototype.getFillData = function (forNode, context) { return __awaiter(this, void 0, void 0, function () { var gradientUnitsMatrix, bBox, gradientTransform; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/ , context.refsHandler.getRendered(this.key, function (node) { return node.apply(new Context(context.pdf, { refsHandler: context.refsHandler, textMeasure: context.textMeasure, styleSheets: context.styleSheets, viewport: context.viewport, svg2pdfParameters: context.svg2pdfParameters })); }) // matrix to convert between gradient space and user space // for "userSpaceOnUse" this is the current transformation: tfMatrix // for "objectBoundingBox" or default, the gradient gets scaled and transformed to the bounding box ]; case 1: _a.sent(); if (!this.gradient.element.hasAttribute('gradientUnits') || // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore this.gradient.element.getAttribute('gradientUnits').toLowerCase() === 'objectboundingbox') { bBox = forNode.getBoundingBox(context); gradientUnitsMatrix = context.pdf.Matrix(bBox[2], 0, 0, bBox[3], bBox[0], bBox[1]); } else { gradientUnitsMatrix = context.pdf.unitMatrix; } gradientTransform = parseTransform(getAttribute(this.gradient.element, context.styleSheets, 'gradientTransform', 'transform'), context); return [2 /*return*/ , { key: this.key, matrix: context.pdf.matrixMult(gradientTransform, gradientUnitsMatrix) }]; } }); }); }; return GradientFill; }(); var Pattern = /** @class */ function (_super) { __extends(Pattern, _super); function Pattern() { return _super !== null && _super.apply(this, arguments) || this; } Pattern.prototype.apply = function (context) { return __awaiter(this, void 0, void 0, function () { var id, bBox, pattern, _i, _a, child; return __generator(this, function (_b) { switch (_b.label) { case 0: id = this.element.getAttribute('id'); if (!id) { return [2 /*return*/ ]; } bBox = this.getBoundingBox(context); pattern = new p([bBox[0], bBox[1], bBox[0] + bBox[2], bBox[1] + bBox[3]], bBox[2], bBox[3]); context.pdf.beginTilingPattern(pattern); _i = 0, _a = this.children; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/ , 4]; child = _a[_i]; return [4 /*yield*/ , child.render(new Context(context.pdf, { attributeState: context.attributeState, refsHandler: context.refsHandler, styleSheets: context.styleSheets, viewport: context.viewport, svg2pdfParameters: context.svg2pdfParameters }))]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/ , 1]; case 4: context.pdf.endTilingPattern(id, pattern); return [2 /*return*/ ]; } }); }); }; Pattern.prototype.getBoundingBoxCore = function (context) { return defaultBoundingBox(this.element, context); }; Pattern.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; Pattern.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; return Pattern; }(NonRenderedNode); var PatternFill = /** @class */ function () { function PatternFill(key, pattern) { this.key = key; this.pattern = pattern; } PatternFill.prototype.getFillData = function (forNode, context) { return __awaiter(this, void 0, void 0, function () { var patternData, bBox, patternUnitsMatrix, fillBBox, x, y, width, height, patternContentUnitsMatrix, fillBBox, x, y, width, height, patternTransformMatrix, patternTransform, matrix; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/ , context.refsHandler.getRendered(this.key, function (node) { return node.apply(new Context(context.pdf, { refsHandler: context.refsHandler, textMeasure: context.textMeasure, styleSheets: context.styleSheets, viewport: context.viewport, svg2pdfParameters: context.svg2pdfParameters })); })]; case 1: _a.sent(); patternData = { key: this.key, boundingBox: undefined, xStep: 0, yStep: 0, matrix: undefined }; patternUnitsMatrix = context.pdf.unitMatrix; if (!this.pattern.element.hasAttribute('patternUnits') || this.pattern.element.getAttribute('patternUnits').toLowerCase() === 'objectboundingbox') { bBox = forNode.getBoundingBox(context); patternUnitsMatrix = context.pdf.Matrix(1, 0, 0, 1, bBox[0], bBox[1]); fillBBox = this.pattern.getBoundingBox(context); x = fillBBox[0] * bBox[0] || 0; y = fillBBox[1] * bBox[1] || 0; width = fillBBox[2] * bBox[2] || 0; height = fillBBox[3] * bBox[3] || 0; patternData.boundingBox = [x, y, x + width, y + height]; patternData.xStep = width; patternData.yStep = height; } patternContentUnitsMatrix = context.pdf.unitMatrix; if (this.pattern.element.hasAttribute('patternContentUnits') && this.pattern.element.getAttribute('patternContentUnits').toLowerCase() === 'objectboundingbox') { bBox || (bBox = forNode.getBoundingBox(context)); patternContentUnitsMatrix = context.pdf.Matrix(bBox[2], 0, 0, bBox[3], 0, 0); fillBBox = patternData.boundingBox || this.pattern.getBoundingBox(context); x = fillBBox[0] / bBox[0] || 0; y = fillBBox[1] / bBox[1] || 0; width = fillBBox[2] / bBox[2] || 0; height = fillBBox[3] / bBox[3] || 0; patternData.boundingBox = [x, y, x + width, y + height]; patternData.xStep = width; patternData.yStep = height; } patternTransformMatrix = context.pdf.unitMatrix; patternTransform = getAttribute(this.pattern.element, context.styleSheets, 'patternTransform', 'transform'); if (patternTransform) { patternTransformMatrix = parseTransform(patternTransform, context); } matrix = patternContentUnitsMatrix; matrix = context.pdf.matrixMult(matrix, patternUnitsMatrix); // translate by matrix = context.pdf.matrixMult(matrix, patternTransformMatrix); matrix = context.pdf.matrixMult(matrix, context.transform); patternData.matrix = matrix; return [2 /*return*/ , patternData]; } }); }); }; return PatternFill; }(); function parseFill(fill, context) { var url = iriReference.exec(fill); if (url) { var fillUrl = url[1]; var fillNode = context.refsHandler.get(fillUrl); if (fillNode && (fillNode instanceof LinearGradient || fillNode instanceof RadialGradient)) { return new GradientFill(fillUrl, fillNode); } else if (fillNode && fillNode instanceof Pattern) { return new PatternFill(fillUrl, fillNode); } else { // unsupported fill argument -> fill black return new ColorFill(new RGBColor$1('rgb(0, 0, 0)')); } } else { // plain color var fillColor = parseColor(fill); if (fillColor.ok) { return new ColorFill(fillColor); } else if (fill === 'none') { return null; } else { return null; } } } function parseAttributes(context, svgNode, node) { var domNode = node || svgNode.element; var visibility = getAttribute(domNode, context.styleSheets, 'visibility'); if (visibility) { context.attributeState.visibility = visibility; } // fill mode var fill = getAttribute(domNode, context.styleSheets, 'fill'); if (fill) { context.attributeState.fill = parseFill(fill, context); } // opacity is realized via a pdf graphics state var fillOpacity = getAttribute(domNode, context.styleSheets, 'fill-opacity'); if (fillOpacity) { context.attributeState.fillOpacity = parseFloat(fillOpacity); } var strokeOpacity = getAttribute(domNode, context.styleSheets, 'stroke-opacity'); if (strokeOpacity) { context.attributeState.strokeOpacity = parseFloat(strokeOpacity); } var opacity = getAttribute(domNode, context.styleSheets, 'opacity'); if (opacity) { context.attributeState.opacity = parseFloat(opacity); } // stroke mode var strokeWidth = getAttribute(domNode, context.styleSheets, 'stroke-width'); if (strokeWidth !== void 0 && strokeWidth !== '') { strokeWidth = Math.abs(parseFloat(strokeWidth)); context.attributeState.strokeWidth = strokeWidth; } var stroke = getAttribute(domNode, context.styleSheets, 'stroke'); if (stroke) { if (stroke === 'none') { context.attributeState.stroke = null; } else { // gradients, patterns not supported for strokes ... var strokeRGB = parseColor(stroke); if (strokeRGB.ok) { context.attributeState.stroke = new ColorFill(strokeRGB); } } } var lineCap = getAttribute(domNode, context.styleSheets, 'stroke-linecap'); if (lineCap) { context.attributeState.strokeLinecap = lineCap; } var lineJoin = getAttribute(domNode, context.styleSheets, 'stroke-linejoin'); if (lineJoin) { context.attributeState.strokeLinejoin = lineJoin; } var dashArray = getAttribute(domNode, context.styleSheets, 'stroke-dasharray'); if (dashArray) { dashArray = parseFloats(dashArray); var dashOffset = parseInt(getAttribute(domNode, context.styleSheets, 'stroke-dashoffset') || '0'); context.attributeState.strokeDasharray = dashArray; context.attributeState.strokeDashoffset = dashOffset; } var miterLimit = getAttribute(domNode, context.styleSheets, 'stroke-miterlimit'); if (miterLimit !== void 0 && miterLimit !== '') { context.attributeState.strokeMiterlimit = parseFloat(miterLimit); } var xmlSpace = domNode.getAttribute('xml:space'); if (xmlSpace) { context.attributeState.xmlSpace = xmlSpace; } var fontWeight = getAttribute(domNode, context.styleSheets, 'font-weight'); if (fontWeight) { context.attributeState.fontWeight = fontWeight; } var fontStyle = getAttribute(domNode, context.styleSheets, 'font-style'); if (fontStyle) { context.attributeState.fontStyle = fontStyle; } var fontFamily = getAttribute(domNode, context.styleSheets, 'font-family'); if (fontFamily) { var fontFamilies = fontFamilyPapandreou.parse(fontFamily); context.attributeState.fontFamily = findFirstAvailableFontFamily(context.attributeState, fontFamilies, context); } var fontSize = getAttribute(domNode, context.styleSheets, 'font-size'); if (fontSize) { var pdfFontSize = context.pdf.getFontSize(); context.attributeState.fontSize = toPixels(fontSize, pdfFontSize); } var alignmentBaseline = getAttribute(domNode, context.styleSheets, 'vertical-align') || getAttribute(domNode, context.styleSheets, 'alignment-baseline'); if (alignmentBaseline) { var matchArr = alignmentBaseline.match(/(baseline|text-bottom|alphabetic|ideographic|middle|central|mathematical|text-top|bottom|center|top|hanging)/); if (matchArr) { context.attributeState.alignmentBaseline = matchArr[0]; } } var textAnchor = getAttribute(domNode, context.styleSheets, 'text-anchor'); if (textAnchor) { context.attributeState.textAnchor = textAnchor; } } function applyAttributes(childContext, parentContext, node) { var fillOpacity = 1.0, strokeOpacity = 1.0; fillOpacity *= childContext.attributeState.fillOpacity; fillOpacity *= childContext.attributeState.opacity; if (childContext.attributeState.fill instanceof ColorFill && typeof childContext.attributeState.fill.color.a !== 'undefined') { fillOpacity *= childContext.attributeState.fill.color.a; } strokeOpacity *= childContext.attributeState.strokeOpacity; strokeOpacity *= childContext.attributeState.opacity; if (childContext.attributeState.stroke instanceof ColorFill && typeof childContext.attributeState.stroke.color.a !== 'undefined') { strokeOpacity *= childContext.attributeState.stroke.color.a; } var hasFillOpacity = fillOpacity < 1.0; var hasStrokeOpacity = strokeOpacity < 1.0; // This is a workaround for symbols that are used multiple times with different // fill/stroke attributes. All paths within symbols are both filled and stroked // and we set the fill/stroke to transparent if the use element has // fill/stroke="none". if (nodeIs(node, 'use')) { hasFillOpacity = true; hasStrokeOpacity = true; fillOpacity *= childContext.attributeState.fill ? 1 : 0; strokeOpacity *= childContext.attributeState.stroke ? 1 : 0; } else if (childContext.withinUse) { if (childContext.attributeState.fill !== parentContext.attributeState.fill) { hasFillOpacity = true; fillOpacity *= childContext.attributeState.fill ? 1 : 0; } else if (hasFillOpacity && !childContext.attributeState.fill) { fillOpacity = 0; } if (childContext.attributeState.stroke !== parentContext.attributeState.stroke) { hasStrokeOpacity = true; strokeOpacity *= childContext.attributeState.stroke ? 1 : 0; } else if (hasStrokeOpacity && !childContext.attributeState.stroke) { strokeOpacity = 0; } } if (hasFillOpacity || hasStrokeOpacity) { var gState = {}; hasFillOpacity && (gState['opacity'] = fillOpacity); hasStrokeOpacity && (gState['stroke-opacity'] = strokeOpacity); childContext.pdf.setGState(new l(gState)); } if (childContext.attributeState.fill && childContext.attributeState.fill !== parentContext.attributeState.fill && childContext.attributeState.fill instanceof ColorFill && childContext.attributeState.fill.color.ok && !nodeIs(node, 'text')) { // text fill color will be applied through setTextColor() childContext.pdf.setFillColor(childContext.attributeState.fill.color.r, childContext.attributeState.fill.color.g, childContext.attributeState.fill.color.b); } if (childContext.attributeState.strokeWidth !== parentContext.attributeState.strokeWidth) { childContext.pdf.setLineWidth(childContext.attributeState.strokeWidth); } if (childContext.attributeState.stroke !== parentContext.attributeState.stroke && childContext.attributeState.stroke instanceof ColorFill) { childContext.pdf.setDrawColor(childContext.attributeState.stroke.color.r, childContext.attributeState.stroke.color.g, childContext.attributeState.stroke.color.b); } if (childContext.attributeState.strokeLinecap !== parentContext.attributeState.strokeLinecap) { childContext.pdf.setLineCap(childContext.attributeState.strokeLinecap); } if (childContext.attributeState.strokeLinejoin !== parentContext.attributeState.strokeLinejoin) { childContext.pdf.setLineJoin(childContext.attributeState.strokeLinejoin); } if ((childContext.attributeState.strokeDasharray !== parentContext.attributeState.strokeDasharray || childContext.attributeState.strokeDashoffset !== parentContext.attributeState.strokeDashoffset) && childContext.attributeState.strokeDasharray) { childContext.pdf.setLineDashPattern(childContext.attributeState.strokeDasharray, childContext.attributeState.strokeDashoffset); } if (childContext.attributeState.strokeMiterlimit !== parentContext.attributeState.strokeMiterlimit) { childContext.pdf.setLineMiterLimit(childContext.attributeState.strokeMiterlimit); } var font; if (childContext.attributeState.fontFamily !== parentContext.attributeState.fontFamily) { if (fontAliases.hasOwnProperty(childContext.attributeState.fontFamily)) { font = fontAliases[childContext.attributeState.fontFamily]; } else { font = childContext.attributeState.fontFamily; } } if (childContext.attributeState.fill && childContext.attributeState.fill !== parentContext.attributeState.fill && childContext.attributeState.fill instanceof ColorFill && childContext.attributeState.fill.color.ok) { var fillColor = childContext.attributeState.fill.color; childContext.pdf.setTextColor(fillColor.r, fillColor.g, fillColor.b); } var fontStyle; if (childContext.attributeState.fontWeight !== parentContext.attributeState.fontWeight || childContext.attributeState.fontStyle !== parentContext.attributeState.fontStyle) { fontStyle = ''; if (childContext.attributeState.fontWeight === 'bold') { fontStyle = 'bold'; } if (childContext.attributeState.fontStyle === 'italic') { fontStyle += 'italic'; } if (fontStyle === '') { fontStyle = 'normal'; } } if (font !== undefined || fontStyle !== undefined) { if (font === undefined) { if (fontAliases.hasOwnProperty(childContext.attributeState.fontFamily)) { font = fontAliases[childContext.attributeState.fontFamily]; } else { font = childContext.attributeState.fontFamily; } } childContext.pdf.setFont(font, fontStyle); } if (childContext.attributeState.fontSize !== parentContext.attributeState.fontSize) { // correct for a jsPDF-instance measurement unit that differs from `pt` childContext.pdf.setFontSize(childContext.attributeState.fontSize * childContext.pdf.internal.scaleFactor); } } function getClipPathNode(targetNode, context) { var clipPathAttr = getAttribute(targetNode.element, context.styleSheets, 'clip-path'); if (!clipPathAttr) { return undefined; } var match = iriReference.exec(clipPathAttr); if (!match) { return undefined; } var clipPathId = match[1]; var clipNode = context.refsHandler.get(clipPathId); return clipNode || undefined; } function applyClipPath(targetNode, clipPathNode, context) { return __awaiter(this, void 0, void 0, function () { var clipContext, bBox; return __generator(this, function (_a) { switch (_a.label) { case 0: clipContext = context.clone(); if (clipPathNode.element.hasAttribute('clipPathUnits') && clipPathNode.element.getAttribute('clipPathUnits').toLowerCase() === 'objectboundingbox') { bBox = targetNode.getBoundingBox(context); clipContext.transform = context.pdf.matrixMult(context.pdf.Matrix(bBox[2], 0, 0, bBox[3], bBox[0], bBox[1]), context.transform); } return [4 /*yield*/ , clipPathNode.apply(clipContext)]; case 1: _a.sent(); return [2 /*return*/ ]; } }); }); } var RenderedNode = /** @class */ function (_super) { __extends(RenderedNode, _super); function RenderedNode() { return _super !== null && _super.apply(this, arguments) || this; } RenderedNode.prototype.render = function (parentContext) { return __awaiter(this, void 0, void 0, function () { var context, hasClipPath, clipNode; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.isVisible(parentContext.attributeState.visibility !== 'hidden', parentContext)) { return [2 /*return*/ ]; } context = parentContext.clone(); context.transform = context.pdf.matrixMult(this.computeNodeTransform(context), parentContext.transform); parseAttributes(context, this); hasClipPath = this.element.hasAttribute('clip-path') && getAttribute(this.element, context.styleSheets, 'clip-path') !== 'none'; if (!hasClipPath) return [3 /*break*/ , 3]; clipNode = getClipPathNode(this, context); if (!(clipNode && clipNode.isVisible(true, context))) return [3 /*break*/ , 2]; context.pdf.saveGraphicsState(); return [4 /*yield*/ , applyClipPath(this, clipNode, context)]; case 1: _a.sent(); return [3 /*break*/ , 3]; case 2: return [2 /*return*/ ]; case 3: if (!context.withinClipPath) { context.pdf.saveGraphicsState(); } applyAttributes(context, parentContext, this.element); return [4 /*yield*/ , this.renderCore(context)]; case 4: _a.sent(); if (!context.withinClipPath) { context.pdf.restoreGraphicsState(); } if (hasClipPath) { context.pdf.restoreGraphicsState(); } return [2 /*return*/ ]; } }); }); }; return RenderedNode; }(SvgNode); var GraphicsNode = /** @class */ function (_super) { __extends(GraphicsNode, _super); function GraphicsNode() { return _super !== null && _super.apply(this, arguments) || this; } return GraphicsNode; }(RenderedNode); var GeometryNode = /** @class */ function (_super) { __extends(GeometryNode, _super); function GeometryNode(hasMarkers, element, children) { var _this = _super.call(this, element, children) || this; _this.cachedPath = null; _this.hasMarkers = hasMarkers; return _this; } GeometryNode.prototype.renderCore = function (context) { return __awaiter(this, void 0, void 0, function () { var path; return __generator(this, function (_a) { switch (_a.label) { case 0: path = this.getCachedPath(context); if (path === null || path.segments.length === 0) { return [2 /*return*/ ]; } if (context.withinClipPath) { path.transform(context.transform); } else { context.pdf.setCurrentTransformationMatrix(context.transform); } path.draw(context); return [4 /*yield*/ , this.fillOrStroke(context)]; case 1: _a.sent(); if (!this.hasMarkers) return [3 /*break*/ , 3]; return [4 /*yield*/ , this.drawMarkers(context, path)]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/ ]; } }); }); }; GeometryNode.prototype.getCachedPath = function (context) { return this.cachedPath || (this.cachedPath = this.getPath(context)); }; GeometryNode.prototype.drawMarkers = function (context, path) { return __awaiter(this, void 0, void 0, function () { var markers; return __generator(this, function (_a) { switch (_a.label) { case 0: markers = this.getMarkers(path, context); return [4 /*yield*/ , markers.draw(context.clone({ transform: context.pdf.unitMatrix }))]; case 1: _a.sent(); return [2 /*return*/ ]; } }); }); }; GeometryNode.prototype.fillOrStroke = function (context) { return __awaiter(this, void 0, void 0, function () { var fill, stroke, fillData, _a, isNodeFillRuleEvenOdd; return __generator(this, function (_b) { switch (_b.label) { case 0: if (context.withinClipPath) { return [2 /*return*/ ]; } fill = context.attributeState.fill; stroke = context.attributeState.stroke && context.attributeState.strokeWidth !== 0; if (!fill) return [3 /*break*/ , 2]; return [4 /*yield*/ , fill.getFillData(this, context)]; case 1: _a = _b.sent(); return [3 /*break*/ , 3]; case 2: _a = undefined; _b.label = 3; case 3: fillData = _a; isNodeFillRuleEvenOdd = getAttribute(this.element, context.styleSheets, 'fill-rule') === 'evenodd'; // This is a workaround for symbols that are used multiple times with different // fill/stroke attributes. All paths within symbols are both filled and stroked // and we set the fill/stroke to transparent if the use element has // fill/stroke="none". if (fill && stroke || context.withinUse) { if (isNodeFillRuleEvenOdd) { context.pdf.fillStrokeEvenOdd(fillData); } else { context.pdf.fillStroke(fillData); } } else if (fill) { if (isNodeFillRuleEvenOdd) { context.pdf.fillEvenOdd(fillData); } else { context.pdf.fill(fillData); } } else if (stroke) { context.pdf.stroke(); } else { context.pdf.discardPath(); } return [2 /*return*/ ]; } }); }); }; GeometryNode.prototype.getBoundingBoxCore = function (context) { var path = this.getCachedPath(context); if (!path) { return [0, 0, 0, 0]; } var minX = Number.POSITIVE_INFINITY; var minY = Number.POSITIVE_INFINITY; var maxX = Number.NEGATIVE_INFINITY; var maxY = Number.NEGATIVE_INFINITY; var x = 0, y = 0; for (var i = 0; i < path.segments.length; i++) { var seg = path.segments[i]; if (seg instanceof MoveTo || seg instanceof LineTo || seg instanceof CurveTo) { x = seg.x; y = seg.y; } if (seg instanceof CurveTo) { minX = Math.min(minX, x, seg.x1, seg.x2, seg.x); maxX = Math.max(maxX, x, seg.x1, seg.x2, seg.x); minY = Math.min(minY, y, seg.y1, seg.y2, seg.y); maxY = Math.max(maxY, y, seg.y1, seg.y2, seg.y); } else { minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); } } return [minX, minY, maxX - minX, maxY - minY]; }; GeometryNode.prototype.getMarkers = function (path, context) { var markerStart = getAttribute(this.element, context.styleSheets, 'marker-start'); var markerMid = getAttribute(this.element, context.styleSheets, 'marker-mid'); var markerEnd = getAttribute(this.element, context.styleSheets, 'marker-end'); var markers = new MarkerList(); if (markerStart || markerMid || markerEnd) { markerEnd && (markerEnd = iri(markerEnd)); markerStart && (markerStart = iri(markerStart)); markerMid && (markerMid = iri(markerMid)); var list_1 = path.segments; var prevAngle = [1, 0], curAngle = void 0, first = false, firstAngle = [1, 0], last_1 = false; var _loop_1 = function _loop_1(i) { var curr = list_1[i]; var hasStartMarker = markerStart && (i === 1 || !(list_1[i] instanceof MoveTo) && list_1[i - 1] instanceof MoveTo); if (hasStartMarker) { list_1.forEach(function (value, index) { if (!last_1 && value instanceof Close && index > i) { var tmp = list_1[index - 1]; last_1 = (tmp instanceof MoveTo || tmp instanceof LineTo || tmp instanceof CurveTo) && tmp; } }); } var hasEndMarker = markerEnd && (i === list_1.length - 1 || !(list_1[i] instanceof MoveTo) && list_1[i + 1] instanceof MoveTo); var hasMidMarker = markerMid && i > 0 && !(i === 1 && list_1[i - 1] instanceof MoveTo); var prev = list_1[i - 1] || null; if (prev instanceof MoveTo || prev instanceof LineTo || prev instanceof CurveTo) { if (curr instanceof CurveTo) { hasStartMarker && markers.addMarker(new Marker(markerStart, [prev.x, prev.y], // @ts-ignore getAngle(last_1 ? [last_1.x, last_1.y] : [prev.x, prev.y], [curr.x1, curr.y1]))); hasEndMarker && markers.addMarker(new Marker(markerEnd, [curr.x, curr.y], getAngle([curr.x2, curr.y2], [curr.x, curr.y]))); if (hasMidMarker) { curAngle = getDirectionVector([prev.x, prev.y], [curr.x1, curr.y1]); curAngle = prev instanceof MoveTo ? curAngle : normalize$1(addVectors(prevAngle, curAngle)); markers.addMarker(new Marker(markerMid, [prev.x, prev.y], Math.atan2(curAngle[1], curAngle[0]))); } prevAngle = getDirectionVector([curr.x2, curr.y2], [curr.x, curr.y]); } else if (curr instanceof MoveTo || curr instanceof LineTo) { curAngle = getDirectionVector([prev.x, prev.y], [curr.x, curr.y]); if (hasStartMarker) { // @ts-ignore var angle = last_1 ? getDirectionVector([last_1.x, last_1.y], [curr.x, curr.y]) : curAngle; markers.addMarker(new Marker(markerStart, [prev.x, prev.y], Math.atan2(angle[1], angle[0]))); } hasEndMarker && markers.addMarker(new Marker(markerEnd, [curr.x, curr.y], Math.atan2(curAngle[1], curAngle[0]))); if (hasMidMarker) { var angle = curr instanceof MoveTo ? prevAngle : prev instanceof MoveTo ? curAngle : normalize$1(addVectors(prevAngle, curAngle)); markers.addMarker(new Marker(markerMid, [prev.x, prev.y], Math.atan2(angle[1], angle[0]))); } prevAngle = curAngle; } else if (curr instanceof Close) { // @ts-ignore curAngle = getDirectionVector([prev.x, prev.y], [first.x, first.y]); if (hasMidMarker) { var angle = prev instanceof MoveTo ? curAngle : normalize$1(addVectors(prevAngle, curAngle)); markers.addMarker(new Marker(markerMid, [prev.x, prev.y], Math.atan2(angle[1], angle[0]))); } if (hasEndMarker) { var angle = normalize$1(addVectors(curAngle, firstAngle)); markers.addMarker( // @ts-ignore new Marker(markerEnd, [first.x, first.y], Math.atan2(angle[1], angle[0]))); } prevAngle = curAngle; } } else { first = curr instanceof MoveTo && curr; var next = list_1[i + 1]; if (next instanceof MoveTo || next instanceof LineTo || next instanceof CurveTo) { // @ts-ignore firstAngle = getDirectionVector([first.x, first.y], [next.x, next.y]); } } }; for (var i = 0; i < list_1.length; i++) { _loop_1(i); } } return markers; }; return GeometryNode; }(GraphicsNode); function iri(attribute) { var match = iriReference.exec(attribute); return match && match[1] || undefined; } var Line = /** @class */ function (_super) { __extends(Line, _super); function Line(node, children) { return _super.call(this, true, node, children) || this; } Line.prototype.getPath = function (context) { if (context.withinClipPath || context.attributeState.stroke === null) { return null; } var x1 = parseFloat(this.element.getAttribute('x1') || '0'), y1 = parseFloat(this.element.getAttribute('y1') || '0'); var x2 = parseFloat(this.element.getAttribute('x2') || '0'), y2 = parseFloat(this.element.getAttribute('y2') || '0'); if (!(x1 || x2 || y1 || y2)) { return null; } return new Path().moveTo(x1, y1).lineTo(x2, y2); }; Line.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; Line.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; Line.prototype.fillOrStroke = function (context) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: context.attributeState.fill = null; return [4 /*yield*/ , _super.prototype.fillOrStroke.call(this, context)]; case 1: _a.sent(); return [2 /*return*/ ]; } }); }); }; return Line; }(GeometryNode); var Symbol$1 = /** @class */ function (_super) { __extends(_Symbol, _super); function _Symbol() { return _super !== null && _super.apply(this, arguments) || this; } _Symbol.prototype.apply = function (parentContext) { return __awaiter(this, void 0, void 0, function () { var context, hasClipPath, clipNode, _i, _a, child; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!this.isVisible(parentContext.attributeState.visibility !== 'hidden', parentContext)) { return [2 /*return*/ ]; } context = parentContext.clone(); context.transform = context.pdf.unitMatrix; parseAttributes(context, this); hasClipPath = this.element.hasAttribute('clip-path') && getAttribute(this.element, context.styleSheets, 'clip-path') !== 'none'; if (!hasClipPath) return [3 /*break*/ , 3]; clipNode = getClipPathNode(this, context); if (!(clipNode && clipNode.isVisible(true, context))) return [3 /*break*/ , 2]; return [4 /*yield*/ , applyClipPath(this, clipNode, context)]; case 1: _b.sent(); return [3 /*break*/ , 3]; case 2: return [2 /*return*/ ]; case 3: applyAttributes(context, parentContext, this.element); _i = 0, _a = this.children; _b.label = 4; case 4: if (!(_i < _a.length)) return [3 /*break*/ , 7]; child = _a[_i]; return [4 /*yield*/ , child.render(context)]; case 5: _b.sent(); _b.label = 6; case 6: _i++; return [3 /*break*/ , 4]; case 7: return [2 /*return*/ ]; } }); }); }; _Symbol.prototype.getBoundingBoxCore = function (context) { return getBoundingBoxByChildren(context, this); }; _Symbol.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; _Symbol.prototype.computeNodeTransformCore = function (context) { var x = parseFloat(getAttribute(this.element, context.styleSheets, 'x') || '0'); var y = parseFloat(getAttribute(this.element, context.styleSheets, 'y') || '0'); // TODO: implement refX/refY - this is still to do because common browsers don't seem to support the feature yet // x += parseFloat(this.element.getAttribute("refX")) || 0; ??? // y += parseFloat(this.element.getAttribute("refY")) || 0; ??? var viewBox = this.element.getAttribute('viewBox'); if (viewBox) { var box = parseFloats(viewBox); var width = parseFloat(getAttribute(this.element, context.styleSheets, 'width') || getAttribute(this.element.ownerSVGElement, context.styleSheets, 'width') || viewBox[2]); var height = parseFloat(getAttribute(this.element, context.styleSheets, 'height') || getAttribute(this.element.ownerSVGElement, context.styleSheets, 'height') || viewBox[3]); return computeViewBoxTransform(this.element, box, x, y, width, height, context); } else { return context.pdf.Matrix(1, 0, 0, 1, x, y); } }; return _Symbol; }(NonRenderedNode); var Viewport = /** @class */ function () { function Viewport(width, height) { this.width = width; this.height = height; } return Viewport; }(); /** * Draws the element referenced by a use node, makes use of pdf's XObjects/FormObjects so nodes are only written once * to the pdf document. This highly reduces the file size and computation time. */ var Use = /** @class */ function (_super) { __extends(Use, _super); function Use() { return _super !== null && _super.apply(this, arguments) || this; } Use.prototype.renderCore = function (context) { return __awaiter(this, void 0, void 0, function () { var pf, url, id, refNode, refNodeOpensViewport, x, y, width, height, t, viewBox, refContext; return __generator(this, function (_a) { switch (_a.label) { case 0: pf = parseFloat; url = this.element.getAttribute('href') || this.element.getAttribute('xlink:href'); // just in case someone has the idea to use empty use-tags, wtf??? if (!url) return [2 /*return*/ ]; id = url.substring(1); refNode = context.refsHandler.get(id); refNodeOpensViewport = nodeIs(refNode.element, 'symbol,svg') && refNode.element.hasAttribute('viewBox'); x = pf(getAttribute(this.element, context.styleSheets, 'x') || '0'); y = pf(getAttribute(this.element, context.styleSheets, 'y') || '0'); width = undefined; height = undefined; if (refNodeOpensViewport) { // <use> inherits width/height only to svg/symbol // if there is no viewBox attribute, width/height don't have an effect // in theory, the default value for width/height is 100%, but we currently don't support this width = pf(getAttribute(this.element, context.styleSheets, 'width') || getAttribute(refNode.element, context.styleSheets, 'width') || '0'); height = pf(getAttribute(this.element, context.styleSheets, 'height') || getAttribute(refNode.element, context.styleSheets, 'height') || '0'); // accumulate x/y to calculate the viewBox transform x += pf(getAttribute(refNode.element, context.styleSheets, 'x') || '0'); y += pf(getAttribute(refNode.element, context.styleSheets, 'y') || '0'); viewBox = parseFloats(refNode.element.getAttribute('viewBox')); t = computeViewBoxTransform(refNode.element, viewBox, x, y, width, height, context); } else { t = context.pdf.Matrix(1, 0, 0, 1, x, y); } refContext = new Context(context.pdf, { refsHandler: context.refsHandler, styleSheets: context.styleSheets, withinUse: true, viewport: refNodeOpensViewport ? new Viewport(width, height) : context.viewport, svg2pdfParameters: context.svg2pdfParameters }); return [4 /*yield*/ , context.refsHandler.getRendered(id, function (node) { return Use.renderReferencedNode(node, refContext); })]; case 1: _a.sent(); context.pdf.saveGraphicsState(); context.pdf.setCurrentTransformationMatrix(context.transform); // apply the bbox (i.e. clip) if needed if (refNodeOpensViewport && getAttribute(refNode.element, context.styleSheets, 'overflow') !== 'visible') { context.pdf.rect(x, y, width, height); context.pdf.clip().discardPath(); } context.pdf.doFormObject(id, t); context.pdf.restoreGraphicsState(); return [2 /*return*/ ]; } }); }); }; Use.renderReferencedNode = function (node, refContext) { return __awaiter(this, void 0, void 0, function () { var bBox; return __generator(this, function (_a) { switch (_a.label) { case 0: bBox = node.getBoundingBox(refContext); // The content of a PDF form object is implicitly clipped at its /BBox property. // SVG, however, applies its clip rect at the <use> attribute, which may modify it. // So, make the bBox a lot larger than it needs to be and hope any thick strokes are // still within. bBox = [bBox[0] - 0.5 * bBox[2], bBox[1] - 0.5 * bBox[3], bBox[2] * 2, bBox[3] * 2]; refContext.pdf.beginFormObject(bBox[0], bBox[1], bBox[2], bBox[3], refContext.pdf.unitMatrix); if (!(node instanceof Symbol$1)) return [3 /*break*/ , 2]; return [4 /*yield*/ , node.apply(refContext)]; case 1: _a.sent(); return [3 /*break*/ , 4]; case 2: return [4 /*yield*/ , node.render(refContext)]; case 3: _a.sent(); _a.label = 4; case 4: refContext.pdf.endFormObject(node.element.getAttribute('id')); return [2 /*return*/ ]; } }); }); }; Use.prototype.getBoundingBoxCore = function (context) { return defaultBoundingBox(this.element, context); }; Use.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; Use.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; return Use; }(GraphicsNode); var Rect = /** @class */ function (_super) { __extends(Rect, _super); function Rect(element, children) { return _super.call(this, false, element, children) || this; } Rect.prototype.getPath = function (context) { var w = parseFloat(getAttribute(this.element, context.styleSheets, 'width') || '0'); var h = parseFloat(getAttribute(this.element, context.styleSheets, 'height') || '0'); if (!isFinite(w) || w <= 0 || !isFinite(h) || h <= 0) { return null; } var rxAttr = getAttribute(this.element, context.styleSheets, 'rx'); var ryAttr = getAttribute(this.element, context.styleSheets, 'ry'); var rx = Math.min(parseFloat(rxAttr || ryAttr || '0'), w * 0.5); var ry = Math.min(parseFloat(ryAttr || rxAttr || '0'), h * 0.5); var x = parseFloat(getAttribute(this.element, context.styleSheets, 'x') || '0'); var y = parseFloat(getAttribute(this.element, context.styleSheets, 'y') || '0'); var arc = 4 / 3 * (Math.SQRT2 - 1); if (rx === 0 && ry === 0) { return new Path().moveTo(x, y).lineTo(x + w, y).lineTo(x + w, y + h).lineTo(x, y + h).close(); } else { return new Path().moveTo(x += rx, y).lineTo(x += w - 2 * rx, y).curveTo(x + rx * arc, y, x + rx, y + (ry - ry * arc), x += rx, y += ry).lineTo(x, y += h - 2 * ry).curveTo(x, y + ry * arc, x - rx * arc, y + ry, x -= rx, y += ry).lineTo(x += -w + 2 * rx, y).curveTo(x - rx * arc, y, x - rx, y - ry * arc, x -= rx, y -= ry).lineTo(x, y += -h + 2 * ry).curveTo(x, y - ry * arc, x + rx * arc, y - ry, x += rx, y -= ry).close(); } }; Rect.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; Rect.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; return Rect; }(GeometryNode); var EllipseBase = /** @class */ function (_super) { __extends(EllipseBase, _super); function EllipseBase(element, children) { return _super.call(this, false, element, children) || this; } EllipseBase.prototype.getPath = function (context) { var rx = this.getRx(context); var ry = this.getRy(context); if (!isFinite(rx) || ry <= 0 || !isFinite(ry) || ry <= 0) { return null; } var x = parseFloat(getAttribute(this.element, context.styleSheets, 'cx') || '0'), y = parseFloat(getAttribute(this.element, context.styleSheets, 'cy') || '0'); var lx = 4 / 3 * (Math.SQRT2 - 1) * rx, ly = 4 / 3 * (Math.SQRT2 - 1) * ry; return new Path().moveTo(x + rx, y).curveTo(x + rx, y - ly, x + lx, y - ry, x, y - ry).curveTo(x - lx, y - ry, x - rx, y - ly, x - rx, y).curveTo(x - rx, y + ly, x - lx, y + ry, x, y + ry).curveTo(x + lx, y + ry, x + rx, y + ly, x + rx, y); }; EllipseBase.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; EllipseBase.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; return EllipseBase; }(GeometryNode); var Ellipse$1 = /** @class */ function (_super) { __extends(Ellipse, _super); function Ellipse(element, children) { return _super.call(this, element, children) || this; } Ellipse.prototype.getRx = function (context) { return parseFloat(getAttribute(this.element, context.styleSheets, 'rx') || '0'); }; Ellipse.prototype.getRy = function (context) { return parseFloat(getAttribute(this.element, context.styleSheets, 'ry') || '0'); }; return Ellipse; }(EllipseBase); function getTextRenderingMode(attributeState) { var renderingMode = 'invisible'; if (attributeState.fill && attributeState.stroke) { renderingMode = 'fillThenStroke'; } else if (attributeState.fill) { renderingMode = 'fill'; } else if (attributeState.stroke) { renderingMode = 'stroke'; } return renderingMode; } function transformXmlSpace(trimmedText, attributeState) { trimmedText = removeNewlines(trimmedText); trimmedText = replaceTabsBySpace(trimmedText); if (attributeState.xmlSpace === 'default') { trimmedText = trimmedText.trim(); trimmedText = consolidateSpaces(trimmedText); } return trimmedText; } function removeNewlines(str) { return str.replace(/[\n\r]/g, ''); } function replaceTabsBySpace(str) { return str.replace(/[\t]/g, ' '); } function consolidateSpaces(str) { return str.replace(/ +/g, ' '); } // applies text transformations to a text node function transformText(node, text, context) { var textTransform = getAttribute(node, context.styleSheets, 'text-transform'); switch (textTransform) { case 'uppercase': return text.toUpperCase(); case 'lowercase': return text.toLowerCase(); default: return text; // TODO: capitalize, full-width } } function trimLeft(str) { return str.replace(/^\s+/, ''); } function trimRight(str) { return str.replace(/\s+$/, ''); } /** * @param {string} textAnchor * @param {number} originX * @param {number} originY * @constructor */ var TextChunk = /** @class */ function () { function TextChunk(parent, textAnchor, originX, originY) { this.textNode = parent; this.texts = []; this.textNodes = []; this.textAnchor = textAnchor; this.originX = originX; this.originY = originY; } TextChunk.prototype.add = function (tSpan, text) { this.texts.push(text); this.textNodes.push(tSpan); }; TextChunk.prototype.put = function (context) { var i, textNode; var strokeRGB; var xs = [], ys = [], textNodeContexts = []; var currentTextX = this.originX, currentTextY = this.originY; var minX = currentTextX, maxX = currentTextX; for (i = 0; i < this.textNodes.length; i++) { textNode = this.textNodes[i]; var x = currentTextX; var y = currentTextY; var textNodeContext = void 0; if (textNode.nodeName === '#text') { textNodeContext = context; } else { textNodeContext = context.clone(); parseAttributes(textNodeContext, this.textNode, textNode); var tSpanStrokeColor = getAttribute(textNode, context.styleSheets, 'stroke'); if (tSpanStrokeColor) { strokeRGB = new RGBColor$1(tSpanStrokeColor); if (strokeRGB.ok) { textNodeContext.attributeState.stroke = new ColorFill(strokeRGB); } } var strokeWidth = getAttribute(textNode, context.styleSheets, 'stroke-width'); if (strokeWidth !== void 0) { textNodeContext.attributeState.strokeWidth = parseFloat(strokeWidth); } var tSpanDx = textNode.getAttribute('dx'); if (tSpanDx !== null) { x += toPixels(tSpanDx, textNodeContext.attributeState.fontSize); } var tSpanDy = textNode.getAttribute('dy'); if (tSpanDy !== null) { y += toPixels(tSpanDy, textNodeContext.attributeState.fontSize); } } textNodeContexts[i] = textNodeContext; xs[i] = x; ys[i] = y; currentTextX = x + context.textMeasure.measureTextWidth(this.texts[i], textNodeContext.attributeState); currentTextY = y; minX = Math.min(minX, x); maxX = Math.max(maxX, currentTextX); } var textOffset = 0; switch (this.textAnchor) { case 'start': textOffset = 0; break; case 'middle': textOffset = (maxX - minX) / 2; break; case 'end': textOffset = maxX - minX; break; } for (i = 0; i < this.textNodes.length; i++) { textNode = this.textNodes[i]; if (textNode.nodeName !== '#text') { var tSpanVisibility = getAttribute(textNode, context.styleSheets, 'visibility') || context.attributeState.visibility; if (tSpanVisibility === 'hidden') { continue; } } context.pdf.saveGraphicsState(); applyAttributes(textNodeContexts[i], context, textNode); var alignmentBaseline = textNodeContexts[i].attributeState.alignmentBaseline; var textRenderingMode = getTextRenderingMode(textNodeContexts[i].attributeState); context.pdf.text(this.texts[i], xs[i] - textOffset, ys[i], { baseline: mapAlignmentBaseline(alignmentBaseline), angle: context.transform, renderingMode: textRenderingMode === 'fill' ? void 0 : textRenderingMode }); context.pdf.restoreGraphicsState(); } return [currentTextX, currentTextY]; }; return TextChunk; }(); var TextNode = /** @class */ function (_super) { __extends(TextNode, _super); function TextNode() { return _super !== null && _super.apply(this, arguments) || this; } TextNode.prototype.renderCore = function (context) { return __awaiter(this, void 0, void 0, function () { var xOffset, pdfFontSize, textX, textY, dx, dy, visibility, tSpanCount, trimmedText, transformedText, alignmentBaseline, textRenderingMode, currentTextSegment, i, textNode, xmlSpace, textContent, tSpan, j, lastPositions, tSpanAbsX, x, tSpanAbsY, y, tSpanXmlSpace, trimmedText, transformedText; return __generator(this, function (_a) { context.pdf.saveGraphicsState(); xOffset = 0; pdfFontSize = context.pdf.getFontSize(); textX = toPixels(this.element.getAttribute('x'), pdfFontSize); textY = toPixels(this.element.getAttribute('y'), pdfFontSize); dx = toPixels(this.element.getAttribute('dx'), pdfFontSize); dy = toPixels(this.element.getAttribute('dy'), pdfFontSize); visibility = context.attributeState.visibility; tSpanCount = this.element.childElementCount; if (tSpanCount === 0) { trimmedText = transformXmlSpace(this.element.textContent || '', context.attributeState); transformedText = transformText(this.element, trimmedText, context); xOffset = context.textMeasure.getTextOffset(transformedText, context.attributeState); if (visibility === 'visible') { alignmentBaseline = context.attributeState.alignmentBaseline; textRenderingMode = getTextRenderingMode(context.attributeState); context.pdf.text(transformedText, textX + dx - xOffset, textY + dy, { baseline: mapAlignmentBaseline(alignmentBaseline), angle: context.transform, renderingMode: textRenderingMode === 'fill' ? void 0 : textRenderingMode }); } } else { currentTextSegment = new TextChunk(this, context.attributeState.textAnchor, textX + dx, textY + dy); for (i = 0; i < this.element.childNodes.length; i++) { textNode = this.element.childNodes[i]; if (!textNode.textContent) { continue; } xmlSpace = context.attributeState.xmlSpace; textContent = textNode.textContent; if (textNode.nodeName === '#text') ;else if (nodeIs(textNode, 'title')) { continue; } else if (nodeIs(textNode, 'tspan')) { tSpan = textNode; if (tSpan.childElementCount > 0) { // filter <title> elements... textContent = ''; for (j = 0; j < tSpan.childNodes.length; j++) { if (tSpan.childNodes[j].nodeName === '#text') { textContent += tSpan.childNodes[j].textContent; } } } lastPositions = void 0; tSpanAbsX = tSpan.getAttribute('x'); if (tSpanAbsX !== null) { x = toPixels(tSpanAbsX, pdfFontSize); lastPositions = currentTextSegment.put(context); currentTextSegment = new TextChunk(this, getAttribute(tSpan, context.styleSheets, 'text-anchor') || context.attributeState.textAnchor, x, lastPositions[1]); } tSpanAbsY = tSpan.getAttribute('y'); if (tSpanAbsY !== null) { y = toPixels(tSpanAbsY, pdfFontSize); lastPositions = currentTextSegment.put(context); currentTextSegment = new TextChunk(this, getAttribute(tSpan, context.styleSheets, 'text-anchor') || context.attributeState.textAnchor, lastPositions[0], y); } tSpanXmlSpace = tSpan.getAttribute('xml:space'); if (tSpanXmlSpace) { xmlSpace = tSpanXmlSpace; } } trimmedText = removeNewlines(textContent); trimmedText = replaceTabsBySpace(trimmedText); if (xmlSpace === 'default') { if (i === 0) { trimmedText = trimLeft(trimmedText); } if (i === tSpanCount - 1) { trimmedText = trimRight(trimmedText); } trimmedText = consolidateSpaces(trimmedText); } transformedText = transformText(this.element, trimmedText, context); currentTextSegment.add(textNode, transformedText); } currentTextSegment.put(context); } context.pdf.restoreGraphicsState(); return [2 /*return*/ ]; }); }); }; TextNode.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; TextNode.prototype.getBoundingBoxCore = function (context) { return defaultBoundingBox(this.element, context); }; TextNode.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; return TextNode; }(GraphicsNode); var PathNode = /** @class */ function (_super) { __extends(PathNode, _super); function PathNode(node, children) { return _super.call(this, true, node, children) || this; } PathNode.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; PathNode.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; PathNode.prototype.getPath = function (context) { var svgPath = new svgpath$1(getAttribute(this.element, context.styleSheets, 'd') || '').unshort().unarc().abs(); var path = new Path(); var prevX; var prevY; svgPath.iterate(function (seg, i) { var type = seg[0]; switch (type) { case 'M': path.moveTo(seg[1], seg[2]); break; case 'L': path.lineTo(seg[1], seg[2]); break; case 'H': path.lineTo(seg[1], prevY); break; case 'V': path.lineTo(prevX, seg[1]); break; case 'C': path.curveTo(seg[1], seg[2], seg[3], seg[4], seg[5], seg[6]); break; case 'Q': var p2 = toCubic([prevX, prevY], [seg[1], seg[2]]); var p3 = toCubic([seg[3], seg[4]], [seg[1], seg[2]]); path.curveTo(p2[0], p2[1], p3[0], p3[1], seg[3], seg[4]); break; case 'Z': path.close(); break; } switch (type) { case 'M': case 'L': prevX = seg[1]; prevY = seg[2]; break; case 'H': prevX = seg[1]; break; case 'V': prevY = seg[1]; break; case 'C': prevX = seg[5]; prevY = seg[6]; break; case 'Q': prevX = seg[3]; prevY = seg[4]; break; } }); return path; }; return PathNode; }(GeometryNode); // groups: 1: mime-type (+ charset), 2: mime-type (w/o charset), 3: charset, 4: base64?, 5: body var dataUriRegex = /^\s*data:(([^/,;]+\/[^/,;]+)(?:;([^,;=]+=[^,;=]+))?)?(?:;(base64))?,(.*\s*)$/i; var ImageNode = /** @class */ function (_super) { __extends(ImageNode, _super); function ImageNode(element, children) { var _this = _super.call(this, element, children) || this; _this.imageLoadingPromise = null; _this.imageUrl = _this.element.getAttribute('xlink:href') || _this.element.getAttribute('href'); if (_this.imageUrl) { // start loading the image as early as possible _this.imageLoadingPromise = ImageNode.fetchImageData(_this.imageUrl); } return _this; } ImageNode.prototype.renderCore = function (context) { return __awaiter(this, void 0, void 0, function () { var width, height, x, y, _a, data, format, parser, svgElement, preserveAspectRatio, idMap, svgnode, dataUri; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!this.imageLoadingPromise) { return [2 /*return*/ ]; } context.pdf.setCurrentTransformationMatrix(context.transform); width = parseFloat(getAttribute(this.element, context.styleSheets, 'width') || '0'), height = parseFloat(getAttribute(this.element, context.styleSheets, 'height') || '0'), x = parseFloat(getAttribute(this.element, context.styleSheets, 'x') || '0'), y = parseFloat(getAttribute(this.element, context.styleSheets, 'y') || '0'); if (!isFinite(width) || width <= 0 || !isFinite(height) || height <= 0) { return [2 /*return*/ ]; } return [4 /*yield*/ , this.imageLoadingPromise]; case 1: _a = _b.sent(), data = _a.data, format = _a.format; if (!(format.indexOf('svg') === 0)) return [3 /*break*/ , 3]; parser = new DOMParser(); svgElement = parser.parseFromString(data, 'image/svg+xml').firstElementChild; preserveAspectRatio = this.element.getAttribute('preserveAspectRatio'); if (!preserveAspectRatio || preserveAspectRatio.indexOf('defer') < 0 || !svgElement.getAttribute('preserveAspectRatio')) { svgElement.setAttribute('preserveAspectRatio', preserveAspectRatio || ''); } svgElement.setAttribute('x', String(x)); svgElement.setAttribute('y', String(y)); svgElement.setAttribute('width', String(width)); svgElement.setAttribute('height', String(height)); idMap = {}; svgnode = parse$1(svgElement, idMap); return [4 /*yield*/ , svgnode.render(new Context(context.pdf, { refsHandler: new ReferencesHandler(idMap), styleSheets: context.styleSheets, viewport: new Viewport(width, height), svg2pdfParameters: context.svg2pdfParameters }))]; case 2: _b.sent(); return [2 /*return*/ ]; case 3: dataUri = "data:image/" + format + ";base64," + btoa(data); try { context.pdf.addImage(dataUri, '', // will be ignored anyways if imageUrl is a data url x, y, width, height); } catch (e) { (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.warn && console.warn("Could not load image " + this.imageUrl + ".\n" + e); } _b.label = 4; case 4: return [2 /*return*/ ]; } }); }); }; ImageNode.prototype.getBoundingBoxCore = function (context) { return defaultBoundingBox(this.element, context); }; ImageNode.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; ImageNode.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; ImageNode.fetchImageData = function (imageUrl) { return __awaiter(this, void 0, void 0, function () { var data, format, match, mimeType, mimeTypeParts; return __generator(this, function (_a) { switch (_a.label) { case 0: match = imageUrl.match(dataUriRegex); if (!match) return [3 /*break*/ , 1]; mimeType = match[2]; mimeTypeParts = mimeType.split('/'); if (mimeTypeParts[0] !== 'image') { throw new Error("Unsupported image URL: " + imageUrl); } format = mimeTypeParts[1]; data = match[5]; if (match[4] === 'base64') { data = atob(data); } else { data = decodeURIComponent(data); } return [3 /*break*/ , 3]; case 1: return [4 /*yield*/ , ImageNode.fetchImage(imageUrl)]; case 2: data = _a.sent(); format = imageUrl.substring(imageUrl.lastIndexOf('.') + 1); _a.label = 3; case 3: return [2 /*return*/ , { data: data, format: format }]; } }); }); }; ImageNode.fetchImage = function (imageUrl) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', imageUrl, true); xhr.responseType = 'arraybuffer'; xhr.onload = function () { if (xhr.status !== 200) { throw new Error("Error " + xhr.status + ": Failed to load image '" + imageUrl + "'"); } var bytes = new Uint8Array(xhr.response); var data = ''; for (var i = 0; i < bytes.length; i++) { data += String.fromCharCode(bytes[i]); } resolve(data); }; xhr.onerror = reject; xhr.onabort = reject; xhr.send(null); }); }; ImageNode.getMimeType = function (format) { format = format.toLowerCase(); switch (format) { case 'jpg': case 'jpeg': return 'image/jpeg'; default: return "image/" + format; } }; return ImageNode; }(GraphicsNode); var Traverse = /** @class */ function (_super) { __extends(Traverse, _super); function Traverse(closed, node, children) { var _this = _super.call(this, true, node, children) || this; _this.closed = closed; return _this; } Traverse.prototype.getPath = function (context) { if (!this.element.hasAttribute('points') || this.element.getAttribute('points') === '') { return null; } // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore var points = Traverse.parsePointsString(this.element.getAttribute('points')); var path = new Path(); if (points.length < 1) { return path; } path.moveTo(points[0][0], points[0][1]); for (var i = 1; i < points.length; i++) { path.lineTo(points[i][0], points[i][1]); } if (this.closed) { path.close(); } return path; }; Traverse.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; Traverse.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; Traverse.parsePointsString = function (string) { var floats = parseFloats(string); var result = []; for (var i = 0; i < floats.length - 1; i += 2) { var x = floats[i]; var y = floats[i + 1]; result.push([x, y]); } return result; }; return Traverse; }(GeometryNode); var Polygon = /** @class */ function (_super) { __extends(Polygon, _super); function Polygon(node, children) { return _super.call(this, true, node, children) || this; } return Polygon; }(Traverse); var VoidNode = /** @class */ function (_super) { __extends(VoidNode, _super); function VoidNode() { return _super !== null && _super.apply(this, arguments) || this; } VoidNode.prototype.render = function (parentContext) { return Promise.resolve(); }; VoidNode.prototype.getBoundingBoxCore = function (context) { return [0, 0, 0, 0]; }; VoidNode.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; VoidNode.prototype.isVisible = function (parentVisible, context) { return svgNodeIsVisible(this, parentVisible, context); }; return VoidNode; }(SvgNode); var MarkerNode = /** @class */ function (_super) { __extends(MarkerNode, _super); function MarkerNode() { return _super !== null && _super.apply(this, arguments) || this; } MarkerNode.prototype.apply = function (parentContext) { return __awaiter(this, void 0, void 0, function () { var tfMatrix, bBox, _i, _a, child; return __generator(this, function (_b) { switch (_b.label) { case 0: tfMatrix = this.computeNodeTransform(parentContext); bBox = this.getBoundingBox(parentContext); parentContext.pdf.beginFormObject(bBox[0], bBox[1], bBox[2], bBox[3], tfMatrix); _i = 0, _a = this.children; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/ , 4]; child = _a[_i]; return [4 /*yield*/ , child.render(new Context(parentContext.pdf, { refsHandler: parentContext.refsHandler, styleSheets: parentContext.styleSheets, viewport: parentContext.viewport, svg2pdfParameters: parentContext.svg2pdfParameters }))]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/ , 1]; case 4: parentContext.pdf.endFormObject(this.element.getAttribute('id')); return [2 /*return*/ ]; } }); }); }; MarkerNode.prototype.getBoundingBoxCore = function (context) { var viewBox = this.element.getAttribute('viewBox'); var vb; if (viewBox) { vb = parseFloats(viewBox); } return [vb && vb[0] || 0, vb && vb[1] || 0, vb && vb[2] || parseFloat(this.element.getAttribute('marker-width') || '0'), vb && vb[3] || parseFloat(this.element.getAttribute('marker-height') || '0')]; }; MarkerNode.prototype.computeNodeTransformCore = function (context) { var refX = parseFloat(this.element.getAttribute('refX') || '0'); var refY = parseFloat(this.element.getAttribute('refY') || '0'); var viewBox = this.element.getAttribute('viewBox'); var nodeTransform; if (viewBox) { var bounds = parseFloats(viewBox); // "Markers are drawn such that their reference point (i.e., attributes ‘refX’ and ‘refY’) // is positioned at the given vertex." - The "translate" part of the viewBox transform is // ignored. nodeTransform = computeViewBoxTransform(this.element, bounds, 0, 0, parseFloat(this.element.getAttribute('markerWidth') || '3'), parseFloat(this.element.getAttribute('markerHeight') || '3'), context, true); nodeTransform = context.pdf.matrixMult(context.pdf.Matrix(1, 0, 0, 1, -refX, -refY), nodeTransform); } else { nodeTransform = context.pdf.Matrix(1, 0, 0, 1, -refX, -refY); } return nodeTransform; }; MarkerNode.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; return MarkerNode; }(NonRenderedNode); var Circle = /** @class */ function (_super) { __extends(Circle, _super); function Circle(node, children) { return _super.call(this, node, children) || this; } Circle.prototype.getR = function (context) { var _a; return (_a = this.r) !== null && _a !== void 0 ? _a : this.r = parseFloat(getAttribute(this.element, context.styleSheets, 'r') || '0'); }; Circle.prototype.getRx = function (context) { return this.getR(context); }; Circle.prototype.getRy = function (context) { return this.getR(context); }; return Circle; }(EllipseBase); var Polyline = /** @class */ function (_super) { __extends(Polyline, _super); function Polyline(node, children) { return _super.call(this, false, node, children) || this; } return Polyline; }(Traverse); var ContainerNode = /** @class */ function (_super) { __extends(ContainerNode, _super); function ContainerNode() { return _super !== null && _super.apply(this, arguments) || this; } ContainerNode.prototype.renderCore = function (context) { return __awaiter(this, void 0, void 0, function () { var _i, _a, child; return __generator(this, function (_b) { switch (_b.label) { case 0: _i = 0, _a = this.children; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/ , 4]; child = _a[_i]; return [4 /*yield*/ , child.render(context)]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/ , 1]; case 4: return [2 /*return*/ ]; } }); }); }; ContainerNode.prototype.getBoundingBoxCore = function (context) { return getBoundingBoxByChildren(context, this); }; return ContainerNode; }(RenderedNode); var Svg = /** @class */ function (_super) { __extends(Svg, _super); function Svg() { return _super !== null && _super.apply(this, arguments) || this; } Svg.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; Svg.prototype.render = function (context) { return __awaiter(this, void 0, void 0, function () { var x, y, width, height, transform; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.isVisible(context.attributeState.visibility !== 'hidden', context)) { return [2 /*return*/ ]; } x = this.getX(context); y = this.getY(context); width = this.getWidth(context); height = this.getHeight(context); context.pdf.saveGraphicsState(); transform = context.transform; if (this.element.hasAttribute('transform')) { // SVG 2 allows transforms on SVG elements // "The transform should be applied as if the ‘svg’ had a parent element with that transform set." transform = context.pdf.matrixMult( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion parseTransform(this.element.getAttribute('transform'), context), transform); } context.pdf.setCurrentTransformationMatrix(transform); if (!context.withinUse && getAttribute(this.element, context.styleSheets, 'overflow') !== 'visible') { // establish a new viewport context.pdf.rect(x, y, width, height).clip().discardPath(); } return [4 /*yield*/ , _super.prototype.render.call(this, context.clone({ transform: context.pdf.unitMatrix, viewport: context.withinUse ? context.viewport : new Viewport(width, height) }))]; case 1: _a.sent(); context.pdf.restoreGraphicsState(); return [2 /*return*/ ]; } }); }); }; Svg.prototype.computeNodeTransform = function (context) { return this.computeNodeTransformCore(context); }; Svg.prototype.computeNodeTransformCore = function (context) { if (context.withinUse) { return context.pdf.unitMatrix; } var x = this.getX(context); var y = this.getY(context); var viewBox = this.getViewBox(); var nodeTransform; if (viewBox) { var width = this.getWidth(context); var height = this.getHeight(context); nodeTransform = computeViewBoxTransform(this.element, viewBox, x, y, width, height, context); } else { nodeTransform = context.pdf.Matrix(1, 0, 0, 1, x, y); } return nodeTransform; }; Svg.prototype.getWidth = function (context) { if (this.width !== undefined) { return this.width; } var width; var parameters = context.svg2pdfParameters; if (this.isOutermostSvg(context)) { // special treatment for the outermost SVG element if (parameters.width != null) { // if there is a user defined width, use it width = parameters.width; } else { // otherwise check if the SVG element defines the width itself var widthAttr = getAttribute(this.element, context.styleSheets, 'width'); if (widthAttr) { width = parseFloat(widthAttr); } else { // if not, check if we can figure out the aspect ratio from the viewBox attribute var viewBox = this.getViewBox(); if (viewBox && (parameters.height != null || getAttribute(this.element, context.styleSheets, 'height'))) { // if there is a viewBox and the height is defined, use the width that matches the height together with the aspect ratio var aspectRatio = viewBox[2] / viewBox[3]; width = this.getHeight(context) * aspectRatio; } else { // if there is no viewBox use a default of 300 or the largest size that fits into the outer viewport // at an aspect ratio of 2:1 width = Math.min(300, context.viewport.width, context.viewport.height * 2); } } } } else { var widthAttr = getAttribute(this.element, context.styleSheets, 'width'); width = widthAttr ? parseFloat(widthAttr) : context.viewport.width; } return this.width = width; }; Svg.prototype.getHeight = function (context) { if (this.height !== undefined) { return this.height; } var height; var parameters = context.svg2pdfParameters; if (this.isOutermostSvg(context)) { // special treatment for the outermost SVG element if (parameters.height != null) { // if there is a user defined height, use it height = parameters.height; } else { // otherwise check if the SVG element defines the height itself var heightAttr = getAttribute(this.element, context.styleSheets, 'height'); if (heightAttr) { height = parseFloat(heightAttr); } else { // if not, check if we can figure out the aspect ratio from the viewBox attribute var viewBox = this.getViewBox(); if (viewBox) { // if there is a viewBox, use the height that matches the width together with the aspect ratio var aspectRatio = viewBox[2] / viewBox[3]; height = this.getWidth(context) / aspectRatio; } else { // if there is no viewBox use a default of 150 or the largest size that fits into the outer viewport // at an aspect ratio of 2:1 height = Math.min(150, context.viewport.width / 2, context.viewport.height); } } } } else { var heightAttr = getAttribute(this.element, context.styleSheets, 'height'); height = heightAttr ? parseFloat(heightAttr) : context.viewport.height; } return this.height = height; }; Svg.prototype.getX = function (context) { if (this.x !== undefined) { return this.x; } if (this.isOutermostSvg(context)) { return this.x = 0; } var xAttr = getAttribute(this.element, context.styleSheets, 'x'); return this.x = xAttr ? parseFloat(xAttr) : 0; }; Svg.prototype.getY = function (context) { if (this.y !== undefined) { return this.y; } if (this.isOutermostSvg(context)) { return this.y = 0; } var yAttr = getAttribute(this.element, context.styleSheets, 'y'); return this.y = yAttr ? parseFloat(yAttr) : 0; }; Svg.prototype.getViewBox = function () { if (this.viewBox !== undefined) { return this.viewBox; } var viewBox = this.element.getAttribute('viewBox'); return this.viewBox = viewBox ? parseFloats(viewBox) : undefined; }; Svg.prototype.isOutermostSvg = function (context) { return context.svg2pdfParameters.element === this.element; }; return Svg; }(ContainerNode); var Group = /** @class */ function (_super) { __extends(Group, _super); function Group() { return _super !== null && _super.apply(this, arguments) || this; } Group.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; Group.prototype.computeNodeTransformCore = function (context) { return context.pdf.unitMatrix; }; return Group; }(ContainerNode); var ClipPath = /** @class */ function (_super) { __extends(ClipPath, _super); function ClipPath() { return _super !== null && _super.apply(this, arguments) || this; } ClipPath.prototype.apply = function (context) { return __awaiter(this, void 0, void 0, function () { var clipPathMatrix, _i, _a, child; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!this.isVisible(true, context)) { return [2 /*return*/ ]; } clipPathMatrix = context.pdf.matrixMult(this.computeNodeTransform(context), context.transform); context.pdf.setCurrentTransformationMatrix(clipPathMatrix); _i = 0, _a = this.children; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/ , 4]; child = _a[_i]; return [4 /*yield*/ , child.render(new Context(context.pdf, { refsHandler: context.refsHandler, styleSheets: context.styleSheets, viewport: context.viewport, withinClipPath: true, svg2pdfParameters: context.svg2pdfParameters }))]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/ , 1]; case 4: context.pdf.clip().discardPath(); // as we cannot use restoreGraphicsState() to reset the transform (this would reset the clipping path, as well), // we must append the inverse instead context.pdf.setCurrentTransformationMatrix(clipPathMatrix.inversed()); return [2 /*return*/ ]; } }); }); }; ClipPath.prototype.getBoundingBoxCore = function (context) { return getBoundingBoxByChildren(context, this); }; ClipPath.prototype.isVisible = function (parentVisible, context) { return svgNodeAndChildrenVisible(this, parentVisible, context); }; return ClipPath; }(NonRenderedNode); function parse$1(node, idMap) { var svgnode; var children = []; forEachChild(node, function (i, n) { return children.push(parse$1(n, idMap)); }); switch (node.tagName.toLowerCase()) { case 'a': case 'g': svgnode = new Group(node, children); break; case 'circle': svgnode = new Circle(node, children); break; case 'clippath': svgnode = new ClipPath(node, children); break; case 'ellipse': svgnode = new Ellipse$1(node, children); break; case 'lineargradient': svgnode = new LinearGradient(node, children); break; case 'image': svgnode = new ImageNode(node, children); break; case 'line': svgnode = new Line(node, children); break; case 'marker': svgnode = new MarkerNode(node, children); break; case 'path': svgnode = new PathNode(node, children); break; case 'pattern': svgnode = new Pattern(node, children); break; case 'polygon': svgnode = new Polygon(node, children); break; case 'polyline': svgnode = new Polyline(node, children); break; case 'radialgradient': svgnode = new RadialGradient(node, children); break; case 'rect': svgnode = new Rect(node, children); break; case 'svg': svgnode = new Svg(node, children); break; case 'symbol': svgnode = new Symbol$1(node, children); break; case 'text': svgnode = new TextNode(node, children); break; case 'use': svgnode = new Use(node, children); break; default: svgnode = new VoidNode(node, children); break; } if (idMap != undefined && svgnode.element.hasAttribute('id')) { var id = cssesc_1(svgnode.element.id, { isIdentifier: true }); idMap[id] = idMap[id] || svgnode; } return svgnode; } var StyleSheets = /** @class */ function () { function StyleSheets(rootSvg, loadExtSheets) { this.rootSvg = rootSvg; this.loadExternalSheets = loadExtSheets; this.styleSheets = []; } StyleSheets.prototype.load = function () { return __awaiter(this, void 0, void 0, function () { var sheetTexts; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/ , this.collectStyleSheetTexts()]; case 1: sheetTexts = _a.sent(); this.parseCssSheets(sheetTexts); return [2 /*return*/ ]; } }); }); }; StyleSheets.prototype.collectStyleSheetTexts = function () { return __awaiter(this, void 0, void 0, function () { var sheetTexts, i, node, styleElements, i, styleElement; return __generator(this, function (_a) { switch (_a.label) { case 0: sheetTexts = []; if (this.loadExternalSheets && this.rootSvg.ownerDocument) { for (i = 0; i < this.rootSvg.ownerDocument.childNodes.length; i++) { node = this.rootSvg.ownerDocument.childNodes[i]; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore if (node.nodeName === 'xml-stylesheet' && typeof node.data === 'string') { sheetTexts.push(StyleSheets.loadSheet( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore node.data.match(/href=["'].*?["']/)[0].split('=')[1].slice(1, -1))); } } } styleElements = this.rootSvg.querySelectorAll('style,link'); for (i = 0; i < styleElements.length; i++) { styleElement = styleElements[i]; if (nodeIs(styleElement, 'style')) { sheetTexts.push(styleElement.textContent); } else if (this.loadExternalSheets && nodeIs(styleElement, 'link') && styleElement.getAttribute('rel') === 'stylesheet' && styleElement.hasAttribute('href')) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion sheetTexts.push(StyleSheets.loadSheet(styleElement.getAttribute('href'))); } } return [4 /*yield*/ , Promise.all(sheetTexts)]; case 1: return [2 /*return*/ , _a.sent().filter(function (sheet) { return sheet !== null; })]; } }); }); }; StyleSheets.prototype.parseCssSheets = function (sheetTexts) { var styleDoc = document.implementation.createHTMLDocument(''); for (var _i = 0, sheetTexts_1 = sheetTexts; _i < sheetTexts_1.length; _i++) { var sheetText = sheetTexts_1[_i]; var style = styleDoc.createElement('style'); style.textContent = sheetText; styleDoc.body.appendChild(style); var sheet = style.sheet; if (sheet instanceof CSSStyleSheet) { for (var i = sheet.cssRules.length - 1; i >= 0; i--) { var cssRule = sheet.cssRules[i]; if (!(cssRule instanceof CSSStyleRule)) { sheet.deleteRule(i); } var cssStyleRule = cssRule; if (cssStyleRule.selectorText.indexOf(',') >= 0) { sheet.deleteRule(i); var body = cssStyleRule.cssText.substring(cssStyleRule.selectorText.length); var selectors = StyleSheets.splitSelectorAtCommas(cssStyleRule.selectorText); for (var j = 0; j < selectors.length; j++) { sheet.insertRule(selectors[j] + body, i + j); } } } this.styleSheets.push(sheet); } } }; StyleSheets.splitSelectorAtCommas = function (selectorText) { var initialRegex = /,|["']/g; var closingDoubleQuotesRegex = /[^\\]["]/g; var closingSingleQuotesRegex = /[^\\][']/g; var parts = []; var state = 'initial'; var match; var lastCommaIndex = -1; var closingQuotesRegex = closingDoubleQuotesRegex; for (var i = 0; i < selectorText.length;) { switch (state) { case 'initial': initialRegex.lastIndex = i; match = initialRegex.exec(selectorText); if (match) { if (match[0] === ',') { parts.push(selectorText.substring(lastCommaIndex + 1, initialRegex.lastIndex - 1).trim()); lastCommaIndex = initialRegex.lastIndex - 1; } else { state = 'withinQuotes'; closingQuotesRegex = match[0] === '"' ? closingDoubleQuotesRegex : closingSingleQuotesRegex; } i = initialRegex.lastIndex; } else { parts.push(selectorText.substring(lastCommaIndex + 1).trim()); i = selectorText.length; } break; case 'withinQuotes': closingQuotesRegex.lastIndex = i; match = closingQuotesRegex.exec(selectorText); if (match) { i = closingQuotesRegex.lastIndex; state = 'initial'; } // else this is a syntax error - omit the last part... break; } } return parts; }; StyleSheets.loadSheet = function (url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'text'; xhr.onload = function () { if (xhr.status !== 200) { reject(new Error("Error " + xhr.status + ": Failed to load '" + url + "'")); } resolve(xhr.responseText); }; xhr.onerror = reject; xhr.onabort = reject; xhr.send(null); }) // ignore the error since some stylesheets may not be accessible // due to CORS policies ["catch"](function () { return null; }); }; StyleSheets.prototype.getPropertyValue = function (node, propertyCss) { var matchingRules = []; for (var _i = 0, _a = this.styleSheets; _i < _a.length; _i++) { var sheet = _a[_i]; for (var i = 0; i < sheet.cssRules.length; i++) { var rule = sheet.cssRules[i]; if (rule.style.getPropertyValue(propertyCss) && node.matches(rule.selectorText)) { matchingRules.push(rule); } } } if (matchingRules.length === 0) { return undefined; } var compare$1 = function compare$1(a, b) { var priorityA = a.style.getPropertyPriority(propertyCss); var priorityB = b.style.getPropertyPriority(propertyCss); if (priorityA !== priorityB) { return priorityA === 'important' ? 1 : -1; } return compare(a.selectorText, b.selectorText); }; var mostSpecificRule = matchingRules.reduce(function (previousValue, currentValue) { return compare$1(previousValue, currentValue) === 1 ? previousValue : currentValue; }); return mostSpecificRule.style.getPropertyValue(propertyCss) || undefined; }; return StyleSheets; }(); function svg2pdf(element, pdf, options) { var _a, _b, _c; if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var x, y, extCss, idMap, refsHandler, styleSheets, viewport, svg2pdfParameters, context, fill, node; return __generator(this, function (_d) { switch (_d.label) { case 0: x = (_a = options.x) !== null && _a !== void 0 ? _a : 0.0; y = (_b = options.y) !== null && _b !== void 0 ? _b : 0.0; extCss = (_c = options.loadExternalStyleSheets) !== null && _c !== void 0 ? _c : false; idMap = {}; refsHandler = new ReferencesHandler(idMap); styleSheets = new StyleSheets(element, extCss); return [4 /*yield*/ , styleSheets.load() // start with the entire page size as viewport ]; case 1: _d.sent(); viewport = new Viewport(pdf.internal.pageSize.getWidth(), pdf.internal.pageSize.getHeight()); svg2pdfParameters = _assign(_assign({}, options), { element: element }); context = new Context(pdf, { refsHandler: refsHandler, styleSheets: styleSheets, viewport: viewport, svg2pdfParameters: svg2pdfParameters }); pdf.advancedAPI(); pdf.saveGraphicsState(); // set offsets pdf.setCurrentTransformationMatrix(pdf.Matrix(1, 0, 0, 1, x, y)); // set default values that differ from pdf defaults pdf.setLineWidth(context.attributeState.strokeWidth); fill = context.attributeState.fill.color; pdf.setFillColor(fill.r, fill.g, fill.b); pdf.setFont(context.attributeState.fontFamily); // correct for a jsPDF-instance measurement unit that differs from `pt` pdf.setFontSize(context.attributeState.fontSize * pdf.internal.scaleFactor); node = parse$1(element, idMap); return [4 /*yield*/ , node.render(context)]; case 2: _d.sent(); pdf.restoreGraphicsState(); pdf.compatAPI(); context.textMeasure.cleanupTextMeasuring(); return [2 /*return*/ , pdf]; } }); }); } g.API.svg = function (element, options) { if (options === void 0) { options = {}; } return svg2pdf(element, this, options); }; /** * For parsing color values. * @module RGBColor * @author Stoyan Stefanov <sstoo@gmail.com> * @see https://www.phpied.com/rgb-color-parser-in-javascript/ * @license MIT */ var simpleColors = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000', blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dodgerblue: '1e90ff', feldspar: 'd19275', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', greenyellow: 'adff2f', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred: 'cd5c5c', indigo: '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgrey: 'd3d3d3', lightgreen: '90ee90', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslateblue: '8470ff', lightslategray: '778899', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370d8', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'd87093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', violetred: 'd02090', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5', yellow: 'ffff00', yellowgreen: '9acd32' }; // array of color definition objects var colorDefs = [{ re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, // re: /^rgb\((?<r>\d{1,3}),\s*(?<g>\d{1,3}),\s*(?<b>\d{1,3})\)$/, example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], process: function process(_) { for (var _len = arguments.length, bits = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { bits[_key - 1] = arguments[_key]; } return bits.map(function (b) { return Number.parseInt(b); }); } }, { re: /^(\w{2})(\w{2})(\w{2})$/, // re: /^(?<r>\w{2})(?<g>\w{2})(?<b>\w{2})$/, example: ['#00ff00', '336699'], process: function process(_) { for (var _len2 = arguments.length, bits = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { bits[_key2 - 1] = arguments[_key2]; } return bits.map(function (b) { return Number.parseInt(b, 16); }); } }, { re: /^(\w)(\w)(\w)$/, // re: /^(?<r>\w{1})(?<g>\w{1})(?<b>\w{1})$/, example: ['#fb0', 'f0f'], process: function process(_) { for (var _len3 = arguments.length, bits = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { bits[_key3 - 1] = arguments[_key3]; } return bits.map(function (b) { return Number.parseInt(b + b, 16); }); } }]; /** * A class to parse color values. */ var RGBColor$2 = /*#__PURE__*/function () { /** * @param {string} colorString */ function RGBColor(colorString) { var _this = this; _classCallCheck(this, RGBColor); this.ok = false; // strip any leading # if (colorString.charAt(0) === '#') { // remove # if any colorString = colorString.substr(1, 6); } colorString = colorString.replace(/ /g, ''); colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches // and overwrite the input if (colorString in simpleColors) { colorString = simpleColors[colorString]; } // end of simple type-in colors // search through the definitions to find a match colorDefs.forEach(function (_ref) { var re = _ref.re, processor = _ref.process; var bits = re.exec(colorString); if (bits) { var _processor = processor.apply(void 0, _toConsumableArray(bits)), _processor2 = _slicedToArray(_processor, 3), r = _processor2[0], g = _processor2[1], b = _processor2[2]; Object.assign(_this, { r: r, g: g, b: b }); _this.ok = true; } }); // validate/cleanup values this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r; this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g; this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b; } // some getters /** * @returns {string} */ _createClass(RGBColor, [{ key: "toRGB", value: function toRGB() { return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; } /** * @returns {string} */ }, { key: "toHex", value: function toHex() { var r = this.r.toString(16); var g = this.g.toString(16); var b = this.b.toString(16); if (r.length === 1) { r = '0' + r; } if (g.length === 1) { g = '0' + g; } if (b.length === 1) { b = '0' + b; } return '#' + r + g + b; } /** * Offers a bulleted list of help. * @returns {HTMLUListElement} */ }], [{ key: "getHelpXML", value: function getHelpXML() { var examples = [].concat(_toConsumableArray(colorDefs.flatMap(function (_ref2) { var example = _ref2.example; return example; })), _toConsumableArray(Object.keys(simpleColors))); var xml = document.createElement('ul'); xml.setAttribute('id', 'rgbcolor-examples'); xml.append.apply(xml, _toConsumableArray(examples.map(function (example) { try { var listItem = document.createElement('li'); var listColor = new RGBColor(example); var exampleDiv = document.createElement('div'); exampleDiv.style.cssText = "\n margin: 3px;\n border: 1px solid black;\n background: ".concat(listColor.toHex(), ";\n color: ").concat(listColor.toHex(), ";"); exampleDiv.append('test'); var listItemValue = " ".concat(example, " -> ").concat(listColor.toRGB(), " -> ").concat(listColor.toHex()); listItem.append(exampleDiv, listItemValue); return listItem; } catch (e) { return ''; } }))); return xml; } }]); return RGBColor; }(); function _typeof$1(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); } function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /* eslint-disable no-bitwise, unicorn/prefer-query-selector */ /** * StackBlur - a fast almost Gaussian Blur For Canvas * * In case you find this class useful - especially in commercial projects - * I am not totally unhappy for a small donation to my PayPal account * mario@quasimondo.de * * Or support me on flattr: * {@link https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript}. * * @module StackBlur * @author Mario Klingemann * Contact: mario@quasimondo.com * Website: {@link http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html} * Twitter: @quasimondo * * @copyright (c) 2010 Mario Klingemann * * 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. */ /* eslint-disable max-len */ var mulTable = [512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456, 437, 420, 404, 388, 374, 360, 347, 335, 323, 312, 302, 292, 282, 273, 265, 512, 497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328, 320, 312, 305, 298, 291, 284, 278, 271, 265, 259, 507, 496, 485, 475, 465, 456, 446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335, 329, 323, 318, 312, 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512, 505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405, 399, 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328, 324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278, 274, 271, 268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456, 451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408, 404, 400, 396, 392, 388, 385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323, 320, 318, 315, 312, 310, 307, 304, 302, 299, 297, 294, 292, 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259]; var shgTable = [9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24]; /** * @param {string|HTMLCanvasElement} canvas * @param {Integer} topX * @param {Integer} topY * @param {Integer} width * @param {Integer} height * @throws {Error|TypeError} * @returns {ImageData} See {@link https://html.spec.whatwg.org/multipage/canvas.html#imagedata} */ function getImageDataFromCanvas(canvas, topX, topY, width, height) { if (typeof canvas === 'string') { canvas = document.getElementById(canvas); } if (!canvas || _typeof$1(canvas) !== 'object' || !('getContext' in canvas)) { throw new TypeError('Expecting canvas with `getContext` method ' + 'in processCanvasRGB(A) calls!'); } var context = canvas.getContext('2d'); try { return context.getImageData(topX, topY, width, height); } catch (e) { throw new Error('unable to access image data: ' + e); } } /** * @param {HTMLCanvasElement} canvas * @param {Integer} topX * @param {Integer} topY * @param {Integer} width * @param {Integer} height * @param {Float} radius * @returns {undefined} */ function processCanvasRGBA(canvas, topX, topY, width, height, radius) { if (isNaN(radius) || radius < 1) { return; } radius |= 0; var imageData = getImageDataFromCanvas(canvas, topX, topY, width, height); imageData = processImageDataRGBA(imageData, topX, topY, width, height, radius); canvas.getContext('2d').putImageData(imageData, topX, topY); } /** * @param {ImageData} imageData * @param {Integer} topX * @param {Integer} topY * @param {Integer} width * @param {Integer} height * @param {Float} radius * @returns {ImageData} */ function processImageDataRGBA(imageData, topX, topY, width, height, radius) { var pixels = imageData.data; var x, y, i, p, yp, yi, yw, rSum, gSum, bSum, aSum, rOutSum, gOutSum, bOutSum, aOutSum, rInSum, gInSum, bInSum, aInSum, pr, pg, pb, pa, rbs; var div = 2 * radius + 1; // const w4 = width << 2; var widthMinus1 = width - 1; var heightMinus1 = height - 1; var radiusPlus1 = radius + 1; var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2; var stackStart = new BlurStack(); var stack = stackStart; var stackEnd; for (i = 1; i < div; i++) { stack = stack.next = new BlurStack(); if (i === radiusPlus1) { stackEnd = stack; } } stack.next = stackStart; var stackIn = null; var stackOut = null; yw = yi = 0; var mulSum = mulTable[radius]; var shgSum = shgTable[radius]; for (y = 0; y < height; y++) { rInSum = gInSum = bInSum = aInSum = rSum = gSum = bSum = aSum = 0; rOutSum = radiusPlus1 * (pr = pixels[yi]); gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); rSum += sumFactor * pr; gSum += sumFactor * pg; bSum += sumFactor * pb; aSum += sumFactor * pa; stack = stackStart; for (i = 0; i < radiusPlus1; i++) { stack.r = pr; stack.g = pg; stack.b = pb; stack.a = pa; stack = stack.next; } for (i = 1; i < radiusPlus1; i++) { p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2); rSum += (stack.r = pr = pixels[p]) * (rbs = radiusPlus1 - i); gSum += (stack.g = pg = pixels[p + 1]) * rbs; bSum += (stack.b = pb = pixels[p + 2]) * rbs; aSum += (stack.a = pa = pixels[p + 3]) * rbs; rInSum += pr; gInSum += pg; bInSum += pb; aInSum += pa; stack = stack.next; } stackIn = stackStart; stackOut = stackEnd; for (x = 0; x < width; x++) { pixels[yi + 3] = pa = aSum * mulSum >> shgSum; if (pa !== 0) { pa = 255 / pa; pixels[yi] = (rSum * mulSum >> shgSum) * pa; pixels[yi + 1] = (gSum * mulSum >> shgSum) * pa; pixels[yi + 2] = (bSum * mulSum >> shgSum) * pa; } else { pixels[yi] = pixels[yi + 1] = pixels[yi + 2] = 0; } rSum -= rOutSum; gSum -= gOutSum; bSum -= bOutSum; aSum -= aOutSum; rOutSum -= stackIn.r; gOutSum -= stackIn.g; bOutSum -= stackIn.b; aOutSum -= stackIn.a; p = yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1) << 2; rInSum += stackIn.r = pixels[p]; gInSum += stackIn.g = pixels[p + 1]; bInSum += stackIn.b = pixels[p + 2]; aInSum += stackIn.a = pixels[p + 3]; rSum += rInSum; gSum += gInSum; bSum += bInSum; aSum += aInSum; stackIn = stackIn.next; rOutSum += pr = stackOut.r; gOutSum += pg = stackOut.g; bOutSum += pb = stackOut.b; aOutSum += pa = stackOut.a; rInSum -= pr; gInSum -= pg; bInSum -= pb; aInSum -= pa; stackOut = stackOut.next; yi += 4; } yw += width; } for (x = 0; x < width; x++) { gInSum = bInSum = aInSum = rInSum = gSum = bSum = aSum = rSum = 0; yi = x << 2; rOutSum = radiusPlus1 * (pr = pixels[yi]); gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); rSum += sumFactor * pr; gSum += sumFactor * pg; bSum += sumFactor * pb; aSum += sumFactor * pa; stack = stackStart; for (i = 0; i < radiusPlus1; i++) { stack.r = pr; stack.g = pg; stack.b = pb; stack.a = pa; stack = stack.next; } yp = width; for (i = 1; i <= radius; i++) { yi = yp + x << 2; rSum += (stack.r = pr = pixels[yi]) * (rbs = radiusPlus1 - i); gSum += (stack.g = pg = pixels[yi + 1]) * rbs; bSum += (stack.b = pb = pixels[yi + 2]) * rbs; aSum += (stack.a = pa = pixels[yi + 3]) * rbs; rInSum += pr; gInSum += pg; bInSum += pb; aInSum += pa; stack = stack.next; if (i < heightMinus1) { yp += width; } } yi = x; stackIn = stackStart; stackOut = stackEnd; for (y = 0; y < height; y++) { p = yi << 2; pixels[p + 3] = pa = aSum * mulSum >> shgSum; if (pa > 0) { pa = 255 / pa; pixels[p] = (rSum * mulSum >> shgSum) * pa; pixels[p + 1] = (gSum * mulSum >> shgSum) * pa; pixels[p + 2] = (bSum * mulSum >> shgSum) * pa; } else { pixels[p] = pixels[p + 1] = pixels[p + 2] = 0; } rSum -= rOutSum; gSum -= gOutSum; bSum -= bOutSum; aSum -= aOutSum; rOutSum -= stackIn.r; gOutSum -= stackIn.g; bOutSum -= stackIn.b; aOutSum -= stackIn.a; p = x + ((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width << 2; rSum += rInSum += stackIn.r = pixels[p]; gSum += gInSum += stackIn.g = pixels[p + 1]; bSum += bInSum += stackIn.b = pixels[p + 2]; aSum += aInSum += stackIn.a = pixels[p + 3]; stackIn = stackIn.next; rOutSum += pr = stackOut.r; gOutSum += pg = stackOut.g; bOutSum += pb = stackOut.b; aOutSum += pa = stackOut.a; rInSum -= pr; gInSum -= pg; bInSum -= pb; aInSum -= pa; stackOut = stackOut.next; yi += width; } } return imageData; } /** * */ var BlurStack = /** * Set properties. */ function BlurStack() { _classCallCheck$1(this, BlurStack); this.r = 0; this.g = 0; this.b = 0; this.a = 0; this.next = null; }; /** * Whether a value is `null` or `undefined`. * @param {any} val * @returns {boolean} */ var isNullish$1 = function isNullish(val) { return val === null || val === undefined; }; /** * @callback module:canvg.ForceRedraw * @returns {boolean} */ /** * @typedef {PlainObject} module:canvg.CanvgOptions * @property {boolean} ignoreMouse true => ignore mouse events * @property {boolean} ignoreAnimation true => ignore animations * @property {boolean} ignoreDimensions true => does not try to resize canvas * @property {boolean} ignoreClear true => does not clear canvas * @property {Integer} offsetX int => draws at a x offset * @property {Integer} offsetY int => draws at a y offset * @property {Integer} scaleWidth int => scales horizontally to width * @property {Integer} scaleHeight int => scales vertically to height * @property {module:canvg.ForceRedraw} forceRedraw function => will call the function on every frame, if it returns true, will redraw * @property {boolean} log Adds log function * @property {boolean} useCORS Whether to set CORS `crossOrigin` for the image to `Anonymous` */ /** * If called with no arguments, it will replace all `<svg>` elements on the page * with `<canvas>` elements. * @function module:canvg.canvg * @param {HTMLCanvasElement|string} target canvas element or the id of a canvas element * @param {string|XMLDocument} s - svg string, url to svg file, or xml document * @param {module:canvg.CanvgOptions} [opts] Optional hash of options * @returns {Promise<XMLDocument|XMLDocument[]>} All the function after the first render is completed with dom */ var canvg = function canvg(target, s, opts) { // no parameters if (isNullish$1(target) && isNullish$1(s) && isNullish$1(opts)) { var svgTags = document.querySelectorAll('svg'); return Promise.all(_toConsumableArray(svgTags).map(function (svgTag) { var c = document.createElement('canvas'); c.width = svgTag.clientWidth; c.height = svgTag.clientHeight; svgTag.before(c); svgTag.remove(); var div = document.createElement('div'); div.append(svgTag); return canvg(c, div.innerHTML); })); } if (typeof target === 'string') { target = document.getElementById(target); } // store class on canvas if (!isNullish$1(target.svg)) target.svg.stop(); var svg = build(opts || {}); // on i.e. 8 for flash canvas, we can't assign the property so check for it if (!(target.childNodes.length === 1 && target.childNodes[0].nodeName === 'OBJECT')) { target.svg = svg; } var ctx = target.getContext('2d'); if (typeof s.documentElement !== 'undefined') { // load from xml doc return svg.loadXmlDoc(ctx, s); } if (s.substr(0, 1) === '<') { // load from xml string return svg.loadXml(ctx, s); } // load from url return svg.load(ctx, s); }; /* eslint-disable jsdoc/check-types */ /** * @param {module:canvg.CanvgOptions} opts * @returns {object} * @todo Flesh out exactly what object is returned here (after updating to latest and reincluding our changes here and those of StackBlur) */ function build(opts) { /* eslint-enable jsdoc/check-types */ var svg = { opts: opts }; svg.FRAMERATE = 30; svg.MAX_VIRTUAL_PIXELS = 30000; svg.log = function (msg) { /* */ }; if (svg.opts.log === true && typeof console !== 'undefined') { svg.log = function (msg) { console.log(msg); }; // eslint-disable-line no-console } // globals svg.init = function (ctx) { var uniqueId = 0; svg.UniqueId = function () { uniqueId++; return 'canvg' + uniqueId; }; svg.Definitions = {}; svg.Styles = {}; svg.Animations = []; svg.Images = []; svg.ctx = ctx; svg.ViewPort = { viewPorts: [], Clear: function Clear() { this.viewPorts = []; }, SetCurrent: function SetCurrent(width, height) { this.viewPorts.push({ width: width, height: height }); }, RemoveCurrent: function RemoveCurrent() { this.viewPorts.pop(); }, Current: function Current() { return this.viewPorts[this.viewPorts.length - 1]; }, width: function width() { return this.Current().width; }, height: function height() { return this.Current().height; }, ComputeSize: function ComputeSize(d) { if (!isNullish$1(d) && typeof d === 'number') return d; if (d === 'x') return this.width(); if (d === 'y') return this.height(); return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2); } }; }; svg.init(); // images loaded svg.ImagesLoaded = function () { return svg.Images.every(function (img) { return img.loaded; }); }; // trim svg.trim = function (s) { return s.replace(/^\s+|\s+$/g, ''); }; // compress spaces svg.compressSpaces = function (s) { return s.replace(/\s+/gm, ' '); }; // ajax // Todo: Replace with `fetch` and polyfill svg.ajax = function (url, asynch) { var AJAX = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP'); if (asynch) { return new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new var req = AJAX.open('GET', url, true); req.addEventListener('load', function () { resolve(AJAX.responseText); }); AJAX.send(null); }); } AJAX.open('GET', url, false); AJAX.send(null); return AJAX.responseText; }; // parse xml svg.parseXml = function (xml) { if (window.DOMParser) { var parser = new DOMParser(); return parser.parseFromString(xml, 'text/xml'); } xml = xml.replace(/<!DOCTYPE svg[^>]*>/, ''); var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM'); xmlDoc.async = 'false'; xmlDoc.loadXML(xml); return xmlDoc; }; // text extensions // get the text baseline var textBaselineMapping = { baseline: 'alphabetic', 'before-edge': 'top', 'text-before-edge': 'top', middle: 'middle', central: 'middle', 'after-edge': 'bottom', 'text-after-edge': 'bottom', ideographic: 'ideographic', alphabetic: 'alphabetic', hanging: 'hanging', mathematical: 'alphabetic' }; svg.Property = /*#__PURE__*/function () { function Property(name, value) { _classCallCheck(this, Property); this.name = name; this.value = value; } _createClass(Property, [{ key: "getValue", value: function getValue() { return this.value; } }, { key: "hasValue", value: function hasValue() { return !isNullish$1(this.value) && this.value !== ''; } // return the numerical value of the property }, { key: "numValue", value: function numValue() { if (!this.hasValue()) return 0; var n = Number.parseFloat(this.value); if (String(this.value).endsWith('%')) { n /= 100.0; } return n; } }, { key: "valueOrDefault", value: function valueOrDefault(def) { if (this.hasValue()) return this.value; return def; } }, { key: "numValueOrDefault", value: function numValueOrDefault(def) { if (this.hasValue()) return this.numValue(); return def; } // color extensions // augment the current color value with the opacity }, { key: "addOpacity", value: function addOpacity(opacityProp) { var newValue = this.value; if (!isNullish$1(opacityProp.value) && opacityProp.value !== '' && typeof this.value === 'string') { // can only add opacity to colors, not patterns var color = new RGBColor$2(this.value); if (color.ok) { newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacityProp.numValue() + ')'; } } return new svg.Property(this.name, newValue); } // definition extensions // get the definition from the definitions table }, { key: "getDefinition", value: function getDefinition() { var name = this.value.match(/#([^)'"]+)/); if (name) { name = name[1]; } if (!name) { name = this.value; } return svg.Definitions[name]; } }, { key: "isUrlDefinition", value: function isUrlDefinition() { return this.value.startsWith('url('); } }, { key: "getFillStyleDefinition", value: function getFillStyleDefinition(e, opacityProp) { var def = this.getDefinition(); // gradient if (!isNullish$1(def) && def.createGradient) { return def.createGradient(svg.ctx, e, opacityProp); } // pattern if (!isNullish$1(def) && def.createPattern) { if (def.getHrefAttribute().hasValue()) { var pt = def.attribute('patternTransform'); def = def.getHrefAttribute().getDefinition(); if (pt.hasValue()) { def.attribute('patternTransform', true).value = pt.value; } } return def.createPattern(svg.ctx, e); } return null; } // length extensions }, { key: "getDPI", value: function getDPI(viewPort) { return 96.0; // TODO: compute? } }, { key: "getEM", value: function getEM(viewPort) { var em = 12; var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); if (fontSize.hasValue()) em = fontSize.toPixels(viewPort); return em; } }, { key: "getUnits", value: function getUnits() { return String(this.value).replace(/[\d.-]/g, ''); } // get the length as pixels }, { key: "toPixels", value: function toPixels(viewPort, processPercent) { if (!this.hasValue()) return 0; var s = String(this.value); if (s.endsWith('em')) return this.numValue() * this.getEM(viewPort); if (s.endsWith('ex')) return this.numValue() * this.getEM(viewPort) / 2.0; if (s.endsWith('px')) return this.numValue(); if (s.endsWith('pt')) return this.numValue() * this.getDPI(viewPort) * (1.0 / 72.0); if (s.endsWith('pc')) return this.numValue() * 15; if (s.endsWith('cm')) return this.numValue() * this.getDPI(viewPort) / 2.54; if (s.endsWith('mm')) return this.numValue() * this.getDPI(viewPort) / 25.4; if (s.endsWith('in')) return this.numValue() * this.getDPI(viewPort); if (s.endsWith('%')) return this.numValue() * svg.ViewPort.ComputeSize(viewPort); var n = this.numValue(); if (processPercent && n < 1.0) return n * svg.ViewPort.ComputeSize(viewPort); return n; } // time extensions // get the time as milliseconds }, { key: "toMilliseconds", value: function toMilliseconds() { if (!this.hasValue()) return 0; var s = String(this.value); if (s.endsWith('ms')) return this.numValue(); if (s.endsWith('s')) return this.numValue() * 1000; return this.numValue(); } // angle extensions // get the angle as radians }, { key: "toRadians", value: function toRadians() { if (!this.hasValue()) return 0; var s = String(this.value); if (s.endsWith('deg')) return this.numValue() * (Math.PI / 180.0); if (s.endsWith('grad')) return this.numValue() * (Math.PI / 200.0); if (s.endsWith('rad')) return this.numValue(); return this.numValue() * (Math.PI / 180.0); } }, { key: "toTextBaseline", value: function toTextBaseline() { if (!this.hasValue()) return null; return textBaselineMapping[this.value]; } }]); return Property; }(); // fonts svg.Font = { Styles: 'normal|italic|oblique|inherit', Variants: 'normal|small-caps|inherit', Weights: 'normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit', CreateFont: function CreateFont(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) { var f = !isNullish$1(inherit) ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); return { fontFamily: fontFamily || f.fontFamily, fontSize: fontSize || f.fontSize, fontStyle: fontStyle || f.fontStyle, fontWeight: fontWeight || f.fontWeight, fontVariant: fontVariant || f.fontVariant, toString: function toString() { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' '); } }; }, Parse: function Parse(s) { var _this = this; var f = {}; var ds = svg.trim(svg.compressSpaces(s || '')).split(' '); var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false }; var ff = ''; ds.forEach(function (d) { if (!set.fontStyle && _this.Styles.includes(d)) { if (d !== 'inherit') { f.fontStyle = d; } set.fontStyle = true; } else if (!set.fontVariant && _this.Variants.includes(d)) { if (d !== 'inherit') { f.fontVariant = d; } set.fontStyle = set.fontVariant = true; } else if (!set.fontWeight && _this.Weights.includes(d)) { if (d !== 'inherit') { f.fontWeight = d; } set.fontStyle = set.fontVariant = set.fontWeight = true; } else if (!set.fontSize) { if (d !== 'inherit') { f.fontSize = d.split('/')[0]; } set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; } else if (d !== 'inherit') { ff += d; } }); if (ff !== '') { f.fontFamily = ff; } return f; } }; // points and paths svg.ToNumberArray = function (s) { var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); return a.map(function (_a) { return Number.parseFloat(_a); }); }; svg.Point = /*#__PURE__*/function () { function _class(x, y) { _classCallCheck(this, _class); this.x = x; this.y = y; } _createClass(_class, [{ key: "angleTo", value: function angleTo(p) { return Math.atan2(p.y - this.y, p.x - this.x); } }, { key: "applyTransform", value: function applyTransform(v) { var xp = this.x * v[0] + this.y * v[2] + v[4]; var yp = this.x * v[1] + this.y * v[3] + v[5]; this.x = xp; this.y = yp; } }]); return _class; }(); svg.CreatePoint = function (s) { var a = svg.ToNumberArray(s); return new svg.Point(a[0], a[1]); }; svg.CreatePath = function (s) { var a = svg.ToNumberArray(s); var path = []; for (var i = 0; i < a.length; i += 2) { path.push(new svg.Point(a[i], a[i + 1])); } return path; }; // bounding box svg.BoundingBox = /*#__PURE__*/function () { function _class2(x1, y1, x2, y2) { _classCallCheck(this, _class2); // pass in initial points if you want this.x1 = Number.NaN; this.y1 = Number.NaN; this.x2 = Number.NaN; this.y2 = Number.NaN; this.addPoint(x1, y1); this.addPoint(x2, y2); } _createClass(_class2, [{ key: "x", value: function x() { return this.x1; } }, { key: "y", value: function y() { return this.y1; } }, { key: "width", value: function width() { return this.x2 - this.x1; } }, { key: "height", value: function height() { return this.y2 - this.y1; } }, { key: "addPoint", value: function addPoint(x, y) { if (!isNullish$1(x)) { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; } if (x < this.x1) this.x1 = x; if (x > this.x2) this.x2 = x; } if (!isNullish$1(y)) { if (isNaN(this.y1) || isNaN(this.y2)) { this.y1 = y; this.y2 = y; } if (y < this.y1) this.y1 = y; if (y > this.y2) this.y2 = y; } } }, { key: "addX", value: function addX(x) { this.addPoint(x, null); } }, { key: "addY", value: function addY(y) { this.addPoint(null, y); } }, { key: "addBoundingBox", value: function addBoundingBox(bb) { this.addPoint(bb.x1, bb.y1); this.addPoint(bb.x2, bb.y2); } }, { key: "addQuadraticCurve", value: function addQuadraticCurve(p0x, p0y, p1x, p1y, p2x, p2y) { var cp1x = p0x + 2 / 3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp1y = p0y + 2 / 3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp2x = cp1x + 1 / 3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) var cp2y = cp1y + 1 / 3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); } }, { key: "addBezierCurve", value: function addBezierCurve(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { var _this2 = this; // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y]; this.addPoint(p0[0], p0[1]); this.addPoint(p3[0], p3[1]); var _loop = function _loop(i) { var f = function f(t) { return Math.pow(1 - t, 3) * p0[i] + 3 * Math.pow(1 - t, 2) * t * p1[i] + 3 * (1 - t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; }; var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; var c = 3 * p1[i] - 3 * p0[i]; if (a === 0) { if (b === 0) return "continue"; var t = -c / b; if (t > 0 && t < 1) { if (i === 0) _this2.addX(f(t)); if (i === 1) _this2.addY(f(t)); } return "continue"; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) return "continue"; var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (t1 > 0 && t1 < 1) { if (i === 0) _this2.addX(f(t1)); if (i === 1) _this2.addY(f(t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (t2 > 0 && t2 < 1) { if (i === 0) _this2.addX(f(t2)); if (i === 1) _this2.addY(f(t2)); } }; for (var i = 0; i <= 1; i++) { var _ret = _loop(i); if (_ret === "continue") continue; } } }, { key: "isPointInBox", value: function isPointInBox(x, y) { return this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2; } }]); return _class2; }(); // transforms svg.Transform = /*#__PURE__*/function () { function _class3(v) { var _this6 = this; _classCallCheck(this, _class3); this.Type = { translate: function translate(s) { _classCallCheck(this, translate); this.p = svg.CreatePoint(s); this.apply = function (ctx) { ctx.translate(this.p.x || 0.0, this.p.y || 0.0); }; this.unapply = function (ctx) { ctx.translate(-1.0 * this.p.x || 0.0, -1.0 * this.p.y || 0.0); }; this.applyToPoint = function (p) { p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); }; }, rotate: function rotate(s) { _classCallCheck(this, rotate); var a = svg.ToNumberArray(s); this.angle = new svg.Property('angle', a[0]); this.cx = a[1] || 0; this.cy = a[2] || 0; this.apply = function (ctx) { ctx.translate(this.cx, this.cy); ctx.rotate(this.angle.toRadians()); ctx.translate(-this.cx, -this.cy); }; this.unapply = function (ctx) { ctx.translate(this.cx, this.cy); ctx.rotate(-1.0 * this.angle.toRadians()); ctx.translate(-this.cx, -this.cy); }; this.applyToPoint = function (p) { var _a = this.angle.toRadians(); p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); p.applyTransform([Math.cos(_a), Math.sin(_a), -Math.sin(_a), Math.cos(_a), 0, 0]); p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); }; }, scale: function scale(s) { _classCallCheck(this, scale); this.p = svg.CreatePoint(s); this.apply = function (ctx) { ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); }; this.unapply = function (ctx) { ctx.scale(1.0 / this.p.x || 1.0, 1.0 / this.p.y || this.p.x || 1.0); }; this.applyToPoint = function (p) { p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); }; }, matrix: function matrix(s) { _classCallCheck(this, matrix); this.m = svg.ToNumberArray(s); this.apply = function (ctx) { ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); }; this.applyToPoint = function (p) { p.applyTransform(this.m); }; } }; Object.assign(this.Type, { SkewBase: /*#__PURE__*/function (_this$Type$matrix) { _inherits(SkewBase, _this$Type$matrix); var _super = _createSuper(SkewBase); function SkewBase(s) { var _this3; _classCallCheck(this, SkewBase); _this3 = _super.call(this, s); _this3.angle = new svg.Property('angle', s); return _this3; } return SkewBase; }(this.Type.matrix) }); Object.assign(this.Type, { skewX: /*#__PURE__*/function (_this$Type$SkewBase) { _inherits(skewX, _this$Type$SkewBase); var _super2 = _createSuper(skewX); function skewX(s) { var _this4; _classCallCheck(this, skewX); _this4 = _super2.call(this, s); _this4.m = [1, 0, Math.tan(_this4.angle.toRadians()), 1, 0, 0]; return _this4; } return skewX; }(this.Type.SkewBase), skewY: /*#__PURE__*/function (_this$Type$SkewBase2) { _inherits(skewY, _this$Type$SkewBase2); var _super3 = _createSuper(skewY); function skewY(s) { var _this5; _classCallCheck(this, skewY); _this5 = _super3.call(this, s); _this5.m = [1, Math.tan(_this5.angle.toRadians()), 0, 1, 0, 0]; return _this5; } return skewY; }(this.Type.SkewBase) }); var data = svg.trim(svg.compressSpaces(v)).replace(/\)([a-zA-Z])/g, ') $1').replace(/\)(\s?,\s?)/g, ') ').split(/\s(?=[a-z])/); this.transforms = data.map(function (d) { var type = svg.trim(d.split('(')[0]); var s = d.split('(')[1].replace(')', ''); var transform = new _this6.Type[type](s); transform.type = type; return transform; }); } _createClass(_class3, [{ key: "apply", value: function apply(ctx) { this.transforms.forEach(function (transform) { transform.apply(ctx); }); } }, { key: "unapply", value: function unapply(ctx) { for (var i = this.transforms.length - 1; i >= 0; i--) { this.transforms[i].unapply(ctx); } } }, { key: "applyToPoint", value: function applyToPoint(p) { this.transforms.forEach(function (transform) { transform.applyToPoint(p); }); } }]); return _class3; }(); // aspect ratio svg.AspectRatio = function (ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { // aspect ratio - https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute aspectRatio = svg.compressSpaces(aspectRatio); aspectRatio = aspectRatio.replace(/^defer\s/, ''); // ignore defer var align = aspectRatio.split(' ')[0] || 'xMidYMid'; var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale var scaleX = width / desiredWidth; var scaleY = height / desiredHeight; var scaleMin = Math.min(scaleX, scaleY); var scaleMax = Math.max(scaleX, scaleY); if (meetOrSlice === 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; } if (meetOrSlice === 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; } refX = new svg.Property('refX', refX); refY = new svg.Property('refY', refY); if (refX.hasValue() && refY.hasValue()) { ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y')); } else { // align if (align.startsWith('xMid') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); } if (align.endsWith('YMid') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { ctx.translate(0, height / 2.0 - desiredHeight / 2.0); } if (align.startsWith('xMax') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { ctx.translate(width - desiredWidth, 0); } if (align.endsWith('YMax') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { ctx.translate(0, height - desiredHeight); } } // scale if (align === 'none') ctx.scale(scaleX, scaleY);else if (meetOrSlice === 'meet') ctx.scale(scaleMin, scaleMin);else if (meetOrSlice === 'slice') ctx.scale(scaleMax, scaleMax); // translate ctx.translate(isNullish$1(minX) ? 0 : -minX, isNullish$1(minY) ? 0 : -minY); }; // elements svg.Element = {}; svg.EmptyProperty = new svg.Property('EMPTY', ''); svg.Element.ElementBase = /*#__PURE__*/function () { function _class4(node) { var _this7 = this; _classCallCheck(this, _class4); // Argument from inheriting class this.captureTextNodes = arguments[1]; // eslint-disable-line prefer-rest-params this.attributes = {}; this.styles = {}; this.children = []; if (!isNullish$1(node) && node.nodeType === 1) { // ELEMENT_NODE // add children _toConsumableArray(node.childNodes).forEach(function (childNode) { if (childNode.nodeType === 1) { _this7.addChild(childNode, true); // ELEMENT_NODE } if (_this7.captureTextNodes && (childNode.nodeType === 3 || childNode.nodeType === 4)) { var text = childNode.nodeValue || childNode.text || ''; if (svg.trim(svg.compressSpaces(text)) !== '') { _this7.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE } } }); // add attributes _toConsumableArray(node.attributes).forEach(function (_ref) { var nodeName = _ref.nodeName, nodeValue = _ref.nodeValue; _this7.attributes[nodeName] = new svg.Property(nodeName, nodeValue); }); // add tag styles var styles = svg.Styles[node.nodeName]; if (!isNullish$1(styles)) { Object.entries(styles).forEach(function (_ref2) { var _ref3 = _slicedToArray(_ref2, 2), name = _ref3[0], styleValue = _ref3[1]; _this7.styles[name] = styleValue; }); } // add class styles if (this.attribute('class').hasValue()) { var classes = svg.compressSpaces(this.attribute('class').value).split(' '); classes.forEach(function (clss) { styles = svg.Styles['.' + clss]; if (!isNullish$1(styles)) { Object.entries(styles).forEach(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 2), name = _ref5[0], styleValue = _ref5[1]; _this7.styles[name] = styleValue; }); } styles = svg.Styles[node.nodeName + '.' + clss]; if (!isNullish$1(styles)) { Object.entries(styles).forEach(function (_ref6) { var _ref7 = _slicedToArray(_ref6, 2), name = _ref7[0], styleValue = _ref7[1]; _this7.styles[name] = styleValue; }); } }); } // add id styles if (this.attribute('id').hasValue()) { var _styles = svg.Styles['#' + this.attribute('id').value]; if (!isNullish$1(_styles)) { Object.entries(_styles).forEach(function (_ref8) { var _ref9 = _slicedToArray(_ref8, 2), name = _ref9[0], styleValue = _ref9[1]; _this7.styles[name] = styleValue; }); } } // add inline styles if (this.attribute('style').hasValue()) { var _styles2 = this.attribute('style').value.split(';'); _styles2.forEach(function (style) { if (svg.trim(style) !== '') { var _style$split = style.split(':'), name = _style$split.name, value = _style$split.value; name = svg.trim(name); value = svg.trim(value); _this7.styles[name] = new svg.Property(name, value); } }); } // add id if (this.attribute('id').hasValue()) { if (isNullish$1(svg.Definitions[this.attribute('id').value])) { svg.Definitions[this.attribute('id').value] = this; } } } } // get or create attribute _createClass(_class4, [{ key: "attribute", value: function attribute(name, createIfNotExists) { var a = this.attributes[name]; if (!isNullish$1(a)) return a; if (createIfNotExists === true) { a = new svg.Property(name, ''); this.attributes[name] = a; } return a || svg.EmptyProperty; } }, { key: "getHrefAttribute", value: function getHrefAttribute() { for (var a in this.attributes) { if (a.endsWith(':href')) { return this.attributes[a]; } } return svg.EmptyProperty; } // get or create style, crawls up node tree }, { key: "style", value: function style(name, createIfNotExists, skipAncestors) { var s = this.styles[name]; if (!isNullish$1(s)) return s; var a = this.attribute(name); if (!isNullish$1(a) && a.hasValue()) { this.styles[name] = a; // move up to me to cache return a; } if (skipAncestors !== true) { var p = this.parent; if (!isNullish$1(p)) { var ps = p.style(name); if (!isNullish$1(ps) && ps.hasValue()) { return ps; } } } if (createIfNotExists === true) { s = new svg.Property(name, ''); this.styles[name] = s; } return s || svg.EmptyProperty; } // base render }, { key: "render", value: function render(ctx) { // don't render display=none if (this.style('display').value === 'none') return; // don't render visibility=hidden if (this.style('visibility').value === 'hidden') return; ctx.save(); if (this.attribute('mask').hasValue()) { // mask var mask = this.attribute('mask').getDefinition(); if (!isNullish$1(mask)) mask.apply(ctx, this); } else if (this.style('filter').hasValue()) { // filter var filter = this.style('filter').getDefinition(); if (!isNullish$1(filter)) filter.apply(ctx, this); } else { this.setContext(ctx); this.renderChildren(ctx); this.clearContext(ctx); } ctx.restore(); } // base set context }, { key: "setContext", value: function setContext(ctx) {// OVERRIDE ME! } // base clear context }, { key: "clearContext", value: function clearContext(ctx) {// OVERRIDE ME! } // base render children }, { key: "renderChildren", value: function renderChildren(ctx) { this.children.forEach(function (child) { child.render(ctx); }); } }, { key: "addChild", value: function addChild(childNode, create) { var child = create ? svg.CreateElement(childNode) : childNode; child.parent = this; if (child.type !== 'title') { this.children.push(child); } } }]); return _class4; }(); svg.Element.RenderedElementBase = /*#__PURE__*/function (_svg$Element$ElementB) { _inherits(_class5, _svg$Element$ElementB); var _super4 = _createSuper(_class5); function _class5() { _classCallCheck(this, _class5); return _super4.apply(this, arguments); } _createClass(_class5, [{ key: "setContext", value: function setContext(ctx) { // fill if (this.style('fill').isUrlDefinition()) { var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity')); if (!isNullish$1(fs)) ctx.fillStyle = fs; } else if (this.style('fill').hasValue()) { var fillStyle = this.style('fill'); if (fillStyle.value === 'currentColor') fillStyle.value = this.style('color').value; ctx.fillStyle = fillStyle.value === 'none' ? 'rgba(0,0,0,0)' : fillStyle.value; } if (this.style('fill-opacity').hasValue()) { var _fillStyle = new svg.Property('fill', ctx.fillStyle); _fillStyle = _fillStyle.addOpacity(this.style('fill-opacity')); ctx.fillStyle = _fillStyle.value; } // stroke if (this.style('stroke').isUrlDefinition()) { var _fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity')); if (!isNullish$1(_fs)) ctx.strokeStyle = _fs; } else if (this.style('stroke').hasValue()) { var strokeStyle = this.style('stroke'); if (strokeStyle.value === 'currentColor') strokeStyle.value = this.style('color').value; ctx.strokeStyle = strokeStyle.value === 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value; } if (this.style('stroke-opacity').hasValue()) { var _strokeStyle = new svg.Property('stroke', ctx.strokeStyle); _strokeStyle = _strokeStyle.addOpacity(this.style('stroke-opacity')); ctx.strokeStyle = _strokeStyle.value; } if (this.style('stroke-width').hasValue()) { var newLineWidth = this.style('stroke-width').toPixels(); ctx.lineWidth = newLineWidth === 0 ? 0.001 : newLineWidth; // browsers don't respect 0 } if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value !== 'none') { var gaps = svg.ToNumberArray(this.style('stroke-dasharray').value); if (typeof ctx.setLineDash !== 'undefined') { ctx.setLineDash(gaps); } else if (typeof ctx.webkitLineDash !== 'undefined') { ctx.webkitLineDash = gaps; } else if (typeof ctx.mozDash !== 'undefined' && !(gaps.length === 1 && gaps[0] === 0)) { ctx.mozDash = gaps; } var offset = this.style('stroke-dashoffset').numValueOrDefault(1); if (typeof ctx.lineDashOffset !== 'undefined') { ctx.lineDashOffset = offset; } else if (typeof ctx.webkitLineDashOffset !== 'undefined') { ctx.webkitLineDashOffset = offset; } else if (typeof ctx.mozDashOffset !== 'undefined') { ctx.mozDashOffset = offset; } } // font if (typeof ctx.font !== 'undefined') { ctx.font = svg.Font.CreateFont(this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '', this.style('font-family').value).toString(); } // transform if (this.attribute('transform').hasValue()) { var transform = new svg.Transform(this.attribute('transform').value); transform.apply(ctx); } // clip if (this.style('clip-path', false, true).hasValue()) { var clip = this.style('clip-path', false, true).getDefinition(); if (!isNullish$1(clip)) clip.apply(ctx); } // opacity if (this.style('opacity').hasValue()) { ctx.globalAlpha = this.style('opacity').numValue(); } } }]); return _class5; }(svg.Element.ElementBase); svg.Element.PathElementBase = /*#__PURE__*/function (_svg$Element$Rendered) { _inherits(_class6, _svg$Element$Rendered); var _super5 = _createSuper(_class6); function _class6() { _classCallCheck(this, _class6); return _super5.apply(this, arguments); } _createClass(_class6, [{ key: "path", value: function path(ctx) { if (!isNullish$1(ctx)) ctx.beginPath(); return new svg.BoundingBox(); } }, { key: "renderChildren", value: function renderChildren(ctx) { this.path(ctx); svg.Mouse.checkPath(this, ctx); if (ctx.fillStyle !== '') { if (this.style('fill-rule').valueOrDefault('inherit') !== 'inherit') { ctx.fill(this.style('fill-rule').value); } else { ctx.fill(); } } if (ctx.strokeStyle !== '') ctx.stroke(); var markers = this.getMarkers(); if (!isNullish$1(markers)) { if (this.style('marker-start').isUrlDefinition()) { var marker = this.style('marker-start').getDefinition(); marker.render(ctx, markers[0][0], markers[0][1]); } if (this.style('marker-mid').isUrlDefinition()) { var _marker = this.style('marker-mid').getDefinition(); for (var i = 1; i < markers.length - 1; i++) { _marker.render(ctx, markers[i][0], markers[i][1]); } } if (this.style('marker-end').isUrlDefinition()) { var _marker2 = this.style('marker-end').getDefinition(); _marker2.render(ctx, markers[markers.length - 1][0], markers[markers.length - 1][1]); } } } }, { key: "getBoundingBox", value: function getBoundingBox() { return this.path(); } }, { key: "getMarkers", value: function getMarkers() { return null; } }]); return _class6; }(svg.Element.RenderedElementBase); // svg element svg.Element.svg = /*#__PURE__*/function (_svg$Element$Rendered2) { _inherits(_class7, _svg$Element$Rendered2); var _super6 = _createSuper(_class7); function _class7() { _classCallCheck(this, _class7); return _super6.apply(this, arguments); } _createClass(_class7, [{ key: "clearContext", value: function clearContext(ctx) { _get(_getPrototypeOf(_class7.prototype), "clearContext", this).call(this, ctx); svg.ViewPort.RemoveCurrent(); } }, { key: "setContext", value: function setContext(ctx) { // initial values and defaults ctx.strokeStyle = 'rgba(0,0,0,0)'; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; ctx.miterLimit = 4; if (typeof ctx.font !== 'undefined' && typeof window.getComputedStyle !== 'undefined') { ctx.font = window.getComputedStyle(ctx.canvas).getPropertyValue('font'); } _get(_getPrototypeOf(_class7.prototype), "setContext", this).call(this, ctx); // create new view port if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0; if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0; ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y')); var width = svg.ViewPort.width(); var height = svg.ViewPort.height(); if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%'; if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%'; if (typeof this.root === 'undefined') { width = this.attribute('width').toPixels('x'); height = this.attribute('height').toPixels('y'); var x = 0; var y = 0; if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { x = -this.attribute('refX').toPixels('x'); y = -this.attribute('refY').toPixels('y'); } if (this.attribute('overflow').valueOrDefault('hidden') !== 'visible') { ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(width, y); ctx.lineTo(width, height); ctx.lineTo(x, height); ctx.closePath(); ctx.clip(); } } svg.ViewPort.SetCurrent(width, height); // viewbox if (this.attribute('viewBox').hasValue()) { var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); var minX = viewBox[0]; var minY = viewBox[1]; width = viewBox[2]; height = viewBox[3]; svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); svg.ViewPort.RemoveCurrent(); svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); } } }]); return _class7; }(svg.Element.RenderedElementBase); // rect element svg.Element.rect = /*#__PURE__*/function (_svg$Element$PathElem) { _inherits(_class8, _svg$Element$PathElem); var _super7 = _createSuper(_class8); function _class8() { _classCallCheck(this, _class8); return _super7.apply(this, arguments); } _createClass(_class8, [{ key: "path", value: function path(ctx) { var x = this.attribute('x').toPixels('x'); var y = this.attribute('y').toPixels('y'); var width = this.attribute('width').toPixels('x'); var height = this.attribute('height').toPixels('y'); var rx = this.attribute('rx').toPixels('x'); var ry = this.attribute('ry').toPixels('y'); if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; rx = Math.min(rx, width / 2.0); ry = Math.min(ry, height / 2.0); if (!isNullish$1(ctx)) { ctx.beginPath(); ctx.moveTo(x + rx, y); ctx.lineTo(x + width - rx, y); ctx.quadraticCurveTo(x + width, y, x + width, y + ry); ctx.lineTo(x + width, y + height - ry); ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height); ctx.lineTo(x + rx, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - ry); ctx.lineTo(x, y + ry); ctx.quadraticCurveTo(x, y, x + rx, y); ctx.closePath(); } return new svg.BoundingBox(x, y, x + width, y + height); } }]); return _class8; }(svg.Element.PathElementBase); // circle element svg.Element.circle = /*#__PURE__*/function (_svg$Element$PathElem2) { _inherits(_class9, _svg$Element$PathElem2); var _super8 = _createSuper(_class9); function _class9() { _classCallCheck(this, _class9); return _super8.apply(this, arguments); } _createClass(_class9, [{ key: "path", value: function path(ctx) { var cx = this.attribute('cx').toPixels('x'); var cy = this.attribute('cy').toPixels('y'); var r = this.attribute('r').toPixels(); if (!isNullish$1(ctx)) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, true); ctx.closePath(); } return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); } }]); return _class9; }(svg.Element.PathElementBase); // ellipse element var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); svg.Element.ellipse = /*#__PURE__*/function (_svg$Element$PathElem3) { _inherits(_class10, _svg$Element$PathElem3); var _super9 = _createSuper(_class10); function _class10() { _classCallCheck(this, _class10); return _super9.apply(this, arguments); } _createClass(_class10, [{ key: "path", value: function path(ctx) { var rx = this.attribute('rx').toPixels('x'); var ry = this.attribute('ry').toPixels('y'); var cx = this.attribute('cx').toPixels('x'); var cy = this.attribute('cy').toPixels('y'); if (!isNullish$1(ctx)) { ctx.beginPath(); ctx.moveTo(cx, cy - ry); ctx.bezierCurveTo(cx + KAPPA * rx, cy - ry, cx + rx, cy - KAPPA * ry, cx + rx, cy); ctx.bezierCurveTo(cx + rx, cy + KAPPA * ry, cx + KAPPA * rx, cy + ry, cx, cy + ry); ctx.bezierCurveTo(cx - KAPPA * rx, cy + ry, cx - rx, cy + KAPPA * ry, cx - rx, cy); ctx.bezierCurveTo(cx - rx, cy - KAPPA * ry, cx - KAPPA * rx, cy - ry, cx, cy - ry); ctx.closePath(); } return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); } }]); return _class10; }(svg.Element.PathElementBase); // line element svg.Element.line = /*#__PURE__*/function (_svg$Element$PathElem4) { _inherits(_class11, _svg$Element$PathElem4); var _super10 = _createSuper(_class11); function _class11() { _classCallCheck(this, _class11); return _super10.apply(this, arguments); } _createClass(_class11, [{ key: "getPoints", value: function getPoints() { return [new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')), new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))]; } }, { key: "path", value: function path(ctx) { var points = this.getPoints(); if (!isNullish$1(ctx)) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); ctx.lineTo(points[1].x, points[1].y); } return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); } }, { key: "getMarkers", value: function getMarkers() { var points = this.getPoints(); var a = points[0].angleTo(points[1]); return [[points[0], a], [points[1], a]]; } }]); return _class11; }(svg.Element.PathElementBase); // polyline element svg.Element.polyline = /*#__PURE__*/function (_svg$Element$PathElem5) { _inherits(_class12, _svg$Element$PathElem5); var _super11 = _createSuper(_class12); function _class12(node) { var _this8; _classCallCheck(this, _class12); _this8 = _super11.call(this, node); _this8.points = svg.CreatePath(_this8.attribute('points').value); return _this8; } _createClass(_class12, [{ key: "path", value: function path(ctx) { var _this$points$ = this.points[0], x = _this$points$.x, y = _this$points$.y; var bb = new svg.BoundingBox(x, y); if (!isNullish$1(ctx)) { ctx.beginPath(); ctx.moveTo(x, y); } for (var i = 1; i < this.points.length; i++) { var _this$points$i = this.points[i], _x = _this$points$i.x, _y = _this$points$i.y; bb.addPoint(_x, _y); if (!isNullish$1(ctx)) ctx.lineTo(_x, _y); } return bb; } }, { key: "getMarkers", value: function getMarkers() { var markers = []; for (var i = 0; i < this.points.length - 1; i++) { markers.push([this.points[i], this.points[i].angleTo(this.points[i + 1])]); } markers.push([this.points[this.points.length - 1], markers[markers.length - 1][1]]); return markers; } }]); return _class12; }(svg.Element.PathElementBase); // polygon element svg.Element.polygon = /*#__PURE__*/function (_svg$Element$polyline) { _inherits(_class13, _svg$Element$polyline); var _super12 = _createSuper(_class13); function _class13() { _classCallCheck(this, _class13); return _super12.apply(this, arguments); } _createClass(_class13, [{ key: "path", value: function path(ctx) { var bb = _get(_getPrototypeOf(_class13.prototype), "path", this).call(this, ctx); if (!isNullish$1(ctx)) { ctx.lineTo(this.points[0].x, this.points[0].y); ctx.closePath(); } return bb; } }]); return _class13; }(svg.Element.polyline); // path element svg.Element.path = /*#__PURE__*/function (_svg$Element$PathElem6) { _inherits(_class14, _svg$Element$PathElem6); var _super13 = _createSuper(_class14); function _class14(node) { var _this9; _classCallCheck(this, _class14); _this9 = _super13.call(this, node); var d = _this9.attribute('d').value // TODO: convert to real lexer based on https://www.w3.org/TR/SVG11/paths.html#PathDataBNF .replace(/,/gm, ' ') // get rid of all commas .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands .replace(/([MmZzLlHhVvCcSsQqTtAa])(\S)/gm, '$1 $2') // separate commands from points .replace(/(\S)([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from points .replace(/(\d)([+-])/gm, '$1 $2') // separate digits when no comma .replace(/(\.\d*)(\.)/gm, '$1 $2') // separate digits when no comma .replace(/([Aa](\s+\d+)(\s+\d+)(\s+\d+))\s+([01])\s*([01])/gm, '$1 $5 $6 '); // shorthand elliptical arc path syntax d = svg.compressSpaces(d); // compress multiple spaces d = svg.trim(d); _this9.PathParser = { tokens: d.split(' '), reset: function reset() { this.i = -1; this.command = ''; this.previousCommand = ''; this.start = new svg.Point(0, 0); this.control = new svg.Point(0, 0); this.current = new svg.Point(0, 0); this.points = []; this.angles = []; }, isEnd: function isEnd() { return this.i >= this.tokens.length - 1; }, isCommandOrEnd: function isCommandOrEnd() { if (this.isEnd()) return true; return !isNullish$1(this.tokens[this.i + 1].match(/^[A-Za-z]$/)); }, isRelativeCommand: function isRelativeCommand() { switch (this.command) { case 'm': case 'l': case 'h': case 'v': case 'c': case 's': case 'q': case 't': case 'a': case 'z': return true; } return false; }, getToken: function getToken() { this.i++; return this.tokens[this.i]; }, getScalar: function getScalar() { return Number.parseFloat(this.getToken()); }, nextCommand: function nextCommand() { this.previousCommand = this.command; this.command = this.getToken(); }, getPoint: function getPoint() { var p = new svg.Point(this.getScalar(), this.getScalar()); return this.makeAbsolute(p); }, getAsControlPoint: function getAsControlPoint() { var p = this.getPoint(); this.control = p; return p; }, getAsCurrentPoint: function getAsCurrentPoint() { var p = this.getPoint(); this.current = p; return p; }, getReflectedControlPoint: function getReflectedControlPoint() { if (this.previousCommand.toLowerCase() !== 'c' && this.previousCommand.toLowerCase() !== 's' && this.previousCommand.toLowerCase() !== 'q' && this.previousCommand.toLowerCase() !== 't') { return this.current; } // reflect point var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); return p; }, makeAbsolute: function makeAbsolute(p) { if (this.isRelativeCommand()) { p.x += this.current.x; p.y += this.current.y; } return p; }, addMarker: function addMarker(p, from, priorTo) { // if the last angle isn't filled in because we didn't have this point yet ... if (!isNullish$1(priorTo) && this.angles.length > 0 && isNullish$1(this.angles[this.angles.length - 1])) { this.angles[this.angles.length - 1] = this.points[this.points.length - 1].angleTo(priorTo); } this.addMarkerAngle(p, isNullish$1(from) ? null : from.angleTo(p)); }, addMarkerAngle: function addMarkerAngle(p, a) { this.points.push(p); this.angles.push(a); }, getMarkerPoints: function getMarkerPoints() { return this.points; }, getMarkerAngles: function getMarkerAngles() { for (var i = 0; i < this.angles.length; i++) { if (isNullish$1(this.angles[i])) { for (var j = i + 1; j < this.angles.length; j++) { if (!isNullish$1(this.angles[j])) { this.angles[i] = this.angles[j]; break; } } } } return this.angles; } }; return _this9; } _createClass(_class14, [{ key: "path", value: function path(ctx) { var pp = this.PathParser; pp.reset(); var bb = new svg.BoundingBox(); if (!isNullish$1(ctx)) ctx.beginPath(); while (!pp.isEnd()) { pp.nextCommand(); switch (pp.command) { case 'M': case 'm': { var p = pp.getAsCurrentPoint(); pp.addMarker(p); bb.addPoint(p.x, p.y); if (!isNullish$1(ctx)) ctx.moveTo(p.x, p.y); pp.start = pp.current; while (!pp.isCommandOrEnd()) { var _p = pp.getAsCurrentPoint(); pp.addMarker(_p, pp.start); bb.addPoint(_p.x, _p.y); if (!isNullish$1(ctx)) ctx.lineTo(_p.x, _p.y); } break; } case 'L': case 'l': while (!pp.isCommandOrEnd()) { var c = pp.current; var _p2 = pp.getAsCurrentPoint(); pp.addMarker(_p2, c); bb.addPoint(_p2.x, _p2.y); if (!isNullish$1(ctx)) ctx.lineTo(_p2.x, _p2.y); } break; case 'H': case 'h': while (!pp.isCommandOrEnd()) { var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (!isNullish$1(ctx)) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'V': case 'v': while (!pp.isCommandOrEnd()) { var _newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); pp.addMarker(_newP, pp.current); pp.current = _newP; bb.addPoint(pp.current.x, pp.current.y); if (!isNullish$1(ctx)) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'C': case 'c': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, p1); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (!isNullish$1(ctx)) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'S': case 's': while (!pp.isCommandOrEnd()) { var _curr = pp.current; var _p3 = pp.getReflectedControlPoint(); var _cntrl = pp.getAsControlPoint(); var _cp = pp.getAsCurrentPoint(); pp.addMarker(_cp, _cntrl, _p3); bb.addBezierCurve(_curr.x, _curr.y, _p3.x, _p3.y, _cntrl.x, _cntrl.y, _cp.x, _cp.y); if (!isNullish$1(ctx)) ctx.bezierCurveTo(_p3.x, _p3.y, _cntrl.x, _cntrl.y, _cp.x, _cp.y); } break; case 'Q': case 'q': while (!pp.isCommandOrEnd()) { var _curr2 = pp.current; var _cntrl2 = pp.getAsControlPoint(); var _cp2 = pp.getAsCurrentPoint(); pp.addMarker(_cp2, _cntrl2, _cntrl2); bb.addQuadraticCurve(_curr2.x, _curr2.y, _cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); if (!isNullish$1(ctx)) ctx.quadraticCurveTo(_cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); } break; case 'T': case 't': while (!pp.isCommandOrEnd()) { var _curr3 = pp.current; var _cntrl3 = pp.getReflectedControlPoint(); pp.control = _cntrl3; var _cp3 = pp.getAsCurrentPoint(); pp.addMarker(_cp3, _cntrl3, _cntrl3); bb.addQuadraticCurve(_curr3.x, _curr3.y, _cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); if (!isNullish$1(ctx)) ctx.quadraticCurveTo(_cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); } break; case 'A': case 'a': var _loop2 = function _loop2() { var curr = pp.current; var rx = pp.getScalar(); var ry = pp.getScalar(); var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); var largeArcFlag = pp.getScalar(); var sweepFlag = pp.getScalar(); var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization // https://www.w3.org/TR/SVG11/implnote.html#ArcConversionEndpointToCenter // x1', y1' var currp = new svg.Point(Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0); // adjust radii var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2); if (l > 1) { rx *= Math.sqrt(l); ry *= Math.sqrt(l); } // cx', cy' var s = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt((Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(currp.y, 2) - Math.pow(ry, 2) * Math.pow(currp.x, 2)) / (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))); if (isNaN(s)) s = 0; var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy var centp = new svg.Point((curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y); // vector magnitude var m = function m(v) { return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)); }; // ratio between two vectors var r = function r(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v)); }; // angle between two vectors var a = function a(u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v)); }; // initial angle var a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]); // angle delta var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]; var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry]; var ad = a(u, v); if (r(u, v) <= -1) ad = Math.PI; if (r(u, v) >= 1) ad = 0; // for markers var dir = 1 - sweepFlag ? 1.0 : -1.0; var ah = a1 + dir * (ad / 2.0); var halfWay = new svg.Point(centp.x + rx * Math.cos(ah), centp.y + ry * Math.sin(ah)); pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2); pp.addMarkerAngle(cp, ah - dir * Math.PI); bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better if (!isNullish$1(ctx)) { var _r = rx > ry ? rx : ry; var sx = rx > ry ? 1 : rx / ry; var sy = rx > ry ? ry / rx : 1; ctx.translate(centp.x, centp.y); ctx.rotate(xAxisRotation); ctx.scale(sx, sy); ctx.arc(0, 0, _r, a1, a1 + ad, 1 - sweepFlag); ctx.scale(1 / sx, 1 / sy); ctx.rotate(-xAxisRotation); ctx.translate(-centp.x, -centp.y); } }; while (!pp.isCommandOrEnd()) { _loop2(); } break; case 'Z': case 'z': if (!isNullish$1(ctx)) ctx.closePath(); pp.current = pp.start; } } return bb; } }, { key: "getMarkers", value: function getMarkers() { var points = this.PathParser.getMarkerPoints(); var angles = this.PathParser.getMarkerAngles(); var markers = points.map(function (point, i) { return [point, angles[i]]; }); return markers; } }]); return _class14; }(svg.Element.PathElementBase); // pattern element svg.Element.pattern = /*#__PURE__*/function (_svg$Element$ElementB2) { _inherits(_class15, _svg$Element$ElementB2); var _super14 = _createSuper(_class15); function _class15() { _classCallCheck(this, _class15); return _super14.apply(this, arguments); } _createClass(_class15, [{ key: "createPattern", value: function createPattern(ctx, element) { var width = this.attribute('width').toPixels('x', true); var height = this.attribute('height').toPixels('y', true); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes.viewBox = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes.width = new svg.Property('width', width + 'px'); tempSvg.attributes.height = new svg.Property('height', height + 'px'); tempSvg.attributes.transform = new svg.Property('transform', this.attribute('patternTransform').value); tempSvg.children = this.children; var c = document.createElement('canvas'); c.width = width; c.height = height; var cctx = c.getContext('2d'); if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true)); } // render 3x3 grid so when we transform there's no white space on edges for (var x = -1; x <= 1; x++) { for (var y = -1; y <= 1; y++) { cctx.save(); cctx.translate(x * c.width, y * c.height); tempSvg.render(cctx); cctx.restore(); } } var pattern = ctx.createPattern(c, 'repeat'); return pattern; } }]); return _class15; }(svg.Element.ElementBase); // marker element svg.Element.marker = /*#__PURE__*/function (_svg$Element$ElementB3) { _inherits(_class16, _svg$Element$ElementB3); var _super15 = _createSuper(_class16); function _class16() { _classCallCheck(this, _class16); return _super15.apply(this, arguments); } _createClass(_class16, [{ key: "render", value: function render(ctx, point, angle) { ctx.translate(point.x, point.y); if (this.attribute('orient').valueOrDefault('auto') === 'auto') ctx.rotate(angle); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); ctx.save(); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes.viewBox = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes.refX = new svg.Property('refX', this.attribute('refX').value); tempSvg.attributes.refY = new svg.Property('refY', this.attribute('refY').value); tempSvg.attributes.width = new svg.Property('width', this.attribute('markerWidth').value); tempSvg.attributes.height = new svg.Property('height', this.attribute('markerHeight').value); tempSvg.attributes.fill = new svg.Property('fill', this.attribute('fill').valueOrDefault('black')); tempSvg.attributes.stroke = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none')); tempSvg.children = this.children; tempSvg.render(ctx); ctx.restore(); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(1 / ctx.lineWidth, 1 / ctx.lineWidth); if (this.attribute('orient').valueOrDefault('auto') === 'auto') { ctx.rotate(-angle); } ctx.translate(-point.x, -point.y); } }]); return _class16; }(svg.Element.ElementBase); // definitions element svg.Element.defs = /*#__PURE__*/function (_svg$Element$ElementB4) { _inherits(_class17, _svg$Element$ElementB4); var _super16 = _createSuper(_class17); function _class17() { _classCallCheck(this, _class17); return _super16.apply(this, arguments); } _createClass(_class17, [{ key: "render", value: function render(ctx) {// NOOP } }]); return _class17; }(svg.Element.ElementBase); // base for gradients svg.Element.GradientBase = /*#__PURE__*/function (_svg$Element$ElementB5) { _inherits(_class18, _svg$Element$ElementB5); var _super17 = _createSuper(_class18); function _class18(node) { var _this10; _classCallCheck(this, _class18); _this10 = _super17.call(this, node); _this10.gradientUnits = _this10.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); _this10.stops = []; _this10.children.forEach(function (child) { if (child.type === 'stop') { _this10.stops.push(child); } }); return _this10; } _createClass(_class18, [{ key: "getGradient", value: function getGradient() {// OVERRIDE ME! } }, { key: "createGradient", value: function createGradient(ctx, element, parentOpacityProp) { var stopsContainer = this.getHrefAttribute().hasValue() ? this.getHrefAttribute().getDefinition() : this; var addParentOpacity = function addParentOpacity(color) { if (parentOpacityProp.hasValue()) { var p = new svg.Property('color', color); return p.addOpacity(parentOpacityProp).value; } return color; }; var g = this.getGradient(ctx, element); if (isNullish$1(g)) return addParentOpacity(stopsContainer.stops[stopsContainer.stops.length - 1].color); stopsContainer.stops.forEach(function (_ref10) { var offset = _ref10.offset, color = _ref10.color; g.addColorStop(offset, addParentOpacity(color)); }); if (this.attribute('gradientTransform').hasValue()) { // render as transformed pattern on temporary canvas var rootView = svg.ViewPort.viewPorts[0]; var rect = new svg.Element.rect(); rect.attributes.x = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS / 3.0); rect.attributes.y = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS / 3.0); rect.attributes.width = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS); rect.attributes.height = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS); var group = new svg.Element.g(); group.attributes.transform = new svg.Property('transform', this.attribute('gradientTransform').value); group.children = [rect]; var tempSvg = new svg.Element.svg(); tempSvg.attributes.x = new svg.Property('x', 0); tempSvg.attributes.y = new svg.Property('y', 0); tempSvg.attributes.width = new svg.Property('width', rootView.width); tempSvg.attributes.height = new svg.Property('height', rootView.height); tempSvg.children = [group]; var c = document.createElement('canvas'); c.width = rootView.width; c.height = rootView.height; var tempCtx = c.getContext('2d'); tempCtx.fillStyle = g; tempSvg.render(tempCtx); return tempCtx.createPattern(c, 'no-repeat'); } return g; } }]); return _class18; }(svg.Element.ElementBase); // linear gradient element svg.Element.linearGradient = /*#__PURE__*/function (_svg$Element$Gradient) { _inherits(_class19, _svg$Element$Gradient); var _super18 = _createSuper(_class19); function _class19() { _classCallCheck(this, _class19); return _super18.apply(this, arguments); } _createClass(_class19, [{ key: "getGradient", value: function getGradient(ctx, element) { var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; var bb = useBB ? element.getBoundingBox() : null; if (!this.attribute('x1').hasValue() && !this.attribute('y1').hasValue() && !this.attribute('x2').hasValue() && !this.attribute('y2').hasValue()) { this.attribute('x1', true).value = 0; this.attribute('y1', true).value = 0; this.attribute('x2', true).value = 1; this.attribute('y2', true).value = 0; } var x1 = useBB ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').toPixels('x'); var y1 = useBB ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').toPixels('y'); var x2 = useBB ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').toPixels('x'); var y2 = useBB ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').toPixels('y'); if (x1 === x2 && y1 === y2) return null; return ctx.createLinearGradient(x1, y1, x2, y2); } }]); return _class19; }(svg.Element.GradientBase); // radial gradient element svg.Element.radialGradient = /*#__PURE__*/function (_svg$Element$Gradient2) { _inherits(_class20, _svg$Element$Gradient2); var _super19 = _createSuper(_class20); function _class20() { _classCallCheck(this, _class20); return _super19.apply(this, arguments); } _createClass(_class20, [{ key: "getGradient", value: function getGradient(ctx, element) { var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; var bb = useBB ? element.getBoundingBox() : null; if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%'; if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%'; if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%'; var cx = useBB ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').toPixels('x'); var cy = useBB ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').toPixels('y'); var fx = cx; var fy = cy; if (this.attribute('fx').hasValue()) { fx = useBB ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').toPixels('x'); } if (this.attribute('fy').hasValue()) { fy = useBB ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').toPixels('y'); } var r = useBB ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').toPixels(); return ctx.createRadialGradient(fx, fy, 0, cx, cy, r); } }]); return _class20; }(svg.Element.GradientBase); // gradient stop element svg.Element.stop = /*#__PURE__*/function (_svg$Element$ElementB6) { _inherits(_class21, _svg$Element$ElementB6); var _super20 = _createSuper(_class21); function _class21(node) { var _this11; _classCallCheck(this, _class21); _this11 = _super20.call(this, node); _this11.offset = _this11.attribute('offset').numValue(); if (_this11.offset < 0) _this11.offset = 0; if (_this11.offset > 1) _this11.offset = 1; var stopColor = _this11.style('stop-color'); if (_this11.style('stop-opacity').hasValue()) { stopColor = stopColor.addOpacity(_this11.style('stop-opacity')); } _this11.color = stopColor.value; return _this11; } return _class21; }(svg.Element.ElementBase); // animation base element svg.Element.AnimateBase = /*#__PURE__*/function (_svg$Element$ElementB7) { _inherits(_class22, _svg$Element$ElementB7); var _super21 = _createSuper(_class22); function _class22(node) { var _this12; _classCallCheck(this, _class22); _this12 = _super21.call(this, node); svg.Animations.push(_assertThisInitialized(_this12)); _this12.duration = 0.0; _this12.begin = _this12.attribute('begin').toMilliseconds(); _this12.maxDuration = _this12.begin + _this12.attribute('dur').toMilliseconds(); _this12.initialValue = null; _this12.initialUnits = ''; _this12.removed = false; _this12.from = _this12.attribute('from'); _this12.to = _this12.attribute('to'); _this12.values = _this12.attribute('values'); if (_this12.values.hasValue()) _this12.values.value = _this12.values.value.split(';'); return _this12; } _createClass(_class22, [{ key: "getProperty", value: function getProperty() { var attributeType = this.attribute('attributeType').value; var attributeName = this.attribute('attributeName').value; if (attributeType === 'CSS') { return this.parent.style(attributeName, true); } return this.parent.attribute(attributeName, true); } }, { key: "calcValue", value: function calcValue() { // OVERRIDE ME! return ''; } }, { key: "update", value: function update(delta) { // set initial value if (isNullish$1(this.initialValue)) { this.initialValue = this.getProperty().value; this.initialUnits = this.getProperty().getUnits(); } // if we're past the end time if (this.duration > this.maxDuration) { // loop for indefinitely repeating animations if (this.attribute('repeatCount').value === 'indefinite' || this.attribute('repeatDur').value === 'indefinite') { this.duration = 0.0; } else if (this.attribute('fill').valueOrDefault('remove') === 'freeze' && !this.frozen) { this.frozen = true; this.parent.animationFrozen = true; this.parent.animationFrozenValue = this.getProperty().value; } else if (this.attribute('fill').valueOrDefault('remove') === 'remove' && !this.removed) { this.removed = true; this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue; return true; } return false; } this.duration += delta; // if we're past the begin time var updated = false; if (this.begin < this.duration) { var newValue = this.calcValue(); // tween if (this.attribute('type').hasValue()) { // for transform, etc. var type = this.attribute('type').value; newValue = type + '(' + newValue + ')'; } this.getProperty().value = newValue; updated = true; } return updated; } // fraction of duration we've covered }, { key: "progress", value: function progress() { var ret = { progress: (this.duration - this.begin) / (this.maxDuration - this.begin) }; if (this.values.hasValue()) { var p = ret.progress * (this.values.value.length - 1); var lb = Math.floor(p), ub = Math.ceil(p); ret.from = new svg.Property('from', Number.parseFloat(this.values.value[lb])); ret.to = new svg.Property('to', Number.parseFloat(this.values.value[ub])); ret.progress = (p - lb) / (ub - lb); } else { ret.from = this.from; ret.to = this.to; } return ret; } }]); return _class22; }(svg.Element.ElementBase); // animate element svg.Element.animate = /*#__PURE__*/function (_svg$Element$AnimateB) { _inherits(_class23, _svg$Element$AnimateB); var _super22 = _createSuper(_class23); function _class23() { _classCallCheck(this, _class23); return _super22.apply(this, arguments); } _createClass(_class23, [{ key: "calcValue", value: function calcValue() { var p = this.progress(); // tween value linearly var newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress; return newValue + this.initialUnits; } }]); return _class23; }(svg.Element.AnimateBase); // animate color element svg.Element.animateColor = /*#__PURE__*/function (_svg$Element$AnimateB2) { _inherits(_class24, _svg$Element$AnimateB2); var _super23 = _createSuper(_class24); function _class24() { _classCallCheck(this, _class24); return _super23.apply(this, arguments); } _createClass(_class24, [{ key: "calcValue", value: function calcValue() { var p = this.progress(); var from = new RGBColor$2(p.from.value); var to = new RGBColor$2(p.to.value); if (from.ok && to.ok) { // tween color linearly var r = from.r + (to.r - from.r) * p.progress; var g = from.g + (to.g - from.g) * p.progress; var b = from.b + (to.b - from.b) * p.progress; return 'rgb(' + Number.parseInt(r) + ',' + Number.parseInt(g) + ',' + Number.parseInt(b) + ')'; } return this.attribute('from').value; } }]); return _class24; }(svg.Element.AnimateBase); // animate transform element svg.Element.animateTransform = /*#__PURE__*/function (_svg$Element$animate) { _inherits(_class25, _svg$Element$animate); var _super24 = _createSuper(_class25); function _class25() { _classCallCheck(this, _class25); return _super24.apply(this, arguments); } _createClass(_class25, [{ key: "calcValue", value: function calcValue() { var p = this.progress(); // tween value linearly var from = svg.ToNumberArray(p.from.value); var to = svg.ToNumberArray(p.to.value); var newValue = ''; from.forEach(function (fr, i) { newValue += fr + (to[i] - fr) * p.progress + ' '; }); return newValue; } }]); return _class25; }(svg.Element.animate); // font element svg.Element.font = /*#__PURE__*/function (_svg$Element$ElementB8) { _inherits(_class26, _svg$Element$ElementB8); var _super25 = _createSuper(_class26); function _class26(node) { var _this13; _classCallCheck(this, _class26); _this13 = _super25.call(this, node); _this13.horizAdvX = _this13.attribute('horiz-adv-x').numValue(); _this13.isRTL = false; _this13.isArabic = false; _this13.fontFace = null; _this13.missingGlyph = null; _this13.glyphs = []; _this13.children.forEach(function (child) { if (child.type === 'font-face') { _this13.fontFace = child; if (child.style('font-family').hasValue()) { svg.Definitions[child.style('font-family').value] = _assertThisInitialized(_this13); } } else if (child.type === 'missing-glyph') { _this13.missingGlyph = child; } else if (child.type === 'glyph') { if (child.arabicForm !== '') { _this13.isRTL = true; _this13.isArabic = true; if (typeof _this13.glyphs[child.unicode] === 'undefined') { _this13.glyphs[child.unicode] = []; } _this13.glyphs[child.unicode][child.arabicForm] = child; } else { _this13.glyphs[child.unicode] = child; } } }); return _this13; } return _class26; }(svg.Element.ElementBase); // font-face element svg.Element.fontface = /*#__PURE__*/function (_svg$Element$ElementB9) { _inherits(_class27, _svg$Element$ElementB9); var _super26 = _createSuper(_class27); function _class27(node) { var _this14; _classCallCheck(this, _class27); _this14 = _super26.call(this, node); _this14.ascent = _this14.attribute('ascent').value; _this14.descent = _this14.attribute('descent').value; _this14.unitsPerEm = _this14.attribute('units-per-em').numValue(); return _this14; } return _class27; }(svg.Element.ElementBase); // missing-glyph element svg.Element.missingglyph = /*#__PURE__*/function (_svg$Element$path) { _inherits(_class28, _svg$Element$path); var _super27 = _createSuper(_class28); function _class28(node) { var _this15; _classCallCheck(this, _class28); _this15 = _super27.call(this, node); _this15.horizAdvX = 0; return _this15; } return _class28; }(svg.Element.path); // glyph element svg.Element.glyph = /*#__PURE__*/function (_svg$Element$path2) { _inherits(_class29, _svg$Element$path2); var _super28 = _createSuper(_class29); function _class29(node) { var _this16; _classCallCheck(this, _class29); _this16 = _super28.call(this, node); _this16.horizAdvX = _this16.attribute('horiz-adv-x').numValue(); _this16.unicode = _this16.attribute('unicode').value; _this16.arabicForm = _this16.attribute('arabic-form').value; return _this16; } return _class29; }(svg.Element.path); // text element svg.Element.text = /*#__PURE__*/function (_svg$Element$Rendered3) { _inherits(_class30, _svg$Element$Rendered3); var _super29 = _createSuper(_class30); function _class30(node) { _classCallCheck(this, _class30); return _super29.call(this, node, true); } _createClass(_class30, [{ key: "setContext", value: function setContext(ctx) { _get(_getPrototypeOf(_class30.prototype), "setContext", this).call(this, ctx); var textBaseline = this.style('dominant-baseline').toTextBaseline(); if (isNullish$1(textBaseline)) textBaseline = this.style('alignment-baseline').toTextBaseline(); if (!isNullish$1(textBaseline)) ctx.textBaseline = textBaseline; } }, { key: "getBoundingBox", value: function getBoundingBox() { var x = this.attribute('x').toPixels('x'); var y = this.attribute('y').toPixels('y'); var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); return new svg.BoundingBox(x, y - fontSize, x + Math.floor(fontSize * 2.0 / 3.0) * this.children[0].getText().length, y); } }, { key: "renderChildren", value: function renderChildren(ctx) { var _this17 = this; this.x = this.attribute('x').toPixels('x'); this.y = this.attribute('y').toPixels('y'); this.x += this.getAnchorDelta(ctx, this, 0); this.children.forEach(function (child, i) { _this17.renderChild(ctx, _this17, i); }); } }, { key: "getAnchorDelta", value: function getAnchorDelta(ctx, parent, startI) { var textAnchor = this.style('text-anchor').valueOrDefault('start'); if (textAnchor !== 'start') { var width = 0; for (var i = startI; i < parent.children.length; i++) { var child = parent.children[i]; if (i > startI && child.attribute('x').hasValue()) break; // new group width += child.measureTextRecursive(ctx); } return -1 * (textAnchor === 'end' ? width : width / 2.0); } return 0; } }, { key: "renderChild", value: function renderChild(ctx, parent, i) { var child = parent.children[i]; if (child.attribute('x').hasValue()) { child.x = child.attribute('x').toPixels('x') + this.getAnchorDelta(ctx, parent, i); if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x'); } else { if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x'); if (child.attribute('dx').hasValue()) this.x += child.attribute('dx').toPixels('x'); child.x = this.x; } this.x = child.x + child.measureText(ctx); if (child.attribute('y').hasValue()) { child.y = child.attribute('y').toPixels('y'); if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y'); } else { if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y'); if (child.attribute('dy').hasValue()) this.y += child.attribute('dy').toPixels('y'); child.y = this.y; } this.y = child.y; child.render(ctx); for (var j = 0; j < child.children.length; j++) { this.renderChild(ctx, child, j); } } }]); return _class30; }(svg.Element.RenderedElementBase); // text base svg.Element.TextElementBase = /*#__PURE__*/function (_svg$Element$Rendered4) { _inherits(_class31, _svg$Element$Rendered4); var _super30 = _createSuper(_class31); function _class31() { _classCallCheck(this, _class31); return _super30.apply(this, arguments); } _createClass(_class31, [{ key: "getGlyph", value: function getGlyph(font, text, i) { var c = text[i]; var glyph = null; if (font.isArabic) { var arabicForm = 'isolated'; if ((i === 0 || text[i - 1] === ' ') && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'terminal'; if (i > 0 && text[i - 1] !== ' ' && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'medial'; if (i > 0 && text[i - 1] !== ' ' && (i === text.length - 1 || text[i + 1] === ' ')) arabicForm = 'initial'; if (typeof font.glyphs[c] !== 'undefined') { glyph = font.glyphs[c][arabicForm]; if (isNullish$1(glyph) && font.glyphs[c].type === 'glyph') glyph = font.glyphs[c]; } } else { glyph = font.glyphs[c]; } if (isNullish$1(glyph)) glyph = font.missingGlyph; return glyph; } }, { key: "renderChildren", value: function renderChildren(ctx) { var customFont = this.parent.style('font-family').getDefinition(); if (!isNullish$1(customFont)) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle); var text = this.getText(); if (customFont.isRTL) text = text.split('').reverse().join(''); var dx = svg.ToNumberArray(this.parent.attribute('dx').value); for (var i = 0; i < text.length; i++) { var glyph = this.getGlyph(customFont, text, i); var scale = fontSize / customFont.fontFace.unitsPerEm; ctx.translate(this.x, this.y); ctx.scale(scale, -scale); var lw = ctx.lineWidth; ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize; if (fontStyle === 'italic') ctx.transform(1, 0, 0.4, 1, 0, 0); glyph.render(ctx); if (fontStyle === 'italic') ctx.transform(1, 0, -0.4, 1, 0, 0); ctx.lineWidth = lw; ctx.scale(1 / scale, -1 / scale); ctx.translate(-this.x, -this.y); this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm; if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { this.x += dx[i]; } } return; } if (ctx.fillStyle !== '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); if (ctx.strokeStyle !== '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y); } }, { key: "getText", value: function getText() {// OVERRIDE ME } }, { key: "measureTextRecursive", value: function measureTextRecursive(ctx) { var width = this.measureText(ctx); this.children.forEach(function (child) { width += child.measureTextRecursive(ctx); }); return width; } }, { key: "measureText", value: function measureText(ctx) { var customFont = this.parent.style('font-family').getDefinition(); if (!isNullish$1(customFont)) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var measure = 0; var text = this.getText(); if (customFont.isRTL) text = text.split('').reverse().join(''); var dx = svg.ToNumberArray(this.parent.attribute('dx').value); for (var i = 0; i < text.length; i++) { var glyph = this.getGlyph(customFont, text, i); measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm; if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { measure += dx[i]; } } return measure; } var textToMeasure = svg.compressSpaces(this.getText()); if (!ctx.measureText) return textToMeasure.length * 10; ctx.save(); this.setContext(ctx); var _ctx$measureText = ctx.measureText(textToMeasure), width = _ctx$measureText.width; ctx.restore(); return width; } }]); return _class31; }(svg.Element.RenderedElementBase); // tspan svg.Element.tspan = /*#__PURE__*/function (_svg$Element$TextElem) { _inherits(_class32, _svg$Element$TextElem); var _super31 = _createSuper(_class32); function _class32(node) { var _this18; _classCallCheck(this, _class32); _this18 = _super31.call(this, node, true); _this18.text = node.nodeValue || node.text || ''; return _this18; } _createClass(_class32, [{ key: "getText", value: function getText() { return this.text; } }]); return _class32; }(svg.Element.TextElementBase); // tref svg.Element.tref = /*#__PURE__*/function (_svg$Element$TextElem2) { _inherits(_class33, _svg$Element$TextElem2); var _super32 = _createSuper(_class33); function _class33() { _classCallCheck(this, _class33); return _super32.apply(this, arguments); } _createClass(_class33, [{ key: "getText", value: function getText() { var element = this.getHrefAttribute().getDefinition(); if (!isNullish$1(element)) return element.children[0].getText(); return undefined; } }]); return _class33; }(svg.Element.TextElementBase); // a element svg.Element.a = /*#__PURE__*/function (_svg$Element$TextElem3) { _inherits(_class34, _svg$Element$TextElem3); var _super33 = _createSuper(_class34); function _class34(node) { var _this19; _classCallCheck(this, _class34); _this19 = _super33.call(this, node); _this19.hasText = true; _toConsumableArray(node.childNodes).forEach(function (childNode) { if (childNode.nodeType !== 3) { _this19.hasText = false; } }); // this might contain text _this19.text = _this19.hasText ? node.childNodes[0].nodeValue : ''; return _this19; } _createClass(_class34, [{ key: "getText", value: function getText() { return this.text; } }, { key: "renderChildren", value: function renderChildren(ctx) { if (this.hasText) { // render as text element _get(_getPrototypeOf(_class34.prototype), "renderChildren", this).call(this, ctx); var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y)); } else { // render as temporary group var g = new svg.Element.g(); g.children = this.children; g.parent = this; g.render(ctx); } } }, { key: "onclick", value: function onclick() { window.open(this.getHrefAttribute().value); } }, { key: "onmousemove", value: function onmousemove() { svg.ctx.canvas.style.cursor = 'pointer'; } }]); return _class34; }(svg.Element.TextElementBase); // image element svg.Element.image = /*#__PURE__*/function (_svg$Element$Rendered5) { _inherits(_class35, _svg$Element$Rendered5); var _super34 = _createSuper(_class35); function _class35(node) { var _this20; _classCallCheck(this, _class35); _this20 = _super34.call(this, node); var href = _this20.getHrefAttribute().value; if (href === '') { return _possibleConstructorReturn(_this20); } _this20._isSvg = href.match(/\.svg$/); svg.Images.push(_assertThisInitialized(_this20)); _this20.loaded = false; if (!_this20._isSvg) { _this20.img = document.createElement('img'); if (svg.opts.useCORS === true) { _this20.img.crossOrigin = 'Anonymous'; } _this20.img.addEventListener('load', function () { _this20.loaded = true; }); _this20.img.addEventListener('error', function () { svg.log('ERROR: image "' + href + '" not found'); _this20.loaded = true; }); _this20.img.src = href; } else { svg.ajax(href, true).then(function (img) { // eslint-disable-line promise/prefer-await-to-then, promise/always-return _this20.img = img; _this20.loaded = true; })["catch"](function (err) { // eslint-disable-line promise/prefer-await-to-callbacks _this20.erred = true; console.error('Ajax error for canvg', err); // eslint-disable-line no-console }); } return _this20; } _createClass(_class35, [{ key: "renderChildren", value: function renderChildren(ctx) { var x = this.attribute('x').toPixels('x'); var y = this.attribute('y').toPixels('y'); var width = this.attribute('width').toPixels('x'); var height = this.attribute('height').toPixels('y'); if (width === 0 || height === 0) return; ctx.save(); if (this._isSvg) { ctx.drawSvg(this.img, x, y, width, height); } else { ctx.translate(x, y); svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); ctx.drawImage(this.img, 0, 0); } ctx.restore(); } }, { key: "getBoundingBox", value: function getBoundingBox() { var x = this.attribute('x').toPixels('x'); var y = this.attribute('y').toPixels('y'); var width = this.attribute('width').toPixels('x'); var height = this.attribute('height').toPixels('y'); return new svg.BoundingBox(x, y, x + width, y + height); } }]); return _class35; }(svg.Element.RenderedElementBase); // group element svg.Element.g = /*#__PURE__*/function (_svg$Element$Rendered6) { _inherits(_class36, _svg$Element$Rendered6); var _super35 = _createSuper(_class36); function _class36() { _classCallCheck(this, _class36); return _super35.apply(this, arguments); } _createClass(_class36, [{ key: "getBoundingBox", value: function getBoundingBox() { var bb = new svg.BoundingBox(); this.children.forEach(function (child) { bb.addBoundingBox(child.getBoundingBox()); }); return bb; } }]); return _class36; }(svg.Element.RenderedElementBase); // symbol element svg.Element.symbol = /*#__PURE__*/function (_svg$Element$Rendered7) { _inherits(_class37, _svg$Element$Rendered7); var _super36 = _createSuper(_class37); function _class37() { _classCallCheck(this, _class37); return _super36.apply(this, arguments); } _createClass(_class37, [{ key: "render", value: function render(ctx) {// NO RENDER } }]); return _class37; }(svg.Element.RenderedElementBase); // style element svg.Element.style = /*#__PURE__*/function (_svg$Element$ElementB10) { _inherits(_class38, _svg$Element$ElementB10); var _super37 = _createSuper(_class38); function _class38(node) { var _this21; _classCallCheck(this, _class38); _this21 = _super37.call(this, node); // text, or spaces then CDATA var css = ''; _toConsumableArray(node.childNodes).forEach(function (_ref11) { var nodeValue = _ref11.nodeValue; css += nodeValue; }); // remove comments css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(^\s*\/\/.*)/gm, ''); // eslint-disable-line unicorn/no-unsafe-regex // replace whitespace css = svg.compressSpaces(css); var cssDefs = css.split('}'); cssDefs.forEach(function (cssDef) { if (svg.trim(cssDef) !== '') { var _cssDef$split = cssDef.split('{'), _cssDef$split2 = _slicedToArray(_cssDef$split, 2), cssClasses = _cssDef$split2[0], cssProps = _cssDef$split2[1]; cssClasses = cssClasses.split(','); cssProps = cssProps.split(';'); cssClasses.forEach(function (cssClass) { cssClass = svg.trim(cssClass); if (cssClass !== '') { var props = {}; cssProps.forEach(function (cssProp) { var prop = cssProp.indexOf(':'); var name = cssProp.substr(0, prop); var value = cssProp.substr(prop + 1, cssProp.length - prop); if (!isNullish$1(name) && !isNullish$1(value)) { props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value)); } }); svg.Styles[cssClass] = props; if (cssClass === '@font-face') { var fontFamily = props['font-family'].value.replace(/"/g, ''); var srcs = props.src.value.split(','); srcs.forEach(function (src) { if (src.includes('format("svg")')) { var urlStart = src.indexOf('url'); var urlEnd = src.indexOf(')', urlStart); var url = src.substr(urlStart + 5, urlEnd - urlStart - 6); // Can this ajax safely be converted to async? var doc = svg.parseXml(svg.ajax(url)); var fonts = doc.getElementsByTagName('font'); _toConsumableArray(fonts).forEach(function (font) { font = svg.CreateElement(font); svg.Definitions[fontFamily] = font; }); } }); } } }); } }); return _this21; } return _class38; }(svg.Element.ElementBase); // use element svg.Element.use = /*#__PURE__*/function (_svg$Element$Rendered8) { _inherits(_class39, _svg$Element$Rendered8); var _super38 = _createSuper(_class39); function _class39(node) { var _this22; _classCallCheck(this, _class39); _this22 = _super38.call(this, node); _this22._el = _this22.getHrefAttribute().getDefinition(); return _this22; } _createClass(_class39, [{ key: "setContext", value: function setContext(ctx) { _get(_getPrototypeOf(_class39.prototype), "setContext", this).call(this, ctx); if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0); if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y')); } }, { key: "path", value: function path(ctx) { var element = this._el; if (!isNullish$1(element)) element.path(ctx); } }, { key: "getBoundingBox", value: function getBoundingBox() { var element = this._el; if (!isNullish$1(element)) return element.getBoundingBox(); return undefined; } }, { key: "renderChildren", value: function renderChildren(ctx) { var element = this._el; if (!isNullish$1(element)) { var tempSvg = element; if (element.type === 'symbol') { // render me using a temporary svg element in symbol cases // (https://www.w3.org/TR/SVG/struct.html#UseElement) tempSvg = new svg.Element.svg(); tempSvg.type = 'svg'; tempSvg.attributes.viewBox = new svg.Property('viewBox', element.attribute('viewBox').value); tempSvg.attributes.preserveAspectRatio = new svg.Property('preserveAspectRatio', element.attribute('preserveAspectRatio').value); tempSvg.attributes.overflow = new svg.Property('overflow', element.attribute('overflow').value); tempSvg.children = element.children; } if (tempSvg.type === 'svg') { // if symbol or svg, inherit width/height from me if (this.attribute('width').hasValue()) { tempSvg.attributes.width = new svg.Property('width', this.attribute('width').value); } if (this.attribute('height').hasValue()) { tempSvg.attributes.height = new svg.Property('height', this.attribute('height').value); } } var oldParent = tempSvg.parent; tempSvg.parent = null; tempSvg.render(ctx); tempSvg.parent = oldParent; } } }]); return _class39; }(svg.Element.RenderedElementBase); // mask element svg.Element.mask = /*#__PURE__*/function (_svg$Element$ElementB11) { _inherits(_class40, _svg$Element$ElementB11); var _super39 = _createSuper(_class40); function _class40() { _classCallCheck(this, _class40); return _super39.apply(this, arguments); } _createClass(_class40, [{ key: "apply", value: function apply(ctx, element) { // render as temp svg var x = this.attribute('x').toPixels('x'); var y = this.attribute('y').toPixels('y'); var width = this.attribute('width').toPixels('x'); var height = this.attribute('height').toPixels('y'); if (width === 0 && height === 0) { var bb = new svg.BoundingBox(); this.children.forEach(function (child) { bb.addBoundingBox(child.getBoundingBox()); }); x = Math.floor(bb.x1); y = Math.floor(bb.y1); width = Math.floor(bb.width()); height = Math.floor(bb.height()); } // temporarily remove mask to avoid recursion var mask = element.attribute('mask').value; element.attribute('mask').value = ''; var cMask = document.createElement('canvas'); cMask.width = x + width; cMask.height = y + height; var maskCtx = cMask.getContext('2d'); this.renderChildren(maskCtx); var c = document.createElement('canvas'); c.width = x + width; c.height = y + height; var tempCtx = c.getContext('2d'); element.render(tempCtx); tempCtx.globalCompositeOperation = 'destination-in'; tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat'); tempCtx.fillRect(0, 0, x + width, y + height); ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat'); ctx.fillRect(0, 0, x + width, y + height); // reassign mask element.attribute('mask').value = mask; } }, { key: "render", value: function render(ctx) {// NO RENDER } }]); return _class40; }(svg.Element.ElementBase); // clip element svg.Element.clipPath = /*#__PURE__*/function (_svg$Element$ElementB12) { _inherits(_class41, _svg$Element$ElementB12); var _super40 = _createSuper(_class41); function _class41() { _classCallCheck(this, _class41); return _super40.apply(this, arguments); } _createClass(_class41, [{ key: "apply", value: function apply(ctx) { this.children.forEach(function (child) { if (typeof child.path !== 'undefined') { var transform = null; if (child.attribute('transform').hasValue()) { transform = new svg.Transform(child.attribute('transform').value); transform.apply(ctx); } child.path(ctx); ctx.clip(); if (transform) { transform.unapply(ctx); } } }); } }, { key: "render", value: function render(ctx) {// NO RENDER } }]); return _class41; }(svg.Element.ElementBase); // filters svg.Element.filter = /*#__PURE__*/function (_svg$Element$ElementB13) { _inherits(_class42, _svg$Element$ElementB13); var _super41 = _createSuper(_class42); function _class42() { _classCallCheck(this, _class42); return _super41.apply(this, arguments); } _createClass(_class42, [{ key: "apply", value: function apply(ctx, element) { // render as temp svg var bb = element.getBoundingBox(); var x = Math.floor(bb.x1); var y = Math.floor(bb.y1); var width = Math.floor(bb.width()); var height = Math.floor(bb.height()); // temporarily remove filter to avoid recursion var filter = element.style('filter').value; element.style('filter').value = ''; var px = 0, py = 0; this.children.forEach(function (child) { var efd = child.extraFilterDistance || 0; px = Math.max(px, efd); py = Math.max(py, efd); }); var c = document.createElement('canvas'); c.width = width + 2 * px; c.height = height + 2 * py; var tempCtx = c.getContext('2d'); tempCtx.translate(-x + px, -y + py); element.render(tempCtx); // apply filters this.children.forEach(function (child) { child.apply(tempCtx, 0, 0, width + 2 * px, height + 2 * py); }); // render on me ctx.drawImage(c, 0, 0, width + 2 * px, height + 2 * py, x - px, y - py, width + 2 * px, height + 2 * py); // reassign filter element.style('filter', true).value = filter; } }, { key: "render", value: function render(ctx) {// NO RENDER } }]); return _class42; }(svg.Element.ElementBase); svg.Element.feMorphology = /*#__PURE__*/function (_svg$Element$ElementB14) { _inherits(_class43, _svg$Element$ElementB14); var _super42 = _createSuper(_class43); function _class43() { _classCallCheck(this, _class43); return _super42.apply(this, arguments); } _createClass(_class43, [{ key: "apply", value: function apply(ctx, x, y, width, height) {// TODO: implement } }]); return _class43; }(svg.Element.ElementBase); svg.Element.feComposite = /*#__PURE__*/function (_svg$Element$ElementB15) { _inherits(_class44, _svg$Element$ElementB15); var _super43 = _createSuper(_class44); function _class44() { _classCallCheck(this, _class44); return _super43.apply(this, arguments); } _createClass(_class44, [{ key: "apply", value: function apply(ctx, x, y, width, height) {// TODO: implement } }]); return _class44; }(svg.Element.ElementBase); /** * @param {Uint8ClampedArray} img * @param {Integer} x * @param {Integer} y * @param {Float} width * @param {Float} height * @param {Integer} rgba * @returns {Integer} */ function imGet(img, x, y, width, height, rgba) { return img[y * width * 4 + x * 4 + rgba]; } /** * @param {Uint8ClampedArray} img * @param {Integer} x * @param {Integer} y * @param {Float} width * @param {Float} height * @param {Integer} rgba * @param {Float} val * @returns {void} */ function imSet(img, x, y, width, height, rgba, val) { img[y * width * 4 + x * 4 + rgba] = val; } svg.Element.feColorMatrix = /*#__PURE__*/function (_svg$Element$ElementB16) { _inherits(_class45, _svg$Element$ElementB16); var _super44 = _createSuper(_class45); function _class45(node) { var _this23; _classCallCheck(this, _class45); _this23 = _super44.call(this, node); var matrix = svg.ToNumberArray(_this23.attribute('values').value); switch (_this23.attribute('type').valueOrDefault('matrix')) { // https://www.w3.org/TR/SVG/filters.html#feColorMatrixElement case 'saturate': { var s = matrix[0]; matrix = [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]; break; } case 'hueRotate': { var a = matrix[0] * Math.PI / 180.0; var c = function c(m1, m2, m3) { return m1 + Math.cos(a) * m2 + Math.sin(a) * m3; }; matrix = [c(0.213, 0.787, -0.213), c(0.715, -0.715, -0.715), c(0.072, -0.072, 0.928), 0, 0, c(0.213, -0.213, 0.143), c(0.715, 0.285, 0.140), c(0.072, -0.072, -0.283), 0, 0, c(0.213, -0.213, -0.787), c(0.715, -0.715, 0.715), c(0.072, 0.928, 0.072), 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]; break; } case 'luminanceToAlpha': matrix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2125, 0.7154, 0.0721, 0, 0, 0, 0, 0, 0, 1]; break; } _this23.matrix = matrix; _this23._m = function (i, v) { var mi = matrix[i]; return mi * (mi < 0 ? v - 255 : v); }; return _this23; } _createClass(_class45, [{ key: "apply", value: function apply(ctx, x, y, width, height) { var m = this._m; // assuming x==0 && y==0 for now var srcData = ctx.getImageData(0, 0, width, height); for (var _y = 0; _y < height; _y++) { for (var _x = 0; _x < width; _x++) { var r = imGet(srcData.data, _x, _y, width, height, 0); var g = imGet(srcData.data, _x, _y, width, height, 1); var b = imGet(srcData.data, _x, _y, width, height, 2); var a = imGet(srcData.data, _x, _y, width, height, 3); imSet(srcData.data, _x, _y, width, height, 0, m(0, r) + m(1, g) + m(2, b) + m(3, a) + m(4, 1)); imSet(srcData.data, _x, _y, width, height, 1, m(5, r) + m(6, g) + m(7, b) + m(8, a) + m(9, 1)); imSet(srcData.data, _x, _y, width, height, 2, m(10, r) + m(11, g) + m(12, b) + m(13, a) + m(14, 1)); imSet(srcData.data, _x, _y, width, height, 3, m(15, r) + m(16, g) + m(17, b) + m(18, a) + m(19, 1)); } } ctx.clearRect(0, 0, width, height); ctx.putImageData(srcData, 0, 0); } }]); return _class45; }(svg.Element.ElementBase); svg.Element.feGaussianBlur = /*#__PURE__*/function (_svg$Element$ElementB17) { _inherits(_class46, _svg$Element$ElementB17); var _super45 = _createSuper(_class46); function _class46(node) { var _this24; _classCallCheck(this, _class46); _this24 = _super45.call(this, node); _this24.blurRadius = Math.floor(_this24.attribute('stdDeviation').numValue()); _this24.extraFilterDistance = _this24.blurRadius; return _this24; } _createClass(_class46, [{ key: "apply", value: function apply(ctx, x, y, width, height) { // Todo: This might not be a problem anymore with out `instanceof` fix // StackBlur requires canvas be on document ctx.canvas.id = svg.UniqueId(); ctx.canvas.style.display = 'none'; document.body.append(ctx.canvas); processCanvasRGBA(ctx.canvas, x, y, width, height, this.blurRadius); ctx.canvas.remove(); } }]); return _class46; }(svg.Element.ElementBase); // title element, do nothing svg.Element.title = /*#__PURE__*/function (_svg$Element$ElementB18) { _inherits(_class47, _svg$Element$ElementB18); var _super46 = _createSuper(_class47); function _class47(node) { _classCallCheck(this, _class47); return _super46.call(this); } return _class47; }(svg.Element.ElementBase); // desc element, do nothing svg.Element.desc = /*#__PURE__*/function (_svg$Element$ElementB19) { _inherits(_class48, _svg$Element$ElementB19); var _super47 = _createSuper(_class48); function _class48(node) { _classCallCheck(this, _class48); return _super47.call(this); } return _class48; }(svg.Element.ElementBase); svg.Element.MISSING = /*#__PURE__*/function (_svg$Element$ElementB20) { _inherits(_class49, _svg$Element$ElementB20); var _super48 = _createSuper(_class49); function _class49(node) { var _this25; _classCallCheck(this, _class49); _this25 = _super48.call(this); svg.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); return _this25; } return _class49; }(svg.Element.ElementBase); // element factory svg.CreateElement = function (node) { var className = node.nodeName.replace(/^[^:]+:/, '') // remove namespace .replace(/-/g, ''); // remove dashes var e; if (typeof svg.Element[className] !== 'undefined') { e = new svg.Element[className](node); } else { e = new svg.Element.MISSING(node); } e.type = node.nodeName; return e; }; // load from url svg.load = /*#__PURE__*/function () { var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(ctx, url) { var dom; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return svg.ajax(url, true); case 2: dom = _context.sent; return _context.abrupt("return", svg.loadXml(ctx, dom)); case 4: case "end": return _context.stop(); } } }, _callee); })); return function (_x2, _x3) { return _ref12.apply(this, arguments); }; }(); // load from xml svg.loadXml = function (ctx, xml) { return svg.loadXmlDoc(ctx, svg.parseXml(xml)); }; svg.loadXmlDoc = function (ctx, dom) { var res; svg.init(ctx); var mapXY = function mapXY(p) { var e = ctx.canvas; while (e) { p.x -= e.offsetLeft; p.y -= e.offsetTop; e = e.offsetParent; } if (window.scrollX) p.x += window.scrollX; if (window.scrollY) p.y += window.scrollY; return p; }; // bind mouse if (svg.opts.ignoreMouse !== true) { ctx.canvas.addEventListener('click', function (e) { var args = !isNullish$1(e) ? [e.clientX, e.clientY] : [event.clientX, event.clientY]; // eslint-disable-line no-restricted-globals var _mapXY = mapXY(_construct(svg.Point, args)), x = _mapXY.x, y = _mapXY.y; svg.Mouse.onclick(x, y); }); ctx.canvas.addEventListener('mousemove', function (e) { var args = !isNullish$1(e) ? [e.clientX, e.clientY] : [event.clientX, event.clientY]; // eslint-disable-line no-restricted-globals var _mapXY2 = mapXY(_construct(svg.Point, args)), x = _mapXY2.x, y = _mapXY2.y; svg.Mouse.onmousemove(x, y); }); } var e = svg.CreateElement(dom.documentElement); e.root = true; // render loop var isFirstRender = true; var draw = function draw(resolve) { svg.ViewPort.Clear(); if (ctx.canvas.parentNode) { svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight); } if (svg.opts.ignoreDimensions !== true) { // set canvas size if (e.style('width').hasValue()) { ctx.canvas.width = e.style('width').toPixels('x'); ctx.canvas.style.width = ctx.canvas.width + 'px'; } if (e.style('height').hasValue()) { ctx.canvas.height = e.style('height').toPixels('y'); ctx.canvas.style.height = ctx.canvas.height + 'px'; } } var cWidth = ctx.canvas.clientWidth || ctx.canvas.width; var cHeight = ctx.canvas.clientHeight || ctx.canvas.height; if (svg.opts.ignoreDimensions === true && e.style('width').hasValue() && e.style('height').hasValue()) { cWidth = e.style('width').toPixels('x'); cHeight = e.style('height').toPixels('y'); } svg.ViewPort.SetCurrent(cWidth, cHeight); if (!isNullish$1(svg.opts.offsetX)) { e.attribute('x', true).value = svg.opts.offsetX; } if (!isNullish$1(svg.opts.offsetY)) { e.attribute('y', true).value = svg.opts.offsetY; } if (!isNullish$1(svg.opts.scaleWidth) || !isNullish$1(svg.opts.scaleHeight)) { var viewBox = svg.ToNumberArray(e.attribute('viewBox').value); var xRatio = null, yRatio = null; if (!isNullish$1(svg.opts.scaleWidth)) { if (e.attribute('width').hasValue()) { xRatio = e.attribute('width').toPixels('x') / svg.opts.scaleWidth; } else if (!isNaN(viewBox[2])) { xRatio = viewBox[2] / svg.opts.scaleWidth; } } if (!isNullish$1(svg.opts.scaleHeight)) { if (e.attribute('height').hasValue()) { yRatio = e.attribute('height').toPixels('y') / svg.opts.scaleHeight; } else if (!isNaN(viewBox[3])) { yRatio = viewBox[3] / svg.opts.scaleHeight; } } if (isNullish$1(xRatio)) { xRatio = yRatio; } if (isNullish$1(yRatio)) { yRatio = xRatio; } e.attribute('width', true).value = svg.opts.scaleWidth; e.attribute('height', true).value = svg.opts.scaleHeight; e.attribute('viewBox', true).value = '0 0 ' + cWidth * xRatio + ' ' + cHeight * yRatio; e.attribute('preserveAspectRatio', true).value = 'none'; } // clear and render if (svg.opts.ignoreClear !== true) { ctx.clearRect(0, 0, cWidth, cHeight); } e.render(ctx); if (isFirstRender) { isFirstRender = false; resolve(dom); } }; var waitingForImages = true; svg.intervalID = setInterval(function () { var needUpdate = false; if (waitingForImages && svg.ImagesLoaded()) { waitingForImages = false; needUpdate = true; } // need update from mouse events? if (svg.opts.ignoreMouse !== true) { needUpdate = needUpdate || svg.Mouse.hasEvents(); } // need update from animations? if (svg.opts.ignoreAnimation !== true) { svg.Animations.forEach(function (animation) { var needAnimationUpdate = animation.update(1000 / svg.FRAMERATE); needUpdate = needUpdate || needAnimationUpdate; }); } // need update from redraw? if (typeof svg.opts.forceRedraw === 'function') { if (svg.opts.forceRedraw() === true) { needUpdate = true; } } // render if needed if (needUpdate) { draw(res); svg.Mouse.runEvents(); // run and clear our events } }, 1000 / svg.FRAMERATE); // Todo: Replace with an image loading Promise utility? // eslint-disable-next-line promise/avoid-new return new Promise(function (resolve, reject) { if (svg.ImagesLoaded()) { waitingForImages = false; draw(resolve); return; } res = resolve; }); }; svg.stop = function () { if (svg.intervalID) { clearInterval(svg.intervalID); } }; svg.Mouse = { events: [], hasEvents: function hasEvents() { return this.events.length !== 0; }, onclick: function onclick(x, y) { this.events.push({ type: 'onclick', x: x, y: y, run: function run(e) { if (e.onclick) e.onclick(); } }); }, onmousemove: function onmousemove(x, y) { this.events.push({ type: 'onmousemove', x: x, y: y, run: function run(e) { if (e.onmousemove) e.onmousemove(); } }); }, eventElements: [], checkPath: function checkPath(element, ctx) { var _this26 = this; this.events.forEach(function (_ref13, i) { var x = _ref13.x, y = _ref13.y; if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { _this26.eventElements[i] = element; } }); }, checkBoundingBox: function checkBoundingBox(element, bb) { var _this27 = this; this.events.forEach(function (_ref14, i) { var x = _ref14.x, y = _ref14.y; if (bb.isPointInBox(x, y)) { _this27.eventElements[i] = element; } }); }, runEvents: function runEvents() { var _this28 = this; svg.ctx.canvas.style.cursor = ''; this.events.forEach(function (e, i) { var element = _this28.eventElements[i]; while (element) { e.run(element); element = element.parent; } }); // done running, clear this.events = []; this.eventElements = []; } }; return svg; } if (typeof CanvasRenderingContext2D !== 'undefined') { CanvasRenderingContext2D.prototype.drawSvg = function (s, dx, dy, dw, dh) { canvg(this.canvas, s, { ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true, ignoreClear: true, offsetX: dx, offsetY: dy, scaleWidth: dw, scaleHeight: dh }); }; } /** * @module jQueryPluginDBox */ /** * @param {external:jQuery} $ * @param {PlainObject} [strings] * @param {PlainObject} [strings.ok] * @param {PlainObject} [strings.cancel] * @returns {external:jQuery} */ function jQueryPluginDBox($) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$ok = _ref.ok, okString = _ref$ok === void 0 ? 'Ok' : _ref$ok, _ref$cancel = _ref.cancel, cancelString = _ref$cancel === void 0 ? 'Cancel' : _ref$cancel; // This sets up alternative dialog boxes. They mostly work the same way as // their UI counterparts, expect instead of returning the result, a callback // needs to be included that returns the result as its first parameter. // In the future we may want to add additional types of dialog boxes, since // they should be easy to handle this way. $('#dialog_container').draggable({ cancel: '#dialog_content, #dialog_buttons *', containment: 'window' }).css('position', 'absolute'); var box = $('#dialog_box'), btnHolder = $('#dialog_buttons'), dialogContent = $('#dialog_content'); /** * @typedef {PlainObject} module:jQueryPluginDBox.PromiseResultObject * @property {string|true} response * @property {boolean} checked */ /** * Resolves to `false` (if cancelled), for prompts and selects * without checkboxes, it resolves to the value of the form control. For other * types without checkboxes, it resolves to `true`. For checkboxes, it resolves * to an object with the `response` key containing the same value as the previous * mentioned (string or `true`) and a `checked` (boolean) property. * @typedef {Promise<boolean|string|module:jQueryPluginDBox.PromiseResultObject>} module:jQueryPluginDBox.ResultPromise */ /** * @typedef {PlainObject} module:jQueryPluginDBox.SelectOption * @property {string} text * @property {string} value */ /** * @typedef {PlainObject} module:jQueryPluginDBox.CheckboxInfo * @property {string} label Label for the checkbox * @property {string} value Value of the checkbox * @property {string} tooltip Tooltip on the checkbox label * @property {boolean} checked Whether the checkbox is checked by default */ /** * Triggered upon a change of value for the select pull-down. * @callback module:jQueryPluginDBox.SelectChangeListener * @returns {void} */ /** * Creates a dialog of the specified type with a given message * and any defaults and type-specific metadata. Returns a `Promise` * which resolves differently depending on whether the dialog * was cancelled or okayed (with the response and any checked state). * @param {"alert"|"prompt"|"select"|"process"} type * @param {string} msg * @param {string} [defaultVal] * @param {module:jQueryPluginDBox.SelectOption[]} [opts] * @param {module:jQueryPluginDBox.SelectChangeListener} [changeListener] * @param {module:jQueryPluginDBox.CheckboxInfo} [checkbox] * @returns {jQueryPluginDBox.ResultPromise} */ function dbox(type, msg, defaultVal, opts, changeListener, checkbox) { dialogContent.html('<p>' + msg.replace(/\n/g, '</p><p>') + '</p>').toggleClass('prompt', type === 'prompt'); btnHolder.empty(); var ok = $('<input type="button" data-ok="" value="' + okString + '">').appendTo(btnHolder); return new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new if (type !== 'alert') { $('<input type="button" value="' + cancelString + '">').appendTo(btnHolder).click(function () { box.hide(); resolve(false); }); } var ctrl, chkbx; if (type === 'prompt') { ctrl = $('<input type="text">').prependTo(btnHolder); ctrl.val(defaultVal || ''); ctrl.bind('keydown', 'return', function () { ok.click(); }); } else if (type === 'select') { var div = $('<div style="text-align:center;">'); ctrl = $("<select aria-label=\"".concat(msg, "\">")).appendTo(div); if (checkbox) { var label = $('<label>').text(checkbox.label); chkbx = $('<input type="checkbox">').appendTo(label); chkbx.val(checkbox.value); if (checkbox.tooltip) { label.attr('title', checkbox.tooltip); } chkbx.prop('checked', Boolean(checkbox.checked)); div.append($('<div>').append(label)); } $.each(opts || [], function (opt, val) { if (_typeof(val) === 'object') { ctrl.append($('<option>').val(val.value).html(val.text)); } else { ctrl.append($('<option>').html(val)); } }); dialogContent.append(div); if (defaultVal) { ctrl.val(defaultVal); } if (changeListener) { ctrl.bind('change', 'return', changeListener); } ctrl.bind('keydown', 'return', function () { ok.click(); }); } else if (type === 'process') { ok.hide(); } box.show(); ok.click(function () { box.hide(); var response = type === 'prompt' || type === 'select' ? ctrl.val() : true; if (chkbx) { resolve({ response: response, checked: chkbx.prop('checked') }); return; } resolve(response); }).focus(); if (type === 'prompt' || type === 'select') { ctrl.focus(); } }); } /** * @param {string} msg Message to alert * @returns {jQueryPluginDBox.ResultPromise} */ $.alert = function (msg) { return dbox('alert', msg); }; /** * @param {string} msg Message for which to ask confirmation * @returns {jQueryPluginDBox.ResultPromise} */ $.confirm = function (msg) { return dbox('confirm', msg); }; /** * @param {string} msg Message to indicate upon cancelable indicator * @returns {jQueryPluginDBox.ResultPromise} */ $.process_cancel = function (msg) { return dbox('process', msg); }; /** * @param {string} msg Message to accompany the prompt * @param {string} [defaultText=''] The default text to show for the prompt * @returns {jQueryPluginDBox.ResultPromise} */ $.prompt = function (msg) { var defaultText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; return dbox('prompt', msg, defaultText); }; $.select = function (msg, opts, changeListener, txt, checkbox) { return dbox('select', msg, txt, opts, changeListener, checkbox); }; return $; } /** * Group: Undo/Redo history management. */ var HistoryEventTypes = { BEFORE_APPLY: 'before_apply', AFTER_APPLY: 'after_apply', BEFORE_UNAPPLY: 'before_unapply', AFTER_UNAPPLY: 'after_unapply' }; /** * Base class for commands. */ var Command = /*#__PURE__*/function () { function Command() { _classCallCheck(this, Command); } _createClass(Command, [{ key: "getText", /** * @returns {string} */ value: function getText() { return this.text; } /** * @param {module:history.HistoryEventHandler} handler * @param {callback} applyFunction * @returns {void} */ }, { key: "apply", value: function apply(handler, applyFunction) { handler && handler.handleHistoryEvent(HistoryEventTypes.BEFORE_APPLY, this); applyFunction(handler); handler && handler.handleHistoryEvent(HistoryEventTypes.AFTER_APPLY, this); } /** * @param {module:history.HistoryEventHandler} handler * @param {callback} unapplyFunction * @returns {void} */ }, { key: "unapply", value: function unapply(handler, unapplyFunction) { handler && handler.handleHistoryEvent(HistoryEventTypes.BEFORE_UNAPPLY, this); unapplyFunction(); handler && handler.handleHistoryEvent(HistoryEventTypes.AFTER_UNAPPLY, this); } /** * @returns {Element[]} Array with element associated with this command * This function needs to be surcharged if multiple elements are returned. */ }, { key: "elements", value: function elements() { return [this.elem]; } /** * @returns {string} String with element associated with this command */ }, { key: "type", value: function type() { return this.constructor.name; } }]); return Command; }(); // Todo: Figure out why the interface members aren't showing // up (with or without modules applied), despite our apparently following // http://usejsdoc.org/tags-interface.html#virtual-comments /** * An interface that all command objects must implement. * @interface module:history.HistoryCommand */ /** * Applies. * * @function module:history.HistoryCommand#apply * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void|true} */ /** * * Unapplies. * @function module:history.HistoryCommand#unapply * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void|true} */ /** * Returns the elements. * @function module:history.HistoryCommand#elements * @returns {Element[]} */ /** * Gets the text. * @function module:history.HistoryCommand#getText * @returns {string} */ /** * Gives the type. * @function module:history.HistoryCommand.type * @returns {string} */ /** * @event module:history~Command#event:history * @type {module:history.HistoryCommand} */ /** * An interface for objects that will handle history events. * @interface module:history.HistoryEventHandler */ /** * * @function module:history.HistoryEventHandler#handleHistoryEvent * @param {string} eventType One of the HistoryEvent types * @param {module:history~Command#event:history} command * @listens module:history~Command#event:history * @returns {void} * */ /** * History command for an element that had its DOM position changed. * @implements {module:history.HistoryCommand} */ var MoveElementCommand = /*#__PURE__*/function (_Command) { _inherits(MoveElementCommand, _Command); var _super = _createSuper(MoveElementCommand); /** * @param {Element} elem - The DOM element that was moved * @param {Element} oldNextSibling - The element's next sibling before it was moved * @param {Element} oldParent - The element's parent before it was moved * @param {string} [text] - An optional string visible to user related to this change */ function MoveElementCommand(elem, oldNextSibling, oldParent, text) { var _this; _classCallCheck(this, MoveElementCommand); _this = _super.call(this); _this.elem = elem; _this.text = text ? 'Move ' + elem.tagName + ' to ' + text : 'Move ' + elem.tagName; _this.oldNextSibling = oldNextSibling; _this.oldParent = oldParent; _this.newNextSibling = elem.nextSibling; _this.newParent = elem.parentNode; return _this; } /** * Re-positions the element. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ _createClass(MoveElementCommand, [{ key: "apply", value: function apply(handler) { var _this2 = this; _get(_getPrototypeOf(MoveElementCommand.prototype), "apply", this).call(this, handler, function () { _this2.elem = _this2.newParent.insertBefore(_this2.elem, _this2.newNextSibling); }); } /** * Positions the element back to its original location. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ }, { key: "unapply", value: function unapply(handler) { var _this3 = this; _get(_getPrototypeOf(MoveElementCommand.prototype), "unapply", this).call(this, handler, function () { _this3.elem = _this3.oldParent.insertBefore(_this3.elem, _this3.oldNextSibling); }); } }]); return MoveElementCommand; }(Command); /** * History command for an element that was added to the DOM. * @implements {module:history.HistoryCommand} */ var InsertElementCommand = /*#__PURE__*/function (_Command2) { _inherits(InsertElementCommand, _Command2); var _super2 = _createSuper(InsertElementCommand); /** * @param {Element} elem - The newly added DOM element * @param {string} text - An optional string visible to user related to this change */ function InsertElementCommand(elem, text) { var _this4; _classCallCheck(this, InsertElementCommand); _this4 = _super2.call(this); _this4.elem = elem; _this4.text = text || 'Create ' + elem.tagName; _this4.parent = elem.parentNode; _this4.nextSibling = _this4.elem.nextSibling; return _this4; } /** * Re-inserts the new element. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ _createClass(InsertElementCommand, [{ key: "apply", value: function apply(handler) { var _this5 = this; _get(_getPrototypeOf(InsertElementCommand.prototype), "apply", this).call(this, handler, function () { _this5.elem = _this5.parent.insertBefore(_this5.elem, _this5.nextSibling); }); } /** * Removes the element. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ }, { key: "unapply", value: function unapply(handler) { var _this6 = this; _get(_getPrototypeOf(InsertElementCommand.prototype), "unapply", this).call(this, handler, function () { _this6.parent = _this6.elem.parentNode; _this6.elem.remove(); }); } }]); return InsertElementCommand; }(Command); /** * History command for an element removed from the DOM. * @implements {module:history.HistoryCommand} */ var RemoveElementCommand = /*#__PURE__*/function (_Command3) { _inherits(RemoveElementCommand, _Command3); var _super3 = _createSuper(RemoveElementCommand); /** * @param {Element} elem - The removed DOM element * @param {Node} oldNextSibling - The DOM element's nextSibling when it was in the DOM * @param {Element} oldParent - The DOM element's parent * @param {string} [text] - An optional string visible to user related to this change */ function RemoveElementCommand(elem, oldNextSibling, oldParent, text) { var _this7; _classCallCheck(this, RemoveElementCommand); _this7 = _super3.call(this); _this7.elem = elem; _this7.text = text || 'Delete ' + elem.tagName; _this7.nextSibling = oldNextSibling; _this7.parent = oldParent; // special hack for webkit: remove this element's entry in the svgTransformLists map removeElementFromListMap(elem); return _this7; } /** * Re-removes the new element. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ _createClass(RemoveElementCommand, [{ key: "apply", value: function apply(handler) { var _this8 = this; _get(_getPrototypeOf(RemoveElementCommand.prototype), "apply", this).call(this, handler, function () { removeElementFromListMap(_this8.elem); _this8.parent = _this8.elem.parentNode; _this8.elem.remove(); }); } /** * Re-adds the new element. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ }, { key: "unapply", value: function unapply(handler) { var _this9 = this; _get(_getPrototypeOf(RemoveElementCommand.prototype), "unapply", this).call(this, handler, function () { removeElementFromListMap(_this9.elem); if (isNullish(_this9.nextSibling)) { if (window.console) { console.error('Reference element was lost'); } } _this9.parent.insertBefore(_this9.elem, _this9.nextSibling); // Don't use `before` or `prepend` as `this.nextSibling` may be `null` }); } }]); return RemoveElementCommand; }(Command); /** * @typedef {"#text"|"#href"|string} module:history.CommandAttributeName */ /** * @typedef {PlainObject<module:history.CommandAttributeName, string>} module:history.CommandAttributes */ /** * History command to make a change to an element. * Usually an attribute change, but can also be textcontent. * @implements {module:history.HistoryCommand} */ var ChangeElementCommand = /*#__PURE__*/function (_Command4) { _inherits(ChangeElementCommand, _Command4); var _super4 = _createSuper(ChangeElementCommand); /** * @param {Element} elem - The DOM element that was changed * @param {module:history.CommandAttributes} attrs - Attributes to be changed with the values they had *before* the change * @param {string} text - An optional string visible to user related to this change */ function ChangeElementCommand(elem, attrs, text) { var _this10; _classCallCheck(this, ChangeElementCommand); _this10 = _super4.call(this); _this10.elem = elem; _this10.text = text ? 'Change ' + elem.tagName + ' ' + text : 'Change ' + elem.tagName; _this10.newValues = {}; _this10.oldValues = attrs; for (var attr in attrs) { if (attr === '#text') { _this10.newValues[attr] = elem.textContent; } else if (attr === '#href') { _this10.newValues[attr] = getHref(elem); } else { _this10.newValues[attr] = elem.getAttribute(attr); } } return _this10; } /** * Performs the stored change action. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ _createClass(ChangeElementCommand, [{ key: "apply", value: function apply(handler) { var _this11 = this; _get(_getPrototypeOf(ChangeElementCommand.prototype), "apply", this).call(this, handler, function () { var bChangedTransform = false; Object.entries(_this11.newValues).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), attr = _ref2[0], value = _ref2[1]; if (value) { if (attr === '#text') { _this11.elem.textContent = value; } else if (attr === '#href') { setHref(_this11.elem, value); } else { _this11.elem.setAttribute(attr, value); } } else if (attr === '#text') { _this11.elem.textContent = ''; } else { _this11.elem.setAttribute(attr, ''); _this11.elem.removeAttribute(attr); } if (attr === 'transform') { bChangedTransform = true; } }); // relocate rotational transform, if necessary if (!bChangedTransform) { var angle = getRotationAngle(_this11.elem); if (angle) { var bbox = _this11.elem.getBBox(); var cx = bbox.x + bbox.width / 2; var cy = bbox.y + bbox.height / 2; var rotate = ['rotate(', angle, ' ', cx, ',', cy, ')'].join(''); if (rotate !== _this11.elem.getAttribute('transform')) { _this11.elem.setAttribute('transform', rotate); } } } }); } /** * Reverses the stored change action. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ }, { key: "unapply", value: function unapply(handler) { var _this12 = this; _get(_getPrototypeOf(ChangeElementCommand.prototype), "unapply", this).call(this, handler, function () { var bChangedTransform = false; Object.entries(_this12.oldValues).forEach(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), attr = _ref4[0], value = _ref4[1]; if (value) { if (attr === '#text') { _this12.elem.textContent = value; } else if (attr === '#href') { setHref(_this12.elem, value); } else { _this12.elem.setAttribute(attr, value); } } else if (attr === '#text') { _this12.elem.textContent = ''; } else { _this12.elem.removeAttribute(attr); } if (attr === 'transform') { bChangedTransform = true; } }); // relocate rotational transform, if necessary if (!bChangedTransform) { var angle = getRotationAngle(_this12.elem); if (angle) { var bbox = _this12.elem.getBBox(); var cx = bbox.x + bbox.width / 2, cy = bbox.y + bbox.height / 2; var rotate = ['rotate(', angle, ' ', cx, ',', cy, ')'].join(''); if (rotate !== _this12.elem.getAttribute('transform')) { _this12.elem.setAttribute('transform', rotate); } } } // Remove transformlist to prevent confusion that causes bugs like 575. removeElementFromListMap(_this12.elem); }); } }]); return ChangeElementCommand; }(Command); // TODO: create a 'typing' command object that tracks changes in text // if a new Typing command is created and the top command on the stack is also a Typing // and they both affect the same element, then collapse the two commands into one /** * History command that can contain/execute multiple other commands. * @implements {module:history.HistoryCommand} */ var BatchCommand = /*#__PURE__*/function (_Command5) { _inherits(BatchCommand, _Command5); var _super5 = _createSuper(BatchCommand); /** * @param {string} [text] - An optional string visible to user related to this change */ function BatchCommand(text) { var _this13; _classCallCheck(this, BatchCommand); _this13 = _super5.call(this); _this13.text = text || 'Batch Command'; _this13.stack = []; return _this13; } /** * Runs "apply" on all subcommands. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ _createClass(BatchCommand, [{ key: "apply", value: function apply(handler) { var _this14 = this; _get(_getPrototypeOf(BatchCommand.prototype), "apply", this).call(this, handler, function () { _this14.stack.forEach(function (stackItem) { console.assert(stackItem, 'stack item should not be null'); stackItem && stackItem.apply(handler); }); }); } /** * Runs "unapply" on all subcommands. * @param {module:history.HistoryEventHandler} handler * @fires module:history~Command#event:history * @returns {void} */ }, { key: "unapply", value: function unapply(handler) { var _this15 = this; _get(_getPrototypeOf(BatchCommand.prototype), "unapply", this).call(this, handler, function () { _this15.stack.reverse().forEach(function (stackItem) { console.assert(stackItem, 'stack item should not be null'); stackItem && stackItem.unapply(handler); }); }); } /** * Iterate through all our subcommands. * @returns {Element[]} All the elements we are changing */ }, { key: "elements", value: function elements() { var elems = []; var cmd = this.stack.length; while (cmd--) { if (!this.stack[cmd]) continue; var thisElems = this.stack[cmd].elements(); var elem = thisElems.length; while (elem--) { if (!elems.includes(thisElems[elem])) { elems.push(thisElems[elem]); } } } return elems; } /** * Adds a given command to the history stack. * @param {Command} cmd - The undo command object to add * @returns {void} */ }, { key: "addSubCommand", value: function addSubCommand(cmd) { console.assert(cmd !== null, 'cmd should not be null'); this.stack.push(cmd); } /** * @returns {boolean} Indicates whether or not the batch command is empty */ }, { key: "isEmpty", value: function isEmpty() { return !this.stack.length; } }]); return BatchCommand; }(Command); /** * */ var UndoManager = /*#__PURE__*/function () { /** * @param {module:history.HistoryEventHandler} historyEventHandler */ function UndoManager(historyEventHandler) { _classCallCheck(this, UndoManager); this.handler_ = historyEventHandler || null; this.undoStackPointer = 0; this.undoStack = []; // this is the stack that stores the original values, the elements and // the attribute name for begin/finish this.undoChangeStackPointer = -1; this.undoableChangeStack = []; } /** * Resets the undo stack, effectively clearing the undo/redo history. * @returns {void} */ _createClass(UndoManager, [{ key: "resetUndoStack", value: function resetUndoStack() { this.undoStack = []; this.undoStackPointer = 0; } /** * @returns {Integer} Current size of the undo history stack */ }, { key: "getUndoStackSize", value: function getUndoStackSize() { return this.undoStackPointer; } /** * @returns {Integer} Current size of the redo history stack */ }, { key: "getRedoStackSize", value: function getRedoStackSize() { return this.undoStack.length - this.undoStackPointer; } /** * @returns {string} String associated with the next undo command */ }, { key: "getNextUndoCommandText", value: function getNextUndoCommandText() { return this.undoStackPointer > 0 ? this.undoStack[this.undoStackPointer - 1].getText() : ''; } /** * @returns {string} String associated with the next redo command */ }, { key: "getNextRedoCommandText", value: function getNextRedoCommandText() { return this.undoStackPointer < this.undoStack.length ? this.undoStack[this.undoStackPointer].getText() : ''; } /** * Performs an undo step. * @returns {void} */ }, { key: "undo", value: function undo() { if (this.undoStackPointer > 0) { var cmd = this.undoStack[--this.undoStackPointer]; cmd.unapply(this.handler_); } } /** * Performs a redo step. * @returns {void} */ }, { key: "redo", value: function redo() { if (this.undoStackPointer < this.undoStack.length && this.undoStack.length > 0) { var cmd = this.undoStack[this.undoStackPointer++]; cmd.apply(this.handler_); } } /** * Adds a command object to the undo history stack. * @param {Command} cmd - The command object to add * @returns {void} */ }, { key: "addCommandToHistory", value: function addCommandToHistory(cmd) { // TODO: we MUST compress consecutive text changes to the same element // (right now each keystroke is saved as a separate command that includes the // entire text contents of the text element) // TODO: consider limiting the history that we store here (need to do some slicing) // if our stack pointer is not at the end, then we have to remove // all commands after the pointer and insert the new command if (this.undoStackPointer < this.undoStack.length && this.undoStack.length > 0) { this.undoStack = this.undoStack.splice(0, this.undoStackPointer); } this.undoStack.push(cmd); this.undoStackPointer = this.undoStack.length; } /** * This function tells the canvas to remember the old values of the * `attrName` attribute for each element sent in. The elements and values * are stored on a stack, so the next call to `finishUndoableChange()` will * pop the elements and old values off the stack, gets the current values * from the DOM and uses all of these to construct the undo-able command. * @param {string} attrName - The name of the attribute being changed * @param {Element[]} elems - Array of DOM elements being changed * @returns {void} */ }, { key: "beginUndoableChange", value: function beginUndoableChange(attrName, elems) { var p = ++this.undoChangeStackPointer; var i = elems.length; var oldValues = new Array(i), elements = new Array(i); while (i--) { var elem = elems[i]; if (isNullish(elem)) { continue; } elements[i] = elem; oldValues[i] = elem.getAttribute(attrName); } this.undoableChangeStack[p] = { attrName: attrName, oldValues: oldValues, elements: elements }; } /** * This function returns a `BatchCommand` object which summarizes the * change since `beginUndoableChange` was called. The command can then * be added to the command history. * @returns {BatchCommand} Batch command object with resulting changes */ }, { key: "finishUndoableChange", value: function finishUndoableChange() { var p = this.undoChangeStackPointer--; var changeset = this.undoableChangeStack[p]; var attrName = changeset.attrName; var batchCmd = new BatchCommand('Change ' + attrName); var i = changeset.elements.length; while (i--) { var elem = changeset.elements[i]; if (isNullish(elem)) { continue; } var changes = {}; changes[attrName] = changeset.oldValues[i]; if (changes[attrName] !== elem.getAttribute(attrName)) { batchCmd.addSubCommand(new ChangeElementCommand(elem, changes, attrName)); } } this.undoableChangeStack[p] = null; return batchCmd; } }]); return UndoManager; }(); var hstry = /*#__PURE__*/Object.freeze({ __proto__: null, HistoryEventTypes: HistoryEventTypes, Command: Command, MoveElementCommand: MoveElementCommand, InsertElementCommand: InsertElementCommand, RemoveElementCommand: RemoveElementCommand, ChangeElementCommand: ChangeElementCommand, BatchCommand: BatchCommand, UndoManager: UndoManager }); var $$4 = jQuery; var segData = { 2: ['x', 'y'], // PATHSEG_MOVETO_ABS 4: ['x', 'y'], // PATHSEG_LINETO_ABS 6: ['x', 'y', 'x1', 'y1', 'x2', 'y2'], // PATHSEG_CURVETO_CUBIC_ABS 8: ['x', 'y', 'x1', 'y1'], // PATHSEG_CURVETO_QUADRATIC_ABS 10: ['x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'], // PATHSEG_ARC_ABS 12: ['x'], // PATHSEG_LINETO_HORIZONTAL_ABS 14: ['y'], // PATHSEG_LINETO_VERTICAL_ABS 16: ['x', 'y', 'x2', 'y2'], // PATHSEG_CURVETO_CUBIC_SMOOTH_ABS 18: ['x', 'y'] // PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS }; /** * @tutorial LocaleDocs * @typedef {module:locale.LocaleStrings|PlainObject} module:path.uiStrings * @property {PlainObject<string, string>} ui */ var uiStrings = {}; /** * @function module:path.setUiStrings * @param {module:path.uiStrings} strs * @returns {void} */ var setUiStrings = function setUiStrings(strs) { Object.assign(uiStrings, strs.ui); }; var pathFuncs = []; var linkControlPts = true; // Stores references to paths via IDs. // TODO: Make this cross-document happy. var pathData = {}; /** * @function module:path.setLinkControlPoints * @param {boolean} lcp * @returns {void} */ var setLinkControlPoints = function setLinkControlPoints(lcp) { linkControlPts = lcp; }; /** * @name module:path.path * @type {null|module:path.Path} * @memberof module:path */ var path$1 = null; // eslint-disable-line import/no-mutable-exports var editorContext_$1 = null; /** * @external MouseEvent */ /** * Object with the following keys/values. * @typedef {PlainObject} module:path.SVGElementJSON * @property {string} element - Tag name of the SVG element to create * @property {PlainObject<string, string>} attr - Has key-value attributes to assign to the new element. An `id` should be set so that {@link module:utilities.EditorContext#addSVGElementFromJson} can later re-identify the element for modification or replacement. * @property {boolean} [curStyles=false] - Indicates whether current style attributes should be applied first * @property {module:path.SVGElementJSON[]} [children] - Data objects to be added recursively as children * @property {string} [namespace="http://www.w3.org/2000/svg"] - Indicate a (non-SVG) namespace */ /** * @interface module:path.EditorContext * @property {module:select.SelectorManager} selectorManager * @property {module:svgcanvas.SvgCanvas} canvas */ /** * @function module:path.EditorContext#call * @param {"selected"|"changed"} ev - String with the event name * @param {module:svgcanvas.SvgCanvas#event:selected|module:svgcanvas.SvgCanvas#event:changed} arg - Argument to pass through to the callback function. If the event is "changed", an array of `Element`s is passed; if "selected", a single-item array of `Element` is passed. * @returns {void} */ /** * @function module:path.EditorContext#resetD * @param {SVGPathElement} p * @returns {void} */ /** * Note: This doesn't round to an integer necessarily. * @function module:path.EditorContext#round * @param {Float} val * @returns {Float} Rounded value to nearest value based on `currentZoom` */ /** * @function module:path.EditorContext#clearSelection * @param {boolean} [noCall] - When `true`, does not call the "selected" handler * @returns {void} */ /** * @function module:path.EditorContext#addToSelection * @param {Element[]} elemsToAdd - An array of DOM elements to add to the selection * @param {boolean} showGrips - Indicates whether the resize grips should be shown * @returns {void} */ /** * @function module:path.EditorContext#addCommandToHistory * @param {Command} cmd * @returns {void} */ /** * @function module:path.EditorContext#remapElement * @param {Element} selected - DOM element to be changed * @param {PlainObject<string, string>} changes - Object with changes to be remapped * @param {SVGMatrix} m - Matrix object to use for remapping coordinates * @returns {void} */ /** * @function module:path.EditorContext#addSVGElementFromJson * @param {module:path.SVGElementJSON} data * @returns {Element} The new element */ /** * @function module:path.EditorContext#getGridSnapping * @returns {boolean} */ /** * @function module:path.EditorContext#getOpacity * @returns {Float} */ /** * @function module:path.EditorContext#getSelectedElements * @returns {Element[]} the array with selected DOM elements */ /** * @function module:path.EditorContext#getContainer * @returns {Element} */ /** * @function module:path.EditorContext#setStarted * @param {boolean} s * @returns {void} */ /** * @function module:path.EditorContext#getRubberBox * @returns {SVGRectElement} */ /** * @function module:path.EditorContext#setRubberBox * @param {SVGRectElement} rb * @returns {SVGRectElement} Same as parameter passed in */ /** * @function module:path.EditorContext#addPtsToSelection * @param {PlainObject} cfg * @param {boolean} cfg.closedSubpath * @param {SVGCircleElement[]} cfg.grips * @returns {void} */ /** * @function module:path.EditorContext#endChanges * @param {PlainObject} cfg * @param {string} cfg.cmd * @param {Element} cfg.elem * @returns {void} */ /** * @function module:path.EditorContext#getCurrentZoom * @returns {Float} The current zoom level */ /** * Returns the last created DOM element ID string. * @function module:path.EditorContext#getId * @returns {string} */ /** * Creates and returns a unique ID string for a DOM element. * @function module:path.EditorContext#getNextId * @returns {string} */ /** * Gets the desired element from a mouse event. * @function module:path.EditorContext#getMouseTarget * @param {external:MouseEvent} evt - Event object from the mouse event * @returns {Element} DOM element we want */ /** * @function module:path.EditorContext#getCurrentMode * @returns {string} */ /** * @function module:path.EditorContext#setCurrentMode * @param {string} cm The mode * @returns {string} The same mode as passed in */ /** * @function module:path.EditorContext#getDrawnPath * @returns {SVGPathElement|null} */ /** * @function module:path.EditorContext#setDrawnPath * @param {SVGPathElement|null} dp * @returns {SVGPathElement|null} The same value as passed in */ /** * @function module:path.EditorContext#getSVGRoot * @returns {SVGSVGElement} */ /** * @function module:path.init * @param {module:path.EditorContext} editorContext * @returns {void} */ var init$2 = function init(editorContext) { editorContext_$1 = editorContext; pathFuncs = [0, 'ClosePath']; var pathFuncsStrs = ['Moveto', 'Lineto', 'CurvetoCubic', 'CurvetoQuadratic', 'Arc', 'LinetoHorizontal', 'LinetoVertical', 'CurvetoCubicSmooth', 'CurvetoQuadraticSmooth']; $$4.each(pathFuncsStrs, function (i, s) { pathFuncs.push(s + 'Abs'); pathFuncs.push(s + 'Rel'); }); }; /** * @function module:path.insertItemBefore * @param {Element} elem * @param {Segment} newseg * @param {Integer} index * @returns {void} */ var insertItemBefore = function insertItemBefore(elem, newseg, index) { // Support insertItemBefore on paths for FF2 var list = elem.pathSegList; if (supportsPathInsertItemBefore()) { list.insertItemBefore(newseg, index); return; } var len = list.numberOfItems; var arr = []; for (var i = 0; i < len; i++) { var curSeg = list.getItem(i); arr.push(curSeg); } list.clear(); for (var _i = 0; _i < len; _i++) { if (_i === index) { // index + 1 list.appendItem(newseg); } list.appendItem(arr[_i]); } }; /** * @function module:path.ptObjToArr * @todo See if this should just live in `replacePathSeg` * @param {string} type * @param {SVGPathSegMovetoAbs|SVGPathSegLinetoAbs|SVGPathSegCurvetoCubicAbs|SVGPathSegCurvetoQuadraticAbs|SVGPathSegArcAbs|SVGPathSegLinetoHorizontalAbs|SVGPathSegLinetoVerticalAbs|SVGPathSegCurvetoCubicSmoothAbs|SVGPathSegCurvetoQuadraticSmoothAbs} segItem * @returns {ArgumentsArray} */ var ptObjToArr = function ptObjToArr(type, segItem) { var props = segData[type]; return props.map(function (prop) { return segItem[prop]; }); }; /** * @function module:path.getGripPt * @param {Segment} seg * @param {module:math.XYObject} altPt * @returns {module:math.XYObject} */ var getGripPt = function getGripPt(seg, altPt) { var pth = seg.path; var out = { x: altPt ? altPt.x : seg.item.x, y: altPt ? altPt.y : seg.item.y }; if (pth.matrix) { var pt = transformPoint(out.x, out.y, pth.matrix); out = pt; } var currentZoom = editorContext_$1.getCurrentZoom(); out.x *= currentZoom; out.y *= currentZoom; return out; }; /** * @function module:path.getPointFromGrip * @param {module:math.XYObject} pt * @param {module:path.Path} pth * @returns {module:math.XYObject} */ var getPointFromGrip = function getPointFromGrip(pt, pth) { var out = { x: pt.x, y: pt.y }; if (pth.matrix) { pt = transformPoint(out.x, out.y, pth.imatrix); out.x = pt.x; out.y = pt.y; } var currentZoom = editorContext_$1.getCurrentZoom(); out.x /= currentZoom; out.y /= currentZoom; return out; }; /** * Requires prior call to `setUiStrings` if `xlink:title` * to be set on the grip. * @function module:path.addPointGrip * @param {Integer} index * @param {Integer} x * @param {Integer} y * @returns {SVGCircleElement} */ var addPointGrip = function addPointGrip(index, x, y) { // create the container of all the point grips var pointGripContainer = getGripContainer(); var pointGrip = getElem('pathpointgrip_' + index); // create it if (!pointGrip) { pointGrip = document.createElementNS(NS.SVG, 'circle'); var atts = { id: 'pathpointgrip_' + index, display: 'none', r: 4, fill: '#0FF', stroke: '#00F', 'stroke-width': 2, cursor: 'move', style: 'pointer-events:all' }; if ('pathNodeTooltip' in uiStrings) { // May be empty if running path.js without svg-editor atts['xlink:title'] = uiStrings.pathNodeTooltip; } assignAttributes(pointGrip, atts); pointGrip = pointGripContainer.appendChild(pointGrip); var grip = $$4('#pathpointgrip_' + index); grip.dblclick(function () { if (path$1) { path$1.setSegType(); } }); } if (x && y) { // set up the point grip element and display it assignAttributes(pointGrip, { cx: x, cy: y, display: 'inline' }); } return pointGrip; }; /** * @function module:path.getGripContainer * @returns {Element} */ var getGripContainer = function getGripContainer() { var c = getElem('pathpointgrip_container'); if (!c) { var parentElement = getElem('selectorParentGroup'); c = parentElement.appendChild(document.createElementNS(NS.SVG, 'g')); c.id = 'pathpointgrip_container'; } return c; }; /** * Requires prior call to `setUiStrings` if `xlink:title` * to be set on the grip. * @function module:path.addCtrlGrip * @param {string} id * @returns {SVGCircleElement} */ var addCtrlGrip = function addCtrlGrip(id) { var pointGrip = getElem('ctrlpointgrip_' + id); if (pointGrip) { return pointGrip; } pointGrip = document.createElementNS(NS.SVG, 'circle'); var atts = { id: 'ctrlpointgrip_' + id, display: 'none', r: 4, fill: '#0FF', stroke: '#55F', 'stroke-width': 1, cursor: 'move', style: 'pointer-events:all' }; if ('pathCtrlPtTooltip' in uiStrings) { // May be empty if running path.js without svg-editor atts['xlink:title'] = uiStrings.pathCtrlPtTooltip; } assignAttributes(pointGrip, atts); getGripContainer().append(pointGrip); return pointGrip; }; /** * @function module:path.getCtrlLine * @param {string} id * @returns {SVGLineElement} */ var getCtrlLine = function getCtrlLine(id) { var ctrlLine = getElem('ctrlLine_' + id); if (ctrlLine) { return ctrlLine; } ctrlLine = document.createElementNS(NS.SVG, 'line'); assignAttributes(ctrlLine, { id: 'ctrlLine_' + id, stroke: '#555', 'stroke-width': 1, style: 'pointer-events:none' }); getGripContainer().append(ctrlLine); return ctrlLine; }; /** * @function module:path.getPointGrip * @param {Segment} seg * @param {boolean} update * @returns {SVGCircleElement} */ var getPointGrip = function getPointGrip(seg, update) { var index = seg.index; var pointGrip = addPointGrip(index); if (update) { var pt = getGripPt(seg); assignAttributes(pointGrip, { cx: pt.x, cy: pt.y, display: 'inline' }); } return pointGrip; }; /** * @function module:path.getControlPoints * @param {Segment} seg * @returns {PlainObject<string, SVGLineElement|SVGCircleElement>} */ var getControlPoints = function getControlPoints(seg) { var item = seg.item, index = seg.index; if (!('x1' in item) || !('x2' in item)) { return null; } var cpt = {}; /* const pointGripContainer = */ getGripContainer(); // Note that this is intentionally not seg.prev.item var prev = path$1.segs[index - 1].item; var segItems = [prev, item]; for (var i = 1; i < 3; i++) { var id = index + 'c' + i; var ctrlLine = cpt['c' + i + '_line'] = getCtrlLine(id); var pt = getGripPt(seg, { x: item['x' + i], y: item['y' + i] }); var gpt = getGripPt(seg, { x: segItems[i - 1].x, y: segItems[i - 1].y }); assignAttributes(ctrlLine, { x1: pt.x, y1: pt.y, x2: gpt.x, y2: gpt.y, display: 'inline' }); cpt['c' + i + '_line'] = ctrlLine; // create it var pointGrip = cpt['c' + i] = addCtrlGrip(id); assignAttributes(pointGrip, { cx: pt.x, cy: pt.y, display: 'inline' }); cpt['c' + i] = pointGrip; } return cpt; }; /** * This replaces the segment at the given index. Type is given as number. * @function module:path.replacePathSeg * @param {Integer} type Possible values set during {@link module:path.init} * @param {Integer} index * @param {ArgumentsArray} pts * @param {SVGPathElement} elem * @returns {void} */ var replacePathSeg = function replacePathSeg(type, index, pts, elem) { var pth = elem || path$1.elem; var func = 'createSVGPathSeg' + pathFuncs[type]; var seg = pth[func].apply(pth, _toConsumableArray(pts)); if (supportsPathReplaceItem()) { pth.pathSegList.replaceItem(seg, index); } else { var segList = pth.pathSegList; var len = segList.numberOfItems; var arr = []; for (var i = 0; i < len; i++) { var curSeg = segList.getItem(i); arr.push(curSeg); } segList.clear(); for (var _i2 = 0; _i2 < len; _i2++) { if (_i2 === index) { segList.appendItem(seg); } else { segList.appendItem(arr[_i2]); } } } }; /** * @function module:path.getSegSelector * @param {Segment} seg * @param {boolean} update * @returns {SVGPathElement} */ var getSegSelector = function getSegSelector(seg, update) { var index = seg.index; var segLine = getElem('segline_' + index); if (!segLine) { var pointGripContainer = getGripContainer(); // create segline segLine = document.createElementNS(NS.SVG, 'path'); assignAttributes(segLine, { id: 'segline_' + index, display: 'none', fill: 'none', stroke: '#0FF', 'stroke-width': 2, style: 'pointer-events:none', d: 'M0,0 0,0' }); pointGripContainer.append(segLine); } if (update) { var prev = seg.prev; if (!prev) { segLine.setAttribute('display', 'none'); return segLine; } var pt = getGripPt(prev); // Set start point replacePathSeg(2, 0, [pt.x, pt.y], segLine); var pts = ptObjToArr(seg.type, seg.item); // , true); for (var i = 0; i < pts.length; i += 2) { var point = getGripPt(seg, { x: pts[i], y: pts[i + 1] }); pts[i] = point.x; pts[i + 1] = point.y; } replacePathSeg(seg.type, 1, pts, segLine); } return segLine; }; /** * @typedef {PlainObject} Point * @property {Integer} x The x value * @property {Integer} y The y value */ /** * Takes three points and creates a smoother line based on them. * @function module:path.smoothControlPoints * @param {Point} ct1 - Object with x and y values (first control point) * @param {Point} ct2 - Object with x and y values (second control point) * @param {Point} pt - Object with x and y values (third point) * @returns {Point[]} Array of two "smoothed" point objects */ var smoothControlPoints = function smoothControlPoints(ct1, ct2, pt) { // each point must not be the origin var x1 = ct1.x - pt.x, y1 = ct1.y - pt.y, x2 = ct2.x - pt.x, y2 = ct2.y - pt.y; if ((x1 !== 0 || y1 !== 0) && (x2 !== 0 || y2 !== 0)) { var r1 = Math.sqrt(x1 * x1 + y1 * y1), r2 = Math.sqrt(x2 * x2 + y2 * y2), nct1 = editorContext_$1.getSVGRoot().createSVGPoint(), nct2 = editorContext_$1.getSVGRoot().createSVGPoint(); var anglea = Math.atan2(y1, x1), angleb = Math.atan2(y2, x2); if (anglea < 0) { anglea += 2 * Math.PI; } if (angleb < 0) { angleb += 2 * Math.PI; } var angleBetween = Math.abs(anglea - angleb), angleDiff = Math.abs(Math.PI - angleBetween) / 2; var newAnglea, newAngleb; if (anglea - angleb > 0) { newAnglea = angleBetween < Math.PI ? anglea + angleDiff : anglea - angleDiff; newAngleb = angleBetween < Math.PI ? angleb - angleDiff : angleb + angleDiff; } else { newAnglea = angleBetween < Math.PI ? anglea - angleDiff : anglea + angleDiff; newAngleb = angleBetween < Math.PI ? angleb + angleDiff : angleb - angleDiff; } // rotate the points nct1.x = r1 * Math.cos(newAnglea) + pt.x; nct1.y = r1 * Math.sin(newAnglea) + pt.y; nct2.x = r2 * Math.cos(newAngleb) + pt.x; nct2.y = r2 * Math.sin(newAngleb) + pt.y; return [nct1, nct2]; } return undefined; }; /** * */ var Segment = /*#__PURE__*/function () { /** * @param {Integer} index * @param {SVGPathSeg} item * @todo Is `item` be more constrained here? */ function Segment(index, item) { _classCallCheck(this, Segment); this.selected = false; this.index = index; this.item = item; this.type = item.pathSegType; this.ctrlpts = []; this.ptgrip = null; this.segsel = null; } /** * @param {boolean} y * @returns {void} */ _createClass(Segment, [{ key: "showCtrlPts", value: function showCtrlPts(y) { for (var i in this.ctrlpts) { if ({}.hasOwnProperty.call(this.ctrlpts, i)) { this.ctrlpts[i].setAttribute('display', y ? 'inline' : 'none'); } } } /** * @param {boolean} y * @returns {void} */ }, { key: "selectCtrls", value: function selectCtrls(y) { $$4('#ctrlpointgrip_' + this.index + 'c1, #ctrlpointgrip_' + this.index + 'c2').attr('fill', y ? '#0FF' : '#EEE'); } /** * @param {boolean} y * @returns {void} */ }, { key: "show", value: function show(y) { if (this.ptgrip) { this.ptgrip.setAttribute('display', y ? 'inline' : 'none'); this.segsel.setAttribute('display', y ? 'inline' : 'none'); // Show/hide all control points if available this.showCtrlPts(y); } } /** * @param {boolean} y * @returns {void} */ }, { key: "select", value: function select(y) { if (this.ptgrip) { this.ptgrip.setAttribute('stroke', y ? '#0FF' : '#00F'); this.segsel.setAttribute('display', y ? 'inline' : 'none'); if (this.ctrlpts) { this.selectCtrls(y); } this.selected = y; } } /** * @returns {void} */ }, { key: "addGrip", value: function addGrip() { this.ptgrip = getPointGrip(this, true); this.ctrlpts = getControlPoints(this); // , true); this.segsel = getSegSelector(this, true); } /** * @param {boolean} full * @returns {void} */ }, { key: "update", value: function update(full) { if (this.ptgrip) { var pt = getGripPt(this); assignAttributes(this.ptgrip, { cx: pt.x, cy: pt.y }); getSegSelector(this, true); if (this.ctrlpts) { if (full) { this.item = path$1.elem.pathSegList.getItem(this.index); this.type = this.item.pathSegType; } getControlPoints(this); } // this.segsel.setAttribute('display', y ? 'inline' : 'none'); } } /** * @param {Integer} dx * @param {Integer} dy * @returns {void} */ }, { key: "move", value: function move(dx, dy) { var item = this.item; var curPts = this.ctrlpts ? [item.x += dx, item.y += dy, item.x1, item.y1, item.x2 += dx, item.y2 += dy] : [item.x += dx, item.y += dy]; replacePathSeg(this.type, this.index, // type 10 means ARC this.type === 10 ? ptObjToArr(this.type, item) : curPts); if (this.next && this.next.ctrlpts) { var next = this.next.item; var nextPts = [next.x, next.y, next.x1 += dx, next.y1 += dy, next.x2, next.y2]; replacePathSeg(this.next.type, this.next.index, nextPts); } if (this.mate) { // The last point of a closed subpath has a 'mate', // which is the 'M' segment of the subpath var itm = this.mate.item; var pts = [itm.x += dx, itm.y += dy]; replacePathSeg(this.mate.type, this.mate.index, pts); // Has no grip, so does not need 'updating'? } this.update(true); if (this.next) { this.next.update(true); } } /** * @param {Integer} num * @returns {void} */ }, { key: "setLinked", value: function setLinked(num) { var seg, anum, pt; if (num === 2) { anum = 1; seg = this.next; if (!seg) { return; } pt = this.item; } else { anum = 2; seg = this.prev; if (!seg) { return; } pt = seg.item; } var _seg = seg, item = _seg.item; item['x' + anum] = pt.x + (pt.x - this.item['x' + num]); item['y' + anum] = pt.y + (pt.y - this.item['y' + num]); var pts = [item.x, item.y, item.x1, item.y1, item.x2, item.y2]; replacePathSeg(seg.type, seg.index, pts); seg.update(true); } /** * @param {Integer} num * @param {Integer} dx * @param {Integer} dy * @returns {void} */ }, { key: "moveCtrl", value: function moveCtrl(num, dx, dy) { var item = this.item; item['x' + num] += dx; item['y' + num] += dy; var pts = [item.x, item.y, item.x1, item.y1, item.x2, item.y2]; replacePathSeg(this.type, this.index, pts); this.update(true); } /** * @param {Integer} newType Possible values set during {@link module:path.init} * @param {ArgumentsArray} pts * @returns {void} */ }, { key: "setType", value: function setType(newType, pts) { replacePathSeg(newType, this.index, pts); this.type = newType; this.item = path$1.elem.pathSegList.getItem(this.index); this.showCtrlPts(newType === 6); this.ctrlpts = getControlPoints(this); this.update(true); } }]); return Segment; }(); /** * */ var Path$1 = /*#__PURE__*/function () { /** * @param {SVGPathElement} elem * @throws {Error} If constructed without a path element */ function Path(elem) { _classCallCheck(this, Path); if (!elem || elem.tagName !== 'path') { throw new Error('svgedit.path.Path constructed without a <path> element'); } this.elem = elem; this.segs = []; this.selected_pts = []; path$1 = this; this.init(); } /** * Reset path data. * @returns {module:path.Path} */ _createClass(Path, [{ key: "init", value: function init() { // Hide all grips, etc // fixed, needed to work on all found elements, not just first $$4(getGripContainer()).find('*').each(function () { $$4(this).attr('display', 'none'); }); var segList = this.elem.pathSegList; var len = segList.numberOfItems; this.segs = []; this.selected_pts = []; this.first_seg = null; // Set up segs array for (var i = 0; i < len; i++) { var item = segList.getItem(i); var segment = new Segment(i, item); segment.path = this; this.segs.push(segment); } var segs = this.segs; var startI = null; for (var _i3 = 0; _i3 < len; _i3++) { var seg = segs[_i3]; var nextSeg = _i3 + 1 >= len ? null : segs[_i3 + 1]; var prevSeg = _i3 - 1 < 0 ? null : segs[_i3 - 1]; if (seg.type === 2) { if (prevSeg && prevSeg.type !== 1) { // New sub-path, last one is open, // so add a grip to last sub-path's first point var startSeg = segs[startI]; startSeg.next = segs[startI + 1]; startSeg.next.prev = startSeg; startSeg.addGrip(); } // Remember that this is a starter seg startI = _i3; } else if (nextSeg && nextSeg.type === 1) { // This is the last real segment of a closed sub-path // Next is first seg after "M" seg.next = segs[startI + 1]; // First seg after "M"'s prev is this seg.next.prev = seg; seg.mate = segs[startI]; seg.addGrip(); if (isNullish(this.first_seg)) { this.first_seg = seg; } } else if (!nextSeg) { if (seg.type !== 1) { // Last seg, doesn't close so add a grip // to last sub-path's first point var _startSeg = segs[startI]; _startSeg.next = segs[startI + 1]; _startSeg.next.prev = _startSeg; _startSeg.addGrip(); seg.addGrip(); if (!this.first_seg) { // Open path, so set first as real first and add grip this.first_seg = segs[startI]; } } } else if (seg.type !== 1) { // Regular segment, so add grip and its "next" seg.addGrip(); // Don't set its "next" if it's an "M" if (nextSeg && nextSeg.type !== 2) { seg.next = nextSeg; seg.next.prev = seg; } } } return this; } /** * @callback module:path.PathEachSegCallback * @this module:path.Segment * @param {Integer} i The index of the seg being iterated * @returns {boolean|void} Will stop execution of `eachSeg` if returns `false` */ /** * @param {module:path.PathEachSegCallback} fn * @returns {void} */ }, { key: "eachSeg", value: function eachSeg(fn) { var len = this.segs.length; for (var i = 0; i < len; i++) { var ret = fn.call(this.segs[i], i); if (ret === false) { break; } } } /** * @param {Integer} index * @returns {void} */ }, { key: "addSeg", value: function addSeg(index) { // Adds a new segment var seg = this.segs[index]; if (!seg.prev) { return; } var prev = seg.prev; var newseg, newX, newY; switch (seg.item.pathSegType) { case 4: { newX = (seg.item.x + prev.item.x) / 2; newY = (seg.item.y + prev.item.y) / 2; newseg = this.elem.createSVGPathSegLinetoAbs(newX, newY); break; } case 6: { // make it a curved segment to preserve the shape (WRS) // https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm#Geometric_interpretation var p0x = (prev.item.x + seg.item.x1) / 2; var p1x = (seg.item.x1 + seg.item.x2) / 2; var p2x = (seg.item.x2 + seg.item.x) / 2; var p01x = (p0x + p1x) / 2; var p12x = (p1x + p2x) / 2; newX = (p01x + p12x) / 2; var p0y = (prev.item.y + seg.item.y1) / 2; var p1y = (seg.item.y1 + seg.item.y2) / 2; var p2y = (seg.item.y2 + seg.item.y) / 2; var p01y = (p0y + p1y) / 2; var p12y = (p1y + p2y) / 2; newY = (p01y + p12y) / 2; newseg = this.elem.createSVGPathSegCurvetoCubicAbs(newX, newY, p0x, p0y, p01x, p01y); var pts = [seg.item.x, seg.item.y, p12x, p12y, p2x, p2y]; replacePathSeg(seg.type, index, pts); break; } } insertItemBefore(this.elem, newseg, index); } /** * @param {Integer} index * @returns {void} */ }, { key: "deleteSeg", value: function deleteSeg(index) { var seg = this.segs[index]; var list = this.elem.pathSegList; seg.show(false); var next = seg.next; if (seg.mate) { // Make the next point be the "M" point var pt = [next.item.x, next.item.y]; replacePathSeg(2, next.index, pt); // Reposition last node replacePathSeg(4, seg.index, pt); list.removeItem(seg.mate.index); } else if (!seg.prev) { // First node of open path, make next point the M // const {item} = seg; var _pt = [next.item.x, next.item.y]; replacePathSeg(2, seg.next.index, _pt); list.removeItem(index); } else { list.removeItem(index); } } /** * @param {Integer} index * @returns {void} */ }, { key: "removePtFromSelection", value: function removePtFromSelection(index) { var pos = this.selected_pts.indexOf(index); if (pos === -1) { return; } this.segs[index].select(false); this.selected_pts.splice(pos, 1); } /** * @returns {void} */ }, { key: "clearSelection", value: function clearSelection() { this.eachSeg(function () { // 'this' is the segment here this.select(false); }); this.selected_pts = []; } /** * @returns {void} */ }, { key: "storeD", value: function storeD() { this.last_d = this.elem.getAttribute('d'); } /** * @param {Integer} y * @returns {Path} */ }, { key: "show", value: function show(y) { // Shows this path's segment grips this.eachSeg(function () { // 'this' is the segment here this.show(y); }); if (y) { this.selectPt(this.first_seg.index); } return this; } /** * Move selected points. * @param {Integer} dx * @param {Integer} dy * @returns {void} */ }, { key: "movePts", value: function movePts(dx, dy) { var i = this.selected_pts.length; while (i--) { var seg = this.segs[this.selected_pts[i]]; seg.move(dx, dy); } } /** * @param {Integer} dx * @param {Integer} dy * @returns {void} */ }, { key: "moveCtrl", value: function moveCtrl(dx, dy) { var seg = this.segs[this.selected_pts[0]]; seg.moveCtrl(this.dragctrl, dx, dy); if (linkControlPts) { seg.setLinked(this.dragctrl); } } /** * @param {?Integer} newType See {@link https://www.w3.org/TR/SVG/single-page.html#paths-InterfaceSVGPathSeg} * @returns {void} */ }, { key: "setSegType", value: function setSegType(newType) { this.storeD(); var i = this.selected_pts.length; var text; while (i--) { var selPt = this.selected_pts[i]; // Selected seg var cur = this.segs[selPt]; var prev = cur.prev; if (!prev) { continue; } if (!newType) { // double-click, so just toggle text = 'Toggle Path Segment Type'; // Toggle segment to curve/straight line var oldType = cur.type; newType = oldType === 6 ? 4 : 6; } newType = Number(newType); var curX = cur.item.x; var curY = cur.item.y; var prevX = prev.item.x; var prevY = prev.item.y; var points = void 0; switch (newType) { case 6: { if (cur.olditem) { var old = cur.olditem; points = [curX, curY, old.x1, old.y1, old.x2, old.y2]; } else { var diffX = curX - prevX; var diffY = curY - prevY; // get control points from straight line segment /* const ct1x = (prevX + (diffY/2)); const ct1y = (prevY - (diffX/2)); const ct2x = (curX + (diffY/2)); const ct2y = (curY - (diffX/2)); */ // create control points on the line to preserve the shape (WRS) var ct1x = prevX + diffX / 3; var ct1y = prevY + diffY / 3; var ct2x = curX - diffX / 3; var ct2y = curY - diffY / 3; points = [curX, curY, ct1x, ct1y, ct2x, ct2y]; } break; } case 4: { points = [curX, curY]; // Store original prevve segment nums cur.olditem = cur.item; break; } } cur.setType(newType, points); } path$1.endChanges(text); } /** * @param {Integer} pt * @param {Integer} ctrlNum * @returns {void} */ }, { key: "selectPt", value: function selectPt(pt, ctrlNum) { this.clearSelection(); if (isNullish(pt)) { this.eachSeg(function (i) { // 'this' is the segment here. if (this.prev) { pt = i; } }); } this.addPtsToSelection(pt); if (ctrlNum) { this.dragctrl = ctrlNum; if (linkControlPts) { this.segs[pt].setLinked(ctrlNum); } } } /** * Update position of all points. * @returns {Path} */ }, { key: "update", value: function update() { var elem = this.elem; if (getRotationAngle(elem)) { this.matrix = getMatrix(elem); this.imatrix = this.matrix.inverse(); } else { this.matrix = null; this.imatrix = null; } this.eachSeg(function (i) { this.item = elem.pathSegList.getItem(i); this.update(); }); return this; } /** * @param {string} text * @returns {void} */ }, { key: "endChanges", value: function endChanges(text) { if (isWebkit()) { editorContext_$1.resetD(this.elem); } var cmd = new ChangeElementCommand(this.elem, { d: this.last_d }, text); editorContext_$1.endChanges({ cmd: cmd, elem: this.elem }); } /** * @param {Integer|Integer[]} indexes * @returns {void} */ }, { key: "addPtsToSelection", value: function addPtsToSelection(indexes) { var _this = this; if (!Array.isArray(indexes)) { indexes = [indexes]; } indexes.forEach(function (index) { var seg = _this.segs[index]; if (seg.ptgrip) { if (!_this.selected_pts.includes(index) && index >= 0) { _this.selected_pts.push(index); } } }); this.selected_pts.sort(); var i = this.selected_pts.length; var grips = []; grips.length = i; // Loop through points to be selected and highlight each while (i--) { var pt = this.selected_pts[i]; var seg = this.segs[pt]; seg.select(true); grips[i] = seg.ptgrip; } var closedSubpath = Path.subpathIsClosed(this.selected_pts[0]); editorContext_$1.addPtsToSelection({ grips: grips, closedSubpath: closedSubpath }); } // STATIC /** * @param {Integer} index * @returns {boolean} */ }], [{ key: "subpathIsClosed", value: function subpathIsClosed(index) { var clsd = false; // Check if subpath is already open path$1.eachSeg(function (i) { if (i <= index) { return true; } if (this.type === 2) { // Found M first, so open return false; } if (this.type === 1) { // Found Z first, so closed clsd = true; return false; } return true; }); return clsd; } }]); return Path; }(); /** * @function module:path.getPath_ * @param {SVGPathElement} elem * @returns {module:path.Path} */ var getPath_ = function getPath_(elem) { var p = pathData[elem.id]; if (!p) { p = pathData[elem.id] = new Path$1(elem); } return p; }; /** * @function module:path.removePath_ * @param {string} id * @returns {void} */ var removePath_ = function removePath_(id) { if (id in pathData) { delete pathData[id]; } }; var newcx, newcy, oldcx, oldcy, angle; var getRotVals = function getRotVals(x, y) { var dx = x - oldcx; var dy = y - oldcy; // rotate the point around the old center var r = Math.sqrt(dx * dx + dy * dy); var theta = Math.atan2(dy, dx) + angle; dx = r * Math.cos(theta) + oldcx; dy = r * Math.sin(theta) + oldcy; // dx,dy should now hold the actual coordinates of each // point after being rotated // now we want to rotate them around the new center in the reverse direction dx -= newcx; dy -= newcy; r = Math.sqrt(dx * dx + dy * dy); theta = Math.atan2(dy, dx) - angle; return { x: r * Math.cos(theta) + newcx, y: r * Math.sin(theta) + newcy }; }; // If the path was rotated, we must now pay the piper: // Every path point must be rotated into the rotated coordinate system of // its old center, then determine the new center, then rotate it back // This is because we want the path to remember its rotation /** * @function module:path.recalcRotatedPath * @todo This is still using ye olde transform methods, can probably * be optimized or even taken care of by `recalculateDimensions` * @returns {void} */ var recalcRotatedPath = function recalcRotatedPath() { var currentPath = path$1.elem; angle = getRotationAngle(currentPath, true); if (!angle) { return; } // selectedBBoxes[0] = path.oldbbox; var oldbox = path$1.oldbbox; // selectedBBoxes[0], oldcx = oldbox.x + oldbox.width / 2; oldcy = oldbox.y + oldbox.height / 2; var box = getBBox(currentPath); newcx = box.x + box.width / 2; newcy = box.y + box.height / 2; // un-rotate the new center to the proper position var dx = newcx - oldcx, dy = newcy - oldcy, r = Math.sqrt(dx * dx + dy * dy), theta = Math.atan2(dy, dx) + angle; newcx = r * Math.cos(theta) + oldcx; newcy = r * Math.sin(theta) + oldcy; var list = currentPath.pathSegList; var i = list.numberOfItems; while (i) { i -= 1; var seg = list.getItem(i), type = seg.pathSegType; if (type === 1) { continue; } var rvals = getRotVals(seg.x, seg.y), points = [rvals.x, rvals.y]; if (!isNullish(seg.x1) && !isNullish(seg.x2)) { var cVals1 = getRotVals(seg.x1, seg.y1); var cVals2 = getRotVals(seg.x2, seg.y2); points.splice(points.length, 0, cVals1.x, cVals1.y, cVals2.x, cVals2.y); } replacePathSeg(type, i, points); } // loop for each point /* box = */ getBBox(currentPath); // selectedBBoxes[0].x = box.x; selectedBBoxes[0].y = box.y; // selectedBBoxes[0].width = box.width; selectedBBoxes[0].height = box.height; // now we must set the new transform to be rotated around the new center var Rnc = editorContext_$1.getSVGRoot().createSVGTransform(), tlist = getTransformList(currentPath); Rnc.setRotate(angle * 180.0 / Math.PI, newcx, newcy); tlist.replaceItem(Rnc, 0); }; // ==================================== // Public API starts here /** * @function module:path.clearData * @returns {void} */ var clearData = function clearData() { pathData = {}; }; // Making public for mocking /** * @function module:path.reorientGrads * @param {Element} elem * @param {SVGMatrix} m * @returns {void} */ var reorientGrads = function reorientGrads(elem, m) { var bb = getBBox(elem); for (var i = 0; i < 2; i++) { var type = i === 0 ? 'fill' : 'stroke'; var attrVal = elem.getAttribute(type); if (attrVal && attrVal.startsWith('url(')) { var grad = getRefElem(attrVal); if (grad.tagName === 'linearGradient') { var x1 = grad.getAttribute('x1') || 0; var y1 = grad.getAttribute('y1') || 0; var x2 = grad.getAttribute('x2') || 1; var y2 = grad.getAttribute('y2') || 0; // Convert to USOU points x1 = bb.width * x1 + bb.x; y1 = bb.height * y1 + bb.y; x2 = bb.width * x2 + bb.x; y2 = bb.height * y2 + bb.y; // Transform those points var pt1 = transformPoint(x1, y1, m); var pt2 = transformPoint(x2, y2, m); // Convert back to BB points var gCoords = { x1: (pt1.x - bb.x) / bb.width, y1: (pt1.y - bb.y) / bb.height, x2: (pt2.x - bb.x) / bb.width, y2: (pt2.y - bb.y) / bb.height }; var newgrad = grad.cloneNode(true); $$4(newgrad).attr(gCoords); newgrad.id = editorContext_$1.getNextId(); findDefs().append(newgrad); elem.setAttribute(type, 'url(#' + newgrad.id + ')'); } } } }; /** * This is how we map paths to our preferred relative segment types. * @name module:path.pathMap * @type {GenericArray} */ var pathMap = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a', 'H', 'h', 'V', 'v', 'S', 's', 'T', 't']; /** * Convert a path to one with only absolute or relative values. * @todo move to pathActions.js * @function module:path.convertPath * @param {SVGPathElement} pth - the path to convert * @param {boolean} toRel - true of convert to relative * @returns {string} */ var convertPath = function convertPath(pth, toRel) { var pathSegList = pth.pathSegList; var len = pathSegList.numberOfItems; var curx = 0, cury = 0; var d = ''; var lastM = null; for (var i = 0; i < len; ++i) { var seg = pathSegList.getItem(i); // if these properties are not in the segment, set them to zero var x = seg.x || 0, y = seg.y || 0, x1 = seg.x1 || 0, y1 = seg.y1 || 0, x2 = seg.x2 || 0, y2 = seg.y2 || 0; var type = seg.pathSegType; var letter = pathMap[type][toRel ? 'toLowerCase' : 'toUpperCase'](); switch (type) { case 1: // z,Z closepath (Z/z) d += 'z'; if (lastM && !toRel) { curx = lastM[0]; cury = lastM[1]; } break; case 12: // absolute horizontal line (H) x -= curx; // Fallthrough case 13: // relative horizontal line (h) if (toRel) { y = 0; curx += x; letter = 'l'; } else { y = cury; x += curx; curx = x; letter = 'L'; } // Convert to "line" for easier editing d += pathDSegment(letter, [[x, y]]); break; case 14: // absolute vertical line (V) y -= cury; // Fallthrough case 15: // relative vertical line (v) if (toRel) { x = 0; cury += y; letter = 'l'; } else { x = curx; y += cury; cury = y; letter = 'L'; } // Convert to "line" for easier editing d += pathDSegment(letter, [[x, y]]); break; case 2: // absolute move (M) case 4: // absolute line (L) case 18: // absolute smooth quad (T) x -= curx; y -= cury; // Fallthrough case 5: // relative line (l) case 3: // relative move (m) case 19: // relative smooth quad (t) if (toRel) { curx += x; cury += y; } else { x += curx; y += cury; curx = x; cury = y; } if (type === 2 || type === 3) { lastM = [curx, cury]; } d += pathDSegment(letter, [[x, y]]); break; case 6: // absolute cubic (C) x -= curx; x1 -= curx; x2 -= curx; y -= cury; y1 -= cury; y2 -= cury; // Fallthrough case 7: // relative cubic (c) if (toRel) { curx += x; cury += y; } else { x += curx; x1 += curx; x2 += curx; y += cury; y1 += cury; y2 += cury; curx = x; cury = y; } d += pathDSegment(letter, [[x1, y1], [x2, y2], [x, y]]); break; case 8: // absolute quad (Q) x -= curx; x1 -= curx; y -= cury; y1 -= cury; // Fallthrough case 9: // relative quad (q) if (toRel) { curx += x; cury += y; } else { x += curx; x1 += curx; y += cury; y1 += cury; curx = x; cury = y; } d += pathDSegment(letter, [[x1, y1], [x, y]]); break; // eslint-disable-next-line sonarjs/no-duplicated-branches case 10: // absolute elliptical arc (A) x -= curx; y -= cury; // Fallthrough case 11: // relative elliptical arc (a) if (toRel) { curx += x; cury += y; } else { x += curx; y += cury; curx = x; cury = y; } d += pathDSegment(letter, [[seg.r1, seg.r2]], [seg.angle, seg.largeArcFlag ? 1 : 0, seg.sweepFlag ? 1 : 0], [x, y]); break; case 16: // absolute smooth cubic (S) x -= curx; x2 -= curx; y -= cury; y2 -= cury; // Fallthrough case 17: // relative smooth cubic (s) if (toRel) { curx += x; cury += y; } else { x += curx; x2 += curx; y += cury; y2 += cury; curx = x; cury = y; } d += pathDSegment(letter, [[x2, y2], [x, y]]); break; } // switch on path segment type } // for each segment return d; }; /** * TODO: refactor callers in `convertPath` to use `getPathDFromSegments` instead of this function. * Legacy code refactored from `svgcanvas.pathActions.convertPath`. * @param {string} letter - path segment command (letter in potentially either case from {@link module:path.pathMap}; see [SVGPathSeg#pathSegTypeAsLetter]{@link https://www.w3.org/TR/SVG/single-page.html#paths-__svg__SVGPathSeg__pathSegTypeAsLetter}) * @param {GenericArray<GenericArray<Integer>>} points - x,y points * @param {GenericArray<GenericArray<Integer>>} [morePoints] - x,y points * @param {Integer[]} [lastPoint] - x,y point * @returns {string} */ function pathDSegment(letter, points, morePoints, lastPoint) { $$4.each(points, function (i, pnt) { points[i] = shortFloat(pnt); }); var segment = letter + points.join(' '); if (morePoints) { segment += ' ' + morePoints.join(' '); } if (lastPoint) { segment += ' ' + shortFloat(lastPoint); } return segment; } /* eslint-disable jsdoc/require-property */ /** * Group: Path edit functions. * Functions relating to editing path elements. * @namespace {PlainObject} pathActions * @memberof module:path */ var pathActions = function () { /* eslint-enable jsdoc/require-property */ var subpath = false; var newPoint, firstCtrl; var currentPath = null; var hasMoved = false; // No `editorContext_` yet but should be ok as is `null` by default // editorContext_.setDrawnPath(null); /** * This function converts a polyline (created by the fh_path tool) into * a path element and coverts every three line segments into a single bezier * curve in an attempt to smooth out the free-hand. * @function smoothPolylineIntoPath * @param {Element} element * @returns {Element} */ var smoothPolylineIntoPath = function smoothPolylineIntoPath(element) { var i; var _element = element, points = _element.points; var N = points.numberOfItems; if (N >= 4) { // loop through every 3 points and convert to a cubic bezier curve segment // // NOTE: this is cheating, it means that every 3 points has the potential to // be a corner instead of treating each point in an equal manner. In general, // this technique does not look that good. // // I am open to better ideas! // // Reading: // - http://www.efg2.com/Lab/Graphics/Jean-YvesQueinecBezierCurves.htm // - https://www.codeproject.com/KB/graphics/BezierSpline.aspx?msg=2956963 // - https://www.ian-ko.com/ET_GeoWizards/UserGuide/smooth.htm // - https://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-der.html var curpos = points.getItem(0), prevCtlPt = null; var d = []; d.push(['M', curpos.x, ',', curpos.y, ' C'].join('')); for (i = 1; i <= N - 4; i += 3) { var ct1 = points.getItem(i); var ct2 = points.getItem(i + 1); var end = points.getItem(i + 2); // if the previous segment had a control point, we want to smooth out // the control points on both sides if (prevCtlPt) { var newpts = smoothControlPoints(prevCtlPt, ct1, curpos); if (newpts && newpts.length === 2) { var prevArr = d[d.length - 1].split(','); prevArr[2] = newpts[0].x; prevArr[3] = newpts[0].y; d[d.length - 1] = prevArr.join(','); ct1 = newpts[1]; } } d.push([ct1.x, ct1.y, ct2.x, ct2.y, end.x, end.y].join(',')); curpos = end; prevCtlPt = ct2; } // handle remaining line segments d.push('L'); while (i < N) { var pt = points.getItem(i); d.push([pt.x, pt.y].join(',')); i++; } d = d.join(' '); // create new path element element = editorContext_$1.addSVGElementFromJson({ element: 'path', curStyles: true, attr: { id: editorContext_$1.getId(), d: d, fill: 'none' } }); // No need to call "changed", as this is already done under mouseUp } return element; }; return ( /** @lends module:path.pathActions */ { /** * @param {MouseEvent} evt * @param {Element} mouseTarget * @param {Float} startX * @param {Float} startY * @returns {boolean|void} */ mouseDown: function mouseDown(evt, mouseTarget, startX, startY) { var id; if (editorContext_$1.getCurrentMode() === 'path') { var mouseX = startX; // Was this meant to work with the other `mouseX`? (was defined globally so adding `let` to at least avoid a global) var mouseY = startY; // Was this meant to work with the other `mouseY`? (was defined globally so adding `let` to at least avoid a global) var currentZoom = editorContext_$1.getCurrentZoom(); var x = mouseX / currentZoom, y = mouseY / currentZoom, stretchy = getElem('path_stretch_line'); newPoint = [x, y]; if (editorContext_$1.getGridSnapping()) { x = snapToGrid(x); y = snapToGrid(y); mouseX = snapToGrid(mouseX); mouseY = snapToGrid(mouseY); } if (!stretchy) { stretchy = document.createElementNS(NS.SVG, 'path'); assignAttributes(stretchy, { id: 'path_stretch_line', stroke: '#22C', 'stroke-width': '0.5', fill: 'none' }); stretchy = getElem('selectorParentGroup').appendChild(stretchy); } stretchy.setAttribute('display', 'inline'); var keep = null; var index; // if pts array is empty, create path element with M at current point var drawnPath = editorContext_$1.getDrawnPath(); if (!drawnPath) { var dAttr = 'M' + x + ',' + y + ' '; // Was this meant to work with the other `dAttr`? (was defined globally so adding `var` to at least avoid a global) /* drawnPath = */ editorContext_$1.setDrawnPath(editorContext_$1.addSVGElementFromJson({ element: 'path', curStyles: true, attr: { d: dAttr, id: editorContext_$1.getNextId(), opacity: editorContext_$1.getOpacity() / 2 } })); // set stretchy line to first point stretchy.setAttribute('d', ['M', mouseX, mouseY, mouseX, mouseY].join(' ')); index = subpath ? path$1.segs.length : 0; addPointGrip(index, mouseX, mouseY); } else { // determine if we clicked on an existing point var seglist = drawnPath.pathSegList; var i = seglist.numberOfItems; var FUZZ = 6 / currentZoom; var clickOnPoint = false; while (i) { i--; var item = seglist.getItem(i); var px = item.x, py = item.y; // found a matching point if (x >= px - FUZZ && x <= px + FUZZ && y >= py - FUZZ && y <= py + FUZZ) { clickOnPoint = true; break; } } // get path element that we are in the process of creating id = editorContext_$1.getId(); // Remove previous path object if previously created removePath_(id); var newpath = getElem(id); var newseg; var sSeg; var len = seglist.numberOfItems; // if we clicked on an existing point, then we are done this path, commit it // (i, i+1) are the x,y that were clicked on if (clickOnPoint) { // if clicked on any other point but the first OR // the first point was clicked on and there are less than 3 points // then leave the path open // otherwise, close the path if (i <= 1 && len >= 2) { // Create end segment var absX = seglist.getItem(0).x; var absY = seglist.getItem(0).y; sSeg = stretchy.pathSegList.getItem(1); if (sSeg.pathSegType === 4) { newseg = drawnPath.createSVGPathSegLinetoAbs(absX, absY); } else { newseg = drawnPath.createSVGPathSegCurvetoCubicAbs(absX, absY, sSeg.x1 / currentZoom, sSeg.y1 / currentZoom, absX, absY); } var endseg = drawnPath.createSVGPathSegClosePath(); seglist.appendItem(newseg); seglist.appendItem(endseg); } else if (len < 3) { keep = false; return keep; } $$4(stretchy).remove(); // This will signal to commit the path // const element = newpath; // Other event handlers define own `element`, so this was probably not meant to interact with them or one which shares state (as there were none); I therefore adding a missing `var` to avoid a global /* drawnPath = */ editorContext_$1.setDrawnPath(null); editorContext_$1.setStarted(false); if (subpath) { if (path$1.matrix) { editorContext_$1.remapElement(newpath, {}, path$1.matrix.inverse()); } var newD = newpath.getAttribute('d'); var origD = $$4(path$1.elem).attr('d'); $$4(path$1.elem).attr('d', origD + newD); $$4(newpath).remove(); if (path$1.matrix) { recalcRotatedPath(); } init$2(); pathActions.toEditMode(path$1.elem); path$1.selectPt(); return false; } // else, create a new point, update path element } else { // Checks if current target or parents are #svgcontent if (!$$4.contains(editorContext_$1.getContainer(), editorContext_$1.getMouseTarget(evt))) { // Clicked outside canvas, so don't make point // console.log('Clicked outside canvas'); return false; } var num = drawnPath.pathSegList.numberOfItems; var last = drawnPath.pathSegList.getItem(num - 1); var lastx = last.x, lasty = last.y; if (evt.shiftKey) { var xya = snapToAngle(lastx, lasty, x, y); x = xya.x; y = xya.y; } // Use the segment defined by stretchy sSeg = stretchy.pathSegList.getItem(1); if (sSeg.pathSegType === 4) { newseg = drawnPath.createSVGPathSegLinetoAbs(editorContext_$1.round(x), editorContext_$1.round(y)); } else { newseg = drawnPath.createSVGPathSegCurvetoCubicAbs(editorContext_$1.round(x), editorContext_$1.round(y), sSeg.x1 / currentZoom, sSeg.y1 / currentZoom, sSeg.x2 / currentZoom, sSeg.y2 / currentZoom); } drawnPath.pathSegList.appendItem(newseg); x *= currentZoom; y *= currentZoom; // set stretchy line to latest point stretchy.setAttribute('d', ['M', x, y, x, y].join(' ')); index = num; if (subpath) { index += path$1.segs.length; } addPointGrip(index, x, y); } // keep = true; } return undefined; } // TODO: Make sure currentPath isn't null at this point if (!path$1) { return undefined; } path$1.storeD(); id = evt.target.id; var curPt; if (id.substr(0, 14) === 'pathpointgrip_') { // Select this point curPt = path$1.cur_pt = Number.parseInt(id.substr(14)); path$1.dragging = [startX, startY]; var seg = path$1.segs[curPt]; // only clear selection if shift is not pressed (otherwise, add // node to selection) if (!evt.shiftKey) { if (path$1.selected_pts.length <= 1 || !seg.selected) { path$1.clearSelection(); } path$1.addPtsToSelection(curPt); } else if (seg.selected) { path$1.removePtFromSelection(curPt); } else { path$1.addPtsToSelection(curPt); } } else if (id.startsWith('ctrlpointgrip_')) { path$1.dragging = [startX, startY]; var parts = id.split('_')[1].split('c'); curPt = Number(parts[0]); var ctrlNum = Number(parts[1]); path$1.selectPt(curPt, ctrlNum); } // Start selection box if (!path$1.dragging) { var rubberBox = editorContext_$1.getRubberBox(); if (isNullish(rubberBox)) { rubberBox = editorContext_$1.setRubberBox(editorContext_$1.selectorManager.getRubberBandBox()); } var currentZoom = editorContext_$1.getCurrentZoom(); assignAttributes(rubberBox, { x: startX * currentZoom, y: startY * currentZoom, width: 0, height: 0, display: 'inline' }); } return undefined; }, /** * @param {Float} mouseX * @param {Float} mouseY * @returns {void} */ mouseMove: function mouseMove(mouseX, mouseY) { var currentZoom = editorContext_$1.getCurrentZoom(); hasMoved = true; var drawnPath = editorContext_$1.getDrawnPath(); if (editorContext_$1.getCurrentMode() === 'path') { if (!drawnPath) { return; } var seglist = drawnPath.pathSegList; var index = seglist.numberOfItems - 1; if (newPoint) { // First point // if (!index) { return; } // Set control points var pointGrip1 = addCtrlGrip('1c1'); var pointGrip2 = addCtrlGrip('0c2'); // dragging pointGrip1 pointGrip1.setAttribute('cx', mouseX); pointGrip1.setAttribute('cy', mouseY); pointGrip1.setAttribute('display', 'inline'); var ptX = newPoint[0]; var ptY = newPoint[1]; // set curve // const seg = seglist.getItem(index); var curX = mouseX / currentZoom; var curY = mouseY / currentZoom; var altX = ptX + (ptX - curX); var altY = ptY + (ptY - curY); pointGrip2.setAttribute('cx', altX * currentZoom); pointGrip2.setAttribute('cy', altY * currentZoom); pointGrip2.setAttribute('display', 'inline'); var ctrlLine = getCtrlLine(1); assignAttributes(ctrlLine, { x1: mouseX, y1: mouseY, x2: altX * currentZoom, y2: altY * currentZoom, display: 'inline' }); if (index === 0) { firstCtrl = [mouseX, mouseY]; } else { var last = seglist.getItem(index - 1); var lastX = last.x; var lastY = last.y; if (last.pathSegType === 6) { lastX += lastX - last.x2; lastY += lastY - last.y2; } else if (firstCtrl) { lastX = firstCtrl[0] / currentZoom; lastY = firstCtrl[1] / currentZoom; } replacePathSeg(6, index, [ptX, ptY, lastX, lastY, altX, altY], drawnPath); } } else { var stretchy = getElem('path_stretch_line'); if (stretchy) { var prev = seglist.getItem(index); if (prev.pathSegType === 6) { var prevX = prev.x + (prev.x - prev.x2); var prevY = prev.y + (prev.y - prev.y2); replacePathSeg(6, 1, [mouseX, mouseY, prevX * currentZoom, prevY * currentZoom, mouseX, mouseY], stretchy); } else if (firstCtrl) { replacePathSeg(6, 1, [mouseX, mouseY, firstCtrl[0], firstCtrl[1], mouseX, mouseY], stretchy); } else { replacePathSeg(4, 1, [mouseX, mouseY], stretchy); } } } return; } // if we are dragging a point, let's move it if (path$1.dragging) { var pt = getPointFromGrip({ x: path$1.dragging[0], y: path$1.dragging[1] }, path$1); var mpt = getPointFromGrip({ x: mouseX, y: mouseY }, path$1); var diffX = mpt.x - pt.x; var diffY = mpt.y - pt.y; path$1.dragging = [mouseX, mouseY]; if (path$1.dragctrl) { path$1.moveCtrl(diffX, diffY); } else { path$1.movePts(diffX, diffY); } } else { path$1.selected_pts = []; path$1.eachSeg(function (i) { var seg = this; if (!seg.next && !seg.prev) { return; } // const {item} = seg; var rubberBox = editorContext_$1.getRubberBox(); var rbb = rubberBox.getBBox(); var pt = getGripPt(seg); var ptBb = { x: pt.x, y: pt.y, width: 0, height: 0 }; var sel = rectsIntersect(rbb, ptBb); this.select(sel); // Note that addPtsToSelection is not being run if (sel) { path$1.selected_pts.push(seg.index); } }); } }, /** * @typedef module:path.keepElement * @type {PlainObject} * @property {boolean} keep * @property {Element} element */ /** * @param {Event} evt * @param {Element} element * @param {Float} mouseX * @param {Float} mouseY * @returns {module:path.keepElement|void} */ mouseUp: function mouseUp(evt, element, mouseX, mouseY) { var drawnPath = editorContext_$1.getDrawnPath(); // Create mode if (editorContext_$1.getCurrentMode() === 'path') { newPoint = null; if (!drawnPath) { element = getElem(editorContext_$1.getId()); editorContext_$1.setStarted(false); firstCtrl = null; } return { keep: true, element: element }; } // Edit mode var rubberBox = editorContext_$1.getRubberBox(); if (path$1.dragging) { var lastPt = path$1.cur_pt; path$1.dragging = false; path$1.dragctrl = false; path$1.update(); if (hasMoved) { path$1.endChanges('Move path point(s)'); } if (!evt.shiftKey && !hasMoved) { path$1.selectPt(lastPt); } } else if (rubberBox && rubberBox.getAttribute('display') !== 'none') { // Done with multi-node-select rubberBox.setAttribute('display', 'none'); if (rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) { pathActions.toSelectMode(evt.target); } // else, move back to select mode } else { pathActions.toSelectMode(evt.target); } hasMoved = false; return undefined; }, /** * @param {Element} element * @returns {void} */ toEditMode: function toEditMode(element) { path$1 = getPath_(element); editorContext_$1.setCurrentMode('pathedit'); editorContext_$1.clearSelection(); path$1.show(true).update(); path$1.oldbbox = getBBox(path$1.elem); subpath = false; }, /** * @param {Element} elem * @fires module:svgcanvas.SvgCanvas#event:selected * @returns {void} */ toSelectMode: function toSelectMode(elem) { var selPath = elem === path$1.elem; editorContext_$1.setCurrentMode('select'); path$1.show(false); currentPath = false; editorContext_$1.clearSelection(); if (path$1.matrix) { // Rotated, so may need to re-calculate the center recalcRotatedPath(); } if (selPath) { editorContext_$1.call('selected', [elem]); editorContext_$1.addToSelection([elem], true); } }, /** * @param {boolean} on * @returns {void} */ addSubPath: function addSubPath(on) { if (on) { // Internally we go into "path" mode, but in the UI it will // still appear as if in "pathedit" mode. editorContext_$1.setCurrentMode('path'); subpath = true; } else { pathActions.clear(true); pathActions.toEditMode(path$1.elem); } }, /** * @param {Element} target * @returns {void} */ select: function select(target) { if (currentPath === target) { pathActions.toEditMode(target); editorContext_$1.setCurrentMode('pathedit'); // going into pathedit mode } else { currentPath = target; } }, /** * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ reorient: function reorient() { var elem = editorContext_$1.getSelectedElements()[0]; if (!elem) { return; } var angl = getRotationAngle(elem); if (angl === 0) { return; } var batchCmd = new BatchCommand('Reorient path'); var changes = { d: elem.getAttribute('d'), transform: elem.getAttribute('transform') }; batchCmd.addSubCommand(new ChangeElementCommand(elem, changes)); editorContext_$1.clearSelection(); this.resetOrientation(elem); editorContext_$1.addCommandToHistory(batchCmd); // Set matrix to null getPath_(elem).show(false).matrix = null; this.clear(); editorContext_$1.addToSelection([elem], true); editorContext_$1.call('changed', editorContext_$1.getSelectedElements()); }, /** * @param {boolean} remove Not in use * @returns {void} */ clear: function clear(remove) { var drawnPath = editorContext_$1.getDrawnPath(); currentPath = null; if (drawnPath) { var elem = getElem(editorContext_$1.getId()); $$4(getElem('path_stretch_line')).remove(); $$4(elem).remove(); $$4(getElem('pathpointgrip_container')).find('*').attr('display', 'none'); firstCtrl = null; editorContext_$1.setDrawnPath(null); editorContext_$1.setStarted(false); } else if (editorContext_$1.getCurrentMode() === 'pathedit') { this.toSelectMode(); } if (path$1) { path$1.init().show(false); } }, /** * @param {?(Element|SVGPathElement)} pth * @returns {false|void} */ resetOrientation: function resetOrientation(pth) { if (isNullish(pth) || pth.nodeName !== 'path') { return false; } var tlist = getTransformList(pth); var m = transformListToTransform(tlist).matrix; tlist.clear(); pth.removeAttribute('transform'); var segList = pth.pathSegList; // Opera/win/non-EN throws an error here. // TODO: Find out why! // Presumed fixed in Opera 10.5, so commented out for now // try { var len = segList.numberOfItems; // } catch(err) { // const fixed_d = pathActions.convertPath(pth); // pth.setAttribute('d', fixed_d); // segList = pth.pathSegList; // const len = segList.numberOfItems; // } // let lastX, lastY; var _loop = function _loop(i) { var seg = segList.getItem(i); var type = seg.pathSegType; if (type === 1) { return "continue"; } var pts = []; $$4.each(['', 1, 2], function (j, n) { var x = seg['x' + n], y = seg['y' + n]; if (x !== undefined && y !== undefined) { var pt = transformPoint(x, y, m); pts.splice(pts.length, 0, pt.x, pt.y); } }); replacePathSeg(type, i, pts, pth); }; for (var i = 0; i < len; ++i) { var _ret = _loop(i); if (_ret === "continue") continue; } reorientGrads(pth, m); return undefined; }, /** * @returns {void} */ zoomChange: function zoomChange() { if (editorContext_$1.getCurrentMode() === 'pathedit') { path$1.update(); } }, /** * @typedef {PlainObject} module:path.NodePoint * @property {Float} x * @property {Float} y * @property {Integer} type */ /** * @returns {module:path.NodePoint} */ getNodePoint: function getNodePoint() { var selPt = path$1.selected_pts.length ? path$1.selected_pts[0] : 1; var seg = path$1.segs[selPt]; return { x: seg.item.x, y: seg.item.y, type: seg.type }; }, /** * @param {boolean} linkPoints * @returns {void} */ linkControlPoints: function linkControlPoints(linkPoints) { setLinkControlPoints(linkPoints); }, /** * @returns {void} */ clonePathNode: function clonePathNode() { path$1.storeD(); var selPts = path$1.selected_pts; // const {segs} = path; var i = selPts.length; var nums = []; while (i--) { var pt = selPts[i]; path$1.addSeg(pt); nums.push(pt + i); nums.push(pt + i + 1); } path$1.init().addPtsToSelection(nums); path$1.endChanges('Clone path node(s)'); }, /** * @returns {void} */ opencloseSubPath: function opencloseSubPath() { var selPts = path$1.selected_pts; // Only allow one selected node for now if (selPts.length !== 1) { return; } var _path = path$1, elem = _path.elem; var list = elem.pathSegList; // const len = list.numberOfItems; var index = selPts[0]; var openPt = null; var startItem = null; // Check if subpath is already open path$1.eachSeg(function (i) { if (this.type === 2 && i <= index) { startItem = this.item; } if (i <= index) { return true; } if (this.type === 2) { // Found M first, so open openPt = i; return false; } if (this.type === 1) { // Found Z first, so closed openPt = false; return false; } return true; }); if (isNullish(openPt)) { // Single path, so close last seg openPt = path$1.segs.length - 1; } if (openPt !== false) { // Close this path // Create a line going to the previous "M" var newseg = elem.createSVGPathSegLinetoAbs(startItem.x, startItem.y); var closer = elem.createSVGPathSegClosePath(); if (openPt === path$1.segs.length - 1) { list.appendItem(newseg); list.appendItem(closer); } else { insertItemBefore(elem, closer, openPt); insertItemBefore(elem, newseg, openPt); } path$1.init().selectPt(openPt + 1); return; } // M 1,1 L 2,2 L 3,3 L 1,1 z // open at 2,2 // M 2,2 L 3,3 L 1,1 // M 1,1 L 2,2 L 1,1 z M 4,4 L 5,5 L6,6 L 5,5 z // M 1,1 L 2,2 L 1,1 z [M 4,4] L 5,5 L(M)6,6 L 5,5 z var seg = path$1.segs[index]; if (seg.mate) { list.removeItem(index); // Removes last "L" list.removeItem(index); // Removes the "Z" path$1.init().selectPt(index - 1); return; } var lastM, zSeg; // Find this sub-path's closing point and remove for (var i = 0; i < list.numberOfItems; i++) { var item = list.getItem(i); if (item.pathSegType === 2) { // Find the preceding M lastM = i; } else if (i === index) { // Remove it list.removeItem(lastM); // index--; } else if (item.pathSegType === 1 && index < i) { // Remove the closing seg of this subpath zSeg = i - 1; list.removeItem(i); break; } } var num = index - lastM - 1; while (num--) { insertItemBefore(elem, list.getItem(lastM), zSeg); } var pt = list.getItem(lastM); // Make this point the new "M" replacePathSeg(2, lastM, [pt.x, pt.y]); // i = index; // i is local here, so has no effect; what was the intent for this? path$1.init().selectPt(0); }, /** * @returns {void} */ deletePathNode: function deletePathNode() { if (!pathActions.canDeleteNodes) { return; } path$1.storeD(); var selPts = path$1.selected_pts; var i = selPts.length; while (i--) { var pt = selPts[i]; path$1.deleteSeg(pt); } // Cleanup var cleanup = function cleanup() { var segList = path$1.elem.pathSegList; var len = segList.numberOfItems; var remItems = function remItems(pos, count) { while (count--) { segList.removeItem(pos); } }; if (len <= 1) { return true; } while (len--) { var item = segList.getItem(len); if (item.pathSegType === 1) { var prev = segList.getItem(len - 1); var nprev = segList.getItem(len - 2); if (prev.pathSegType === 2) { remItems(len - 1, 2); cleanup(); break; } else if (nprev.pathSegType === 2) { remItems(len - 2, 3); cleanup(); break; } } else if (item.pathSegType === 2) { if (len > 0) { var prevType = segList.getItem(len - 1).pathSegType; // Path has M M if (prevType === 2) { remItems(len - 1, 1); cleanup(); break; // Entire path ends with Z M } else if (prevType === 1 && segList.numberOfItems - 1 === len) { remItems(len, 1); cleanup(); break; } } } } return false; }; cleanup(); // Completely delete a path with 1 or 0 segments if (path$1.elem.pathSegList.numberOfItems <= 1) { pathActions.toSelectMode(path$1.elem); editorContext_$1.canvas.deleteSelectedElements(); return; } path$1.init(); path$1.clearSelection(); // TODO: Find right way to select point now // path.selectPt(selPt); if (window.opera) { // Opera repaints incorrectly var cp = $$4(path$1.elem); cp.attr('d', cp.attr('d')); } path$1.endChanges('Delete path node(s)'); }, /* eslint-disable jsdoc/require-returns */ // Can't seem to use `@borrows` here, so using `@see` /** * Smooth polyline into path. * @function module:path.pathActions.smoothPolylineIntoPath * @see module:path~smoothPolylineIntoPath */ smoothPolylineIntoPath: smoothPolylineIntoPath, /* eslint-enable jsdoc/require-returns */ /** * @param {?Integer} v See {@link https://www.w3.org/TR/SVG/single-page.html#paths-InterfaceSVGPathSeg} * @returns {void} */ setSegType: function setSegType(v) { path$1.setSegType(v); }, /** * @param {string} attr * @param {Float} newValue * @returns {void} */ moveNode: function moveNode(attr, newValue) { var selPts = path$1.selected_pts; if (!selPts.length) { return; } path$1.storeD(); // Get first selected point var seg = path$1.segs[selPts[0]]; var diff = { x: 0, y: 0 }; diff[attr] = newValue - seg.item[attr]; seg.move(diff.x, diff.y); path$1.endChanges('Move path point'); }, /** * @param {Element} elem * @returns {void} */ fixEnd: function fixEnd(elem) { // Adds an extra segment if the last seg before a Z doesn't end // at its M point // M0,0 L0,100 L100,100 z var segList = elem.pathSegList; var len = segList.numberOfItems; var lastM; for (var i = 0; i < len; ++i) { var item = segList.getItem(i); if (item.pathSegType === 2) { lastM = item; } if (item.pathSegType === 1) { var prev = segList.getItem(i - 1); if (prev.x !== lastM.x || prev.y !== lastM.y) { // Add an L segment here var newseg = elem.createSVGPathSegLinetoAbs(lastM.x, lastM.y); insertItemBefore(elem, newseg, i); // Can this be done better? pathActions.fixEnd(elem); break; } } } if (isWebkit()) { editorContext_$1.resetD(elem); } }, /* eslint-disable jsdoc/require-returns */ // Can't seem to use `@borrows` here, so using `@see` /** * Convert a path to one with only absolute or relative values. * @function module:path.pathActions.convertPath * @see module:path.convertPath */ convertPath: convertPath /* eslint-enable jsdoc/require-returns */ } ); }(); // end pathActions var $$5 = jQuery; /** * This class encapsulates the concept of a layer in the drawing. It can be constructed with * an existing group element or, with three parameters, will create a new layer group element. * * @example * const l1 = new Layer('name', group); // Use the existing group for this layer. * const l2 = new Layer('name', group, svgElem); // Create a new group and add it to the DOM after group. * const l3 = new Layer('name', null, svgElem); // Create a new group and add it to the DOM as the last layer. * @memberof module:layer */ var Layer = /*#__PURE__*/function () { /** * @param {string} name - Layer name * @param {SVGGElement|null} group - An existing SVG group element or null. * If group and no svgElem, use group for this layer. * If group and svgElem, create a new group element and insert it in the DOM after group. * If no group and svgElem, create a new group element and insert it in the DOM as the last layer. * @param {SVGGElement} [svgElem] - The SVG DOM element. If defined, use this to add * a new layer to the document. */ function Layer(name, group, svgElem) { _classCallCheck(this, Layer); this.name_ = name; this.group_ = svgElem ? null : group; if (svgElem) { // Create a group element with title and add it to the DOM. var svgdoc = svgElem.ownerDocument; this.group_ = svgdoc.createElementNS(NS.SVG, 'g'); var layerTitle = svgdoc.createElementNS(NS.SVG, 'title'); layerTitle.textContent = name; this.group_.append(layerTitle); if (group) { $$5(group).after(this.group_); } else { svgElem.append(this.group_); } } addLayerClass(this.group_); walkTree(this.group_, function (e) { e.setAttribute('style', 'pointer-events:inherit'); }); this.group_.setAttribute('style', svgElem ? 'pointer-events:all' : 'pointer-events:none'); } /** * Get the layer's name. * @returns {string} The layer name */ _createClass(Layer, [{ key: "getName", value: function getName() { return this.name_; } /** * Get the group element for this layer. * @returns {SVGGElement} The layer SVG group */ }, { key: "getGroup", value: function getGroup() { return this.group_; } /** * Active this layer so it takes pointer events. * @returns {void} */ }, { key: "activate", value: function activate() { this.group_.setAttribute('style', 'pointer-events:all'); } /** * Deactive this layer so it does NOT take pointer events. * @returns {void} */ }, { key: "deactivate", value: function deactivate() { this.group_.setAttribute('style', 'pointer-events:none'); } /** * Set this layer visible or hidden based on 'visible' parameter. * @param {boolean} visible - If true, make visible; otherwise, hide it. * @returns {void} */ }, { key: "setVisible", value: function setVisible(visible) { var expected = visible === undefined || visible ? 'inline' : 'none'; var oldDisplay = this.group_.getAttribute('display'); if (oldDisplay !== expected) { this.group_.setAttribute('display', expected); } } /** * Is this layer visible? * @returns {boolean} True if visible. */ }, { key: "isVisible", value: function isVisible() { return this.group_.getAttribute('display') !== 'none'; } /** * Get layer opacity. * @returns {Float} Opacity value. */ }, { key: "getOpacity", value: function getOpacity() { var opacity = this.group_.getAttribute('opacity'); if (isNullish(opacity)) { return 1; } return Number.parseFloat(opacity); } /** * Sets the opacity of this layer. If opacity is not a value between 0.0 and 1.0, * nothing happens. * @param {Float} opacity - A float value in the range 0.0-1.0 * @returns {void} */ }, { key: "setOpacity", value: function setOpacity(opacity) { if (typeof opacity === 'number' && opacity >= 0.0 && opacity <= 1.0) { this.group_.setAttribute('opacity', opacity); } } /** * Append children to this layer. * @param {SVGGElement} children - The children to append to this layer. * @returns {void} */ }, { key: "appendChildren", value: function appendChildren(children) { var _iterator = _createForOfIteratorHelper(children), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var child = _step.value; this.group_.append(child); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } /** * @returns {SVGTitleElement|null} */ }, { key: "getTitleElement", value: function getTitleElement() { var len = this.group_.childNodes.length; for (var i = 0; i < len; ++i) { var child = this.group_.childNodes.item(i); if (child && child.tagName === 'title') { return child; } } return null; } /** * Set the name of this layer. * @param {string} name - The new name. * @param {module:history.HistoryRecordingService} hrService - History recording service * @returns {string|null} The new name if changed; otherwise, null. */ }, { key: "setName", value: function setName(name, hrService) { var previousName = this.name_; name = toXml(name); // now change the underlying title element contents var title = this.getTitleElement(); if (title) { $$5(title).empty(); title.textContent = name; this.name_ = name; if (hrService) { hrService.changeElement(title, { '#text': previousName }); } return this.name_; } return null; } /** * Remove this layer's group from the DOM. No more functions on group can be called after this. * @returns {SVGGElement} The layer SVG group that was just removed. */ }, { key: "removeGroup", value: function removeGroup() { var group = this.group_; this.group_.remove(); this.group_ = undefined; return group; } }]); return Layer; }(); /** * @property {string} CLASS_NAME - class attribute assigned to all layer groups. */ Layer.CLASS_NAME = 'layer'; /** * @property {RegExp} CLASS_REGEX - Used to test presence of class Layer.CLASS_NAME */ Layer.CLASS_REGEX = new RegExp('(\\s|^)' + Layer.CLASS_NAME + '(\\s|$)'); /** * Add class `Layer.CLASS_NAME` to the element (usually `class='layer'`). * * @param {SVGGElement} elem - The SVG element to update * @returns {void} */ function addLayerClass(elem) { var classes = elem.getAttribute('class'); if (isNullish(classes) || !classes.length) { elem.setAttribute('class', Layer.CLASS_NAME); } else if (!Layer.CLASS_REGEX.test(classes)) { elem.setAttribute('class', classes + ' ' + Layer.CLASS_NAME); } } /** * History recording service. * * A self-contained service interface for recording history. Once injected, no other dependencies * or globals are required (example: UndoManager, command types, etc.). Easy to mock for unit tests. * Built on top of history classes in history.js. * * There is a simple start/end interface for batch commands. * * HistoryRecordingService.NO_HISTORY is a singleton that can be passed in to functions * that record history. This helps when the caller requires that no history be recorded. * * The following will record history: insert, batch, insert. * @example * hrService = new HistoryRecordingService(this.undoMgr); * hrService.insertElement(elem, text); // add simple command to history. * hrService.startBatchCommand('create two elements'); * hrService.changeElement(elem, attrs, text); // add to batchCommand * hrService.changeElement(elem, attrs2, text); // add to batchCommand * hrService.endBatchCommand(); // add batch command with two change commands to history. * hrService.insertElement(elem, text); // add simple command to history. * * @example * // Note that all functions return this, so commands can be chained, like so: * hrService * .startBatchCommand('create two elements') * .insertElement(elem, text) * .changeElement(elem, attrs, text) * .endBatchCommand(); * * @memberof module:history */ var HistoryRecordingService = /*#__PURE__*/function () { /** * @param {history.UndoManager|null} undoManager - The undo manager. * A value of `null` is valid for cases where no history recording is required. * See singleton: {@link module:history.HistoryRecordingService.HistoryRecordingService.NO_HISTORY} */ function HistoryRecordingService(undoManager) { _classCallCheck(this, HistoryRecordingService); this.undoManager_ = undoManager; this.currentBatchCommand_ = null; this.batchCommandStack_ = []; } /** * Start a batch command so multiple commands can recorded as a single history command. * Requires a corresponding call to endBatchCommand. Start and end commands can be nested. * * @param {string} text - Optional string describing the batch command. * @returns {module:history.HistoryRecordingService} */ _createClass(HistoryRecordingService, [{ key: "startBatchCommand", value: function startBatchCommand(text) { if (!this.undoManager_) { return this; } this.currentBatchCommand_ = new BatchCommand(text); this.batchCommandStack_.push(this.currentBatchCommand_); return this; } /** * End a batch command and add it to the history or a parent batch command. * @returns {module:history.HistoryRecordingService} */ }, { key: "endBatchCommand", value: function endBatchCommand() { if (!this.undoManager_) { return this; } if (this.currentBatchCommand_) { var batchCommand = this.currentBatchCommand_; this.batchCommandStack_.pop(); var len = this.batchCommandStack_.length; this.currentBatchCommand_ = len ? this.batchCommandStack_[len - 1] : null; this.addCommand_(batchCommand); } return this; } /** * Add a `MoveElementCommand` to the history or current batch command. * @param {Element} elem - The DOM element that was moved * @param {Element} oldNextSibling - The element's next sibling before it was moved * @param {Element} oldParent - The element's parent before it was moved * @param {string} [text] - An optional string visible to user related to this change * @returns {module:history.HistoryRecordingService} */ }, { key: "moveElement", value: function moveElement(elem, oldNextSibling, oldParent, text) { if (!this.undoManager_) { return this; } this.addCommand_(new MoveElementCommand(elem, oldNextSibling, oldParent, text)); return this; } /** * Add an `InsertElementCommand` to the history or current batch command. * @param {Element} elem - The DOM element that was added * @param {string} [text] - An optional string visible to user related to this change * @returns {module:history.HistoryRecordingService} */ }, { key: "insertElement", value: function insertElement(elem, text) { if (!this.undoManager_) { return this; } this.addCommand_(new InsertElementCommand(elem, text)); return this; } /** * Add a `RemoveElementCommand` to the history or current batch command. * @param {Element} elem - The DOM element that was removed * @param {Element} oldNextSibling - The element's next sibling before it was removed * @param {Element} oldParent - The element's parent before it was removed * @param {string} [text] - An optional string visible to user related to this change * @returns {module:history.HistoryRecordingService} */ }, { key: "removeElement", value: function removeElement(elem, oldNextSibling, oldParent, text) { if (!this.undoManager_) { return this; } this.addCommand_(new RemoveElementCommand(elem, oldNextSibling, oldParent, text)); return this; } /** * Add a `ChangeElementCommand` to the history or current batch command. * @param {Element} elem - The DOM element that was changed * @param {module:history.CommandAttributes} attrs - An object with the attributes to be changed and the values they had *before* the change * @param {string} [text] - An optional string visible to user related to this change * @returns {module:history.HistoryRecordingService} */ }, { key: "changeElement", value: function changeElement(elem, attrs, text) { if (!this.undoManager_) { return this; } this.addCommand_(new ChangeElementCommand(elem, attrs, text)); return this; } /** * Private function to add a command to the history or current batch command. * @private * @param {Command} cmd * @returns {module:history.HistoryRecordingService|void} */ }, { key: "addCommand_", value: function addCommand_(cmd) { if (!this.undoManager_) { return this; } if (this.currentBatchCommand_) { this.currentBatchCommand_.addSubCommand(cmd); } else { this.undoManager_.addCommandToHistory(cmd); } return undefined; } }]); return HistoryRecordingService; }(); /** * @memberof module:history.HistoryRecordingService * @property {module:history.HistoryRecordingService} NO_HISTORY - Singleton that can be passed to functions that record history, but the caller requires that no history be recorded. */ HistoryRecordingService.NO_HISTORY = new HistoryRecordingService(); /* globals jQuery */ var $$6 = jQueryPluginSVG(jQuery); /** * Create a clone of an element, updating its ID and its children's IDs when needed. * @function module:utilities.copyElem * @param {Element} el - DOM element to clone * @param {module:utilities.GetNextID} getNextId - The getter of the next unique ID. * @returns {Element} The cloned element */ var copyElem = function copyElem(el, getNextId) { // manually create a copy of the element var newEl = document.createElementNS(el.namespaceURI, el.nodeName); $$6.each(el.attributes, function (i, attr) { if (attr.localName !== '-moz-math-font-style') { newEl.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value); } }); // set the copied element's new id newEl.removeAttribute('id'); newEl.id = getNextId(); // Opera's "d" value needs to be reset for Opera/Win/non-EN // Also needed for webkit (else does not keep curved segments on clone) if (isWebkit() && el.nodeName === 'path') { var fixedD = convertPath(el); newEl.setAttribute('d', fixedD); } // now create copies of all children $$6.each(el.childNodes, function (i, child) { switch (child.nodeType) { case 1: // element node newEl.append(copyElem(child, getNextId)); break; case 3: // text node newEl.textContent = child.nodeValue; break; } }); if ($$6(el).data('gsvg')) { $$6(newEl).data('gsvg', newEl.firstChild); } else if ($$6(el).data('symbol')) { var ref = $$6(el).data('symbol'); $$6(newEl).data('ref', ref).data('symbol', ref); } else if (newEl.tagName === 'image') { preventClickDefault(newEl); } return newEl; }; var $$7 = jQuery; var visElems$1 = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'.split(','); var RandomizeModes = { LET_DOCUMENT_DECIDE: 0, ALWAYS_RANDOMIZE: 1, NEVER_RANDOMIZE: 2 }; var randIds = RandomizeModes.LET_DOCUMENT_DECIDE; // Array with current disabled elements (for in-group editing) var disabledElems = []; /** * Get a HistoryRecordingService. * @param {module:history.HistoryRecordingService} [hrService] - if exists, return it instead of creating a new service. * @returns {module:history.HistoryRecordingService} */ function historyRecordingService(hrService) { return hrService || new HistoryRecordingService(canvas_.undoMgr); } /** * Find the layer name in a group element. * @param {Element} group The group element to search in. * @returns {string} The layer name or empty string. */ function findLayerNameInGroup(group) { return $$7('title', group).text() || (isOpera() && group.querySelectorAll // Hack for Opera 10.60 ? $$7(group.querySelectorAll('title')).text() : ''); } /** * Given a set of names, return a new unique name. * @param {string[]} existingLayerNames - Existing layer names. * @returns {string} - The new name. */ function getNewLayerName(existingLayerNames) { var i = 1; // TODO(codedread): What about internationalization of "Layer"? while (existingLayerNames.includes('Layer ' + i)) { i++; } return 'Layer ' + i; } /** * This class encapsulates the concept of a SVG-edit drawing. */ var Drawing = /*#__PURE__*/function () { /** * @param {SVGSVGElement} svgElem - The SVG DOM Element that this JS object * encapsulates. If the svgElem has a se:nonce attribute on it, then * IDs will use the nonce as they are generated. * @param {string} [optIdPrefix=svg_] - The ID prefix to use. * @throws {Error} If not initialized with an SVG element */ function Drawing(svgElem, optIdPrefix) { _classCallCheck(this, Drawing); if (!svgElem || !svgElem.tagName || !svgElem.namespaceURI || svgElem.tagName !== 'svg' || svgElem.namespaceURI !== NS.SVG) { throw new Error('Error: svgedit.draw.Drawing instance initialized without a <svg> element'); } /** * The SVG DOM Element that represents this drawing. * @type {SVGSVGElement} */ this.svgElem_ = svgElem; /** * The latest object number used in this drawing. * @type {Integer} */ this.obj_num = 0; /** * The prefix to prepend to each element id in the drawing. * @type {string} */ this.idPrefix = optIdPrefix || 'svg_'; /** * An array of released element ids to immediately reuse. * @type {Integer[]} */ this.releasedNums = []; /** * The z-ordered array of Layer objects. Each layer has a name * and group element. * The first layer is the one at the bottom of the rendering. * @type {Layer[]} */ this.all_layers = []; /** * Map of all_layers by name. * * Note: Layers are ordered, but referenced externally by name; so, we need both container * types depending on which function is called (i.e. all_layers and layer_map). * * @type {PlainObject<string, Layer>} */ this.layer_map = {}; /** * The current layer being used. * @type {Layer} */ this.current_layer = null; /** * The nonce to use to uniquely identify elements across drawings. * @type {!string} */ this.nonce_ = ''; var n = this.svgElem_.getAttributeNS(NS.SE, 'nonce'); // If already set in the DOM, use the nonce throughout the document // else, if randomizeIds(true) has been called, create and set the nonce. if (n && randIds !== RandomizeModes.NEVER_RANDOMIZE) { this.nonce_ = n; } else if (randIds === RandomizeModes.ALWAYS_RANDOMIZE) { this.setNonce(Math.floor(Math.random() * 100001)); } } /** * @param {string} id Element ID to retrieve * @returns {Element} SVG element within the root SVGSVGElement */ _createClass(Drawing, [{ key: "getElem_", value: function getElem_(id) { if (this.svgElem_.querySelector) { // querySelector lookup return this.svgElem_.querySelector('#' + id); } // jQuery lookup: twice as slow as xpath in FF return $$7(this.svgElem_).find('[id=' + id + ']')[0]; } /** * @returns {SVGSVGElement} */ }, { key: "getSvgElem", value: function getSvgElem() { return this.svgElem_; } /** * @returns {!(string|Integer)} The previously set nonce */ }, { key: "getNonce", value: function getNonce() { return this.nonce_; } /** * @param {!(string|Integer)} n The nonce to set * @returns {void} */ }, { key: "setNonce", value: function setNonce(n) { this.svgElem_.setAttributeNS(NS.XMLNS, 'xmlns:se', NS.SE); this.svgElem_.setAttributeNS(NS.SE, 'se:nonce', n); this.nonce_ = n; } /** * Clears any previously set nonce. * @returns {void} */ }, { key: "clearNonce", value: function clearNonce() { // We deliberately leave any se:nonce attributes alone, // we just don't use it to randomize ids. this.nonce_ = ''; } /** * Returns the latest object id as a string. * @returns {string} The latest object Id. */ }, { key: "getId", value: function getId() { return this.nonce_ ? this.idPrefix + this.nonce_ + '_' + this.obj_num : this.idPrefix + this.obj_num; } /** * Returns the next object Id as a string. * @returns {string} The next object Id to use. */ }, { key: "getNextId", value: function getNextId() { var oldObjNum = this.obj_num; var restoreOldObjNum = false; // If there are any released numbers in the release stack, // use the last one instead of the next obj_num. // We need to temporarily use obj_num as that is what getId() depends on. if (this.releasedNums.length > 0) { this.obj_num = this.releasedNums.pop(); restoreOldObjNum = true; } else { // If we are not using a released id, then increment the obj_num. this.obj_num++; } // Ensure the ID does not exist. var id = this.getId(); while (this.getElem_(id)) { if (restoreOldObjNum) { this.obj_num = oldObjNum; restoreOldObjNum = false; } this.obj_num++; id = this.getId(); } // Restore the old object number if required. if (restoreOldObjNum) { this.obj_num = oldObjNum; } return id; } /** * Releases the object Id, letting it be used as the next id in getNextId(). * This method DOES NOT remove any elements from the DOM, it is expected * that client code will do this. * @param {string} id - The id to release. * @returns {boolean} True if the id was valid to be released, false otherwise. */ }, { key: "releaseId", value: function releaseId(id) { // confirm if this is a valid id for this Document, else return false var front = this.idPrefix + (this.nonce_ ? this.nonce_ + '_' : ''); if (typeof id !== 'string' || !id.startsWith(front)) { return false; } // extract the obj_num of this id var num = Number.parseInt(id.substr(front.length)); // if we didn't get a positive number or we already released this number // then return false. if (typeof num !== 'number' || num <= 0 || this.releasedNums.includes(num)) { return false; } // push the released number into the released queue this.releasedNums.push(num); return true; } /** * Returns the number of layers in the current drawing. * @returns {Integer} The number of layers in the current drawing. */ }, { key: "getNumLayers", value: function getNumLayers() { return this.all_layers.length; } /** * Check if layer with given name already exists. * @param {string} name - The layer name to check * @returns {boolean} */ }, { key: "hasLayer", value: function hasLayer(name) { return this.layer_map[name] !== undefined; } /** * Returns the name of the ith layer. If the index is out of range, an empty string is returned. * @param {Integer} i - The zero-based index of the layer you are querying. * @returns {string} The name of the ith layer (or the empty string if none found) */ }, { key: "getLayerName", value: function getLayerName(i) { return i >= 0 && i < this.getNumLayers() ? this.all_layers[i].getName() : ''; } /** * @returns {SVGGElement|null} The SVGGElement representing the current layer. */ }, { key: "getCurrentLayer", value: function getCurrentLayer() { return this.current_layer ? this.current_layer.getGroup() : null; } /** * Get a layer by name. * @param {string} name * @returns {SVGGElement} The SVGGElement representing the named layer or null. */ }, { key: "getLayerByName", value: function getLayerByName(name) { var layer = this.layer_map[name]; return layer ? layer.getGroup() : null; } /** * Returns the name of the currently selected layer. If an error occurs, an empty string * is returned. * @returns {string} The name of the currently active layer (or the empty string if none found). */ }, { key: "getCurrentLayerName", value: function getCurrentLayerName() { return this.current_layer ? this.current_layer.getName() : ''; } /** * Set the current layer's name. * @param {string} name - The new name. * @param {module:history.HistoryRecordingService} hrService - History recording service * @returns {string|null} The new name if changed; otherwise, null. */ }, { key: "setCurrentLayerName", value: function setCurrentLayerName(name, hrService) { var finalName = null; if (this.current_layer) { var oldName = this.current_layer.getName(); finalName = this.current_layer.setName(name, hrService); if (finalName) { delete this.layer_map[oldName]; this.layer_map[finalName] = this.current_layer; } } return finalName; } /** * Set the current layer's position. * @param {Integer} newpos - The zero-based index of the new position of the layer. Range should be 0 to layers-1 * @returns {{title: SVGGElement, previousName: string}|null} If the name was changed, returns {title:SVGGElement, previousName:string}; otherwise null. */ }, { key: "setCurrentLayerPosition", value: function setCurrentLayerPosition(newpos) { var layerCount = this.getNumLayers(); if (!this.current_layer || newpos < 0 || newpos >= layerCount) { return null; } var oldpos; for (oldpos = 0; oldpos < layerCount; ++oldpos) { if (this.all_layers[oldpos] === this.current_layer) { break; } } // some unknown error condition (current_layer not in all_layers) if (oldpos === layerCount) { return null; } if (oldpos !== newpos) { // if our new position is below us, we need to insert before the node after newpos var currentGroup = this.current_layer.getGroup(); var oldNextSibling = currentGroup.nextSibling; var refGroup = null; if (newpos > oldpos) { if (newpos < layerCount - 1) { refGroup = this.all_layers[newpos + 1].getGroup(); } // if our new position is above us, we need to insert before the node at newpos } else { refGroup = this.all_layers[newpos].getGroup(); } this.svgElem_.insertBefore(currentGroup, refGroup); // Ok to replace with `refGroup.before(currentGroup);`? this.identifyLayers(); this.setCurrentLayer(this.getLayerName(newpos)); return { currentGroup: currentGroup, oldNextSibling: oldNextSibling }; } return null; } /** * @param {module:history.HistoryRecordingService} hrService * @returns {void} */ }, { key: "mergeLayer", value: function mergeLayer(hrService) { var currentGroup = this.current_layer.getGroup(); var prevGroup = $$7(currentGroup).prev()[0]; if (!prevGroup) { return; } hrService.startBatchCommand('Merge Layer'); var layerNextSibling = currentGroup.nextSibling; hrService.removeElement(currentGroup, layerNextSibling, this.svgElem_); while (currentGroup.firstChild) { var child = currentGroup.firstChild; if (child.localName === 'title') { hrService.removeElement(child, child.nextSibling, currentGroup); child.remove(); continue; } var oldNextSibling = child.nextSibling; prevGroup.append(child); hrService.moveElement(child, oldNextSibling, currentGroup); } // Remove current layer's group this.current_layer.removeGroup(); // Remove the current layer and set the previous layer as the new current layer var index = this.all_layers.indexOf(this.current_layer); if (index > 0) { var _name = this.current_layer.getName(); this.current_layer = this.all_layers[index - 1]; this.all_layers.splice(index, 1); delete this.layer_map[_name]; } hrService.endBatchCommand(); } /** * @param {module:history.HistoryRecordingService} hrService * @returns {void} */ }, { key: "mergeAllLayers", value: function mergeAllLayers(hrService) { // Set the current layer to the last layer. this.current_layer = this.all_layers[this.all_layers.length - 1]; hrService.startBatchCommand('Merge all Layers'); while (this.all_layers.length > 1) { this.mergeLayer(hrService); } hrService.endBatchCommand(); } /** * Sets the current layer. If the name is not a valid layer name, then this * function returns `false`. Otherwise it returns `true`. This is not an * undo-able action. * @param {string} name - The name of the layer you want to switch to. * @returns {boolean} `true` if the current layer was switched, otherwise `false` */ }, { key: "setCurrentLayer", value: function setCurrentLayer(name) { var layer = this.layer_map[name]; if (layer) { if (this.current_layer) { this.current_layer.deactivate(); } this.current_layer = layer; this.current_layer.activate(); return true; } return false; } /** * Deletes the current layer from the drawing and then clears the selection. * This function then calls the 'changed' handler. This is an undoable action. * @todo Does this actually call the 'changed' handler? * @returns {SVGGElement} The SVGGElement of the layer removed or null. */ }, { key: "deleteCurrentLayer", value: function deleteCurrentLayer() { if (this.current_layer && this.getNumLayers() > 1) { var oldLayerGroup = this.current_layer.removeGroup(); this.identifyLayers(); return oldLayerGroup; } return null; } /** * Updates layer system and sets the current layer to the * top-most layer (last `<g>` child of this drawing). * @returns {void} */ }, { key: "identifyLayers", value: function identifyLayers() { this.all_layers = []; this.layer_map = {}; var numchildren = this.svgElem_.childNodes.length; // loop through all children of SVG element var orphans = [], layernames = []; var layer = null; var childgroups = false; for (var i = 0; i < numchildren; ++i) { var child = this.svgElem_.childNodes.item(i); // for each g, find its layer name if (child && child.nodeType === 1) { if (child.tagName === 'g') { childgroups = true; var _name2 = findLayerNameInGroup(child); if (_name2) { layernames.push(_name2); layer = new Layer(_name2, child); this.all_layers.push(layer); this.layer_map[_name2] = layer; } else { // if group did not have a name, it is an orphan orphans.push(child); } } else if (visElems$1.includes(child.nodeName)) { // Child is "visible" (i.e. not a <title> or <defs> element), so it is an orphan orphans.push(child); } } } // If orphans or no layers found, create a new layer and add all the orphans to it if (orphans.length > 0 || !childgroups) { layer = new Layer(getNewLayerName(layernames), null, this.svgElem_); layer.appendChildren(orphans); this.all_layers.push(layer); this.layer_map[name] = layer; } else { layer.activate(); } this.current_layer = layer; } /** * Creates a new top-level layer in the drawing with the given name and * makes it the current layer. * @param {string} name - The given name. If the layer name exists, a new name will be generated. * @param {module:history.HistoryRecordingService} hrService - History recording service * @returns {SVGGElement} The SVGGElement of the new layer, which is * also the current layer of this drawing. */ }, { key: "createLayer", value: function createLayer(name, hrService) { if (this.current_layer) { this.current_layer.deactivate(); } // Check for duplicate name. if (name === undefined || name === null || name === '' || this.layer_map[name]) { name = getNewLayerName(Object.keys(this.layer_map)); } // Crate new layer and add to DOM as last layer var layer = new Layer(name, null, this.svgElem_); // Like to assume hrService exists, but this is backwards compatible with old version of createLayer. if (hrService) { hrService.startBatchCommand('Create Layer'); hrService.insertElement(layer.getGroup()); hrService.endBatchCommand(); } this.all_layers.push(layer); this.layer_map[name] = layer; this.current_layer = layer; return layer.getGroup(); } /** * Creates a copy of the current layer with the given name and makes it the current layer. * @param {string} name - The given name. If the layer name exists, a new name will be generated. * @param {module:history.HistoryRecordingService} hrService - History recording service * @returns {SVGGElement} The SVGGElement of the new layer, which is * also the current layer of this drawing. */ }, { key: "cloneLayer", value: function cloneLayer(name, hrService) { var _this = this; if (!this.current_layer) { return null; } this.current_layer.deactivate(); // Check for duplicate name. if (name === undefined || name === null || name === '' || this.layer_map[name]) { name = getNewLayerName(Object.keys(this.layer_map)); } // Create new group and add to DOM just after current_layer var currentGroup = this.current_layer.getGroup(); var layer = new Layer(name, currentGroup, this.svgElem_); var group = layer.getGroup(); // Clone children var children = _toConsumableArray(currentGroup.childNodes); children.forEach(function (child) { if (child.localName === 'title') { return; } group.append(_this.copyElem(child)); }); if (hrService) { hrService.startBatchCommand('Duplicate Layer'); hrService.insertElement(group); hrService.endBatchCommand(); } // Update layer containers and current_layer. var index = this.all_layers.indexOf(this.current_layer); if (index >= 0) { this.all_layers.splice(index + 1, 0, layer); } else { this.all_layers.push(layer); } this.layer_map[name] = layer; this.current_layer = layer; return group; } /** * Returns whether the layer is visible. If the layer name is not valid, * then this function returns `false`. * @param {string} layerName - The name of the layer which you want to query. * @returns {boolean} The visibility state of the layer, or `false` if the layer name was invalid. */ }, { key: "getLayerVisibility", value: function getLayerVisibility(layerName) { var layer = this.layer_map[layerName]; return layer ? layer.isVisible() : false; } /** * Sets the visibility of the layer. If the layer name is not valid, this * function returns `null`, otherwise it returns the `SVGElement` representing * the layer. This is an undo-able action. * @param {string} layerName - The name of the layer to change the visibility * @param {boolean} bVisible - Whether the layer should be visible * @returns {?SVGGElement} The SVGGElement representing the layer if the * `layerName` was valid, otherwise `null`. */ }, { key: "setLayerVisibility", value: function setLayerVisibility(layerName, bVisible) { if (typeof bVisible !== 'boolean') { return null; } var layer = this.layer_map[layerName]; if (!layer) { return null; } layer.setVisible(bVisible); return layer.getGroup(); } /** * Returns the opacity of the given layer. If the input name is not a layer, `null` is returned. * @param {string} layerName - name of the layer on which to get the opacity * @returns {?Float} The opacity value of the given layer. This will be a value between 0.0 and 1.0, or `null` * if `layerName` is not a valid layer */ }, { key: "getLayerOpacity", value: function getLayerOpacity(layerName) { var layer = this.layer_map[layerName]; if (!layer) { return null; } return layer.getOpacity(); } /** * Sets the opacity of the given layer. If the input name is not a layer, * nothing happens. If opacity is not a value between 0.0 and 1.0, then * nothing happens. * NOTE: this function exists solely to apply a highlighting/de-emphasis * effect to a layer. When it is possible for a user to affect the opacity * of a layer, we will need to allow this function to produce an undo-able * action. * @param {string} layerName - Name of the layer on which to set the opacity * @param {Float} opacity - A float value in the range 0.0-1.0 * @returns {void} */ }, { key: "setLayerOpacity", value: function setLayerOpacity(layerName, opacity) { if (typeof opacity !== 'number' || opacity < 0.0 || opacity > 1.0) { return; } var layer = this.layer_map[layerName]; if (layer) { layer.setOpacity(opacity); } } /** * Create a clone of an element, updating its ID and its children's IDs when needed. * @param {Element} el - DOM element to clone * @returns {Element} */ }, { key: "copyElem", value: function copyElem$1(el) { var that = this; var getNextIdClosure = function getNextIdClosure() { return that.getNextId(); }; return copyElem(el, getNextIdClosure); } }]); return Drawing; }(); /** * Called to ensure that drawings will or will not have randomized ids. * The currentDrawing will have its nonce set if it doesn't already. * @function module:draw.randomizeIds * @param {boolean} enableRandomization - flag indicating if documents should have randomized ids * @param {draw.Drawing} currentDrawing * @returns {void} */ var randomizeIds = function randomizeIds(enableRandomization, currentDrawing) { randIds = enableRandomization === false ? RandomizeModes.NEVER_RANDOMIZE : RandomizeModes.ALWAYS_RANDOMIZE; if (randIds === RandomizeModes.ALWAYS_RANDOMIZE && !currentDrawing.getNonce()) { currentDrawing.setNonce(Math.floor(Math.random() * 100001)); } else if (randIds === RandomizeModes.NEVER_RANDOMIZE && currentDrawing.getNonce()) { currentDrawing.clearNonce(); } }; // Layer API Functions /** * Group: Layers. */ /** * @see {@link https://api.jquery.com/jQuery.data/} * @name external:jQuery.data */ /** * @interface module:draw.DrawCanvasInit * @property {module:path.pathActions} pathActions * @property {external:jQuery.data} elData * @property {module:history.UndoManager} undoMgr */ /** * @function module:draw.DrawCanvasInit#getCurrentGroup * @returns {Element} */ /** * @function module:draw.DrawCanvasInit#setCurrentGroup * @param {Element} cg * @returns {void} */ /** * @function module:draw.DrawCanvasInit#getSelectedElements * @returns {Element[]} the array with selected DOM elements */ /** * @function module:draw.DrawCanvasInit#getSVGContent * @returns {SVGSVGElement} */ /** * @function module:draw.DrawCanvasInit#getCurrentDrawing * @returns {module:draw.Drawing} */ /** * @function module:draw.DrawCanvasInit#clearSelection * @param {boolean} [noCall] - When `true`, does not call the "selected" handler * @returns {void} */ /** * Run the callback function associated with the given event. * @function module:draw.DrawCanvasInit#call * @param {"changed"|"contextset"} ev - String with the event name * @param {module:svgcanvas.SvgCanvas#event:changed|module:svgcanvas.SvgCanvas#event:contextset} arg - Argument to pass through to the callback * function. If the event is "changed", a (single-item) array of `Element`s is * passed. If the event is "contextset", the arg is `null` or `Element`. * @returns {void} */ /** * @function module:draw.DrawCanvasInit#addCommandToHistory * @param {Command} cmd * @returns {void} */ /** * @function module:draw.DrawCanvasInit#changeSVGContent * @returns {void} */ var canvas_; /** * @function module:draw.init * @param {module:draw.DrawCanvasInit} canvas * @returns {void} */ var init$3 = function init(canvas) { canvas_ = canvas; }; /** * Updates layer system. * @function module:draw.identifyLayers * @returns {void} */ var identifyLayers = function identifyLayers() { leaveContext(); canvas_.getCurrentDrawing().identifyLayers(); }; /** * Creates a new top-level layer in the drawing with the given name, sets the current layer * to it, and then clears the selection. This function then calls the 'changed' handler. * This is an undoable action. * @function module:draw.createLayer * @param {string} name - The given name * @param {module:history.HistoryRecordingService} hrService * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ var createLayer = function createLayer(name, hrService) { var newLayer = canvas_.getCurrentDrawing().createLayer(name, historyRecordingService(hrService)); canvas_.clearSelection(); canvas_.call('changed', [newLayer]); }; /** * Creates a new top-level layer in the drawing with the given name, copies all the current layer's contents * to it, and then clears the selection. This function then calls the 'changed' handler. * This is an undoable action. * @function module:draw.cloneLayer * @param {string} name - The given name. If the layer name exists, a new name will be generated. * @param {module:history.HistoryRecordingService} hrService - History recording service * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ var cloneLayer = function cloneLayer(name, hrService) { // Clone the current layer and make the cloned layer the new current layer var newLayer = canvas_.getCurrentDrawing().cloneLayer(name, historyRecordingService(hrService)); canvas_.clearSelection(); leaveContext(); canvas_.call('changed', [newLayer]); }; /** * Deletes the current layer from the drawing and then clears the selection. This function * then calls the 'changed' handler. This is an undoable action. * @function module:draw.deleteCurrentLayer * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {boolean} `true` if an old layer group was found to delete */ var deleteCurrentLayer = function deleteCurrentLayer() { var currentLayer = canvas_.getCurrentDrawing().getCurrentLayer(); var _currentLayer = currentLayer, nextSibling = _currentLayer.nextSibling; var parent = currentLayer.parentNode; currentLayer = canvas_.getCurrentDrawing().deleteCurrentLayer(); if (currentLayer) { var batchCmd = new BatchCommand('Delete Layer'); // store in our Undo History batchCmd.addSubCommand(new RemoveElementCommand(currentLayer, nextSibling, parent)); canvas_.addCommandToHistory(batchCmd); canvas_.clearSelection(); canvas_.call('changed', [parent]); return true; } return false; }; /** * Sets the current layer. If the name is not a valid layer name, then this function returns * false. Otherwise it returns true. This is not an undo-able action. * @function module:draw.setCurrentLayer * @param {string} name - The name of the layer you want to switch to. * @returns {boolean} true if the current layer was switched, otherwise false */ var setCurrentLayer = function setCurrentLayer(name) { var result = canvas_.getCurrentDrawing().setCurrentLayer(toXml(name)); if (result) { canvas_.clearSelection(); } return result; }; /** * Renames the current layer. If the layer name is not valid (i.e. unique), then this function * does nothing and returns `false`, otherwise it returns `true`. This is an undo-able action. * @function module:draw.renameCurrentLayer * @param {string} newName - the new name you want to give the current layer. This name must * be unique among all layer names. * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {boolean} Whether the rename succeeded */ var renameCurrentLayer = function renameCurrentLayer(newName) { var drawing = canvas_.getCurrentDrawing(); var layer = drawing.getCurrentLayer(); if (layer) { var result = drawing.setCurrentLayerName(newName, historyRecordingService()); if (result) { canvas_.call('changed', [layer]); return true; } } return false; }; /** * Changes the position of the current layer to the new value. If the new index is not valid, * this function does nothing and returns false, otherwise it returns true. This is an * undo-able action. * @function module:draw.setCurrentLayerPosition * @param {Integer} newPos - The zero-based index of the new position of the layer. This should be between * 0 and (number of layers - 1) * @returns {boolean} `true` if the current layer position was changed, `false` otherwise. */ var setCurrentLayerPosition = function setCurrentLayerPosition(newPos) { var drawing = canvas_.getCurrentDrawing(); var result = drawing.setCurrentLayerPosition(newPos); if (result) { canvas_.addCommandToHistory(new MoveElementCommand(result.currentGroup, result.oldNextSibling, canvas_.getSVGContent())); return true; } return false; }; /** * Sets the visibility of the layer. If the layer name is not valid, this function return * `false`, otherwise it returns `true`. This is an undo-able action. * @function module:draw.setLayerVisibility * @param {string} layerName - The name of the layer to change the visibility * @param {boolean} bVisible - Whether the layer should be visible * @returns {boolean} true if the layer's visibility was set, false otherwise */ var setLayerVisibility = function setLayerVisibility(layerName, bVisible) { var drawing = canvas_.getCurrentDrawing(); var prevVisibility = drawing.getLayerVisibility(layerName); var layer = drawing.setLayerVisibility(layerName, bVisible); if (layer) { var oldDisplay = prevVisibility ? 'inline' : 'none'; canvas_.addCommandToHistory(new ChangeElementCommand(layer, { display: oldDisplay }, 'Layer Visibility')); } else { return false; } if (layer === drawing.getCurrentLayer()) { canvas_.clearSelection(); canvas_.pathActions.clear(); } // call('changed', [selected]); return true; }; /** * Moves the selected elements to layerName. If the name is not a valid layer name, then `false` * is returned. Otherwise it returns `true`. This is an undo-able action. * @function module:draw.moveSelectedToLayer * @param {string} layerName - The name of the layer you want to which you want to move the selected elements * @returns {boolean} Whether the selected elements were moved to the layer. */ var moveSelectedToLayer = function moveSelectedToLayer(layerName) { // find the layer var drawing = canvas_.getCurrentDrawing(); var layer = drawing.getLayerByName(layerName); if (!layer) { return false; } var batchCmd = new BatchCommand('Move Elements to Layer'); // loop for each selected element and move it var selElems = canvas_.getSelectedElements(); var i = selElems.length; while (i--) { var elem = selElems[i]; if (!elem) { continue; } var oldNextSibling = elem.nextSibling; // TODO: this is pretty brittle! var oldLayer = elem.parentNode; layer.append(elem); batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldLayer)); } canvas_.addCommandToHistory(batchCmd); return true; }; /** * @function module:draw.mergeLayer * @param {module:history.HistoryRecordingService} hrService * @returns {void} */ var mergeLayer = function mergeLayer(hrService) { canvas_.getCurrentDrawing().mergeLayer(historyRecordingService(hrService)); canvas_.clearSelection(); leaveContext(); canvas_.changeSVGContent(); }; /** * @function module:draw.mergeAllLayers * @param {module:history.HistoryRecordingService} hrService * @returns {void} */ var mergeAllLayers = function mergeAllLayers(hrService) { canvas_.getCurrentDrawing().mergeAllLayers(historyRecordingService(hrService)); canvas_.clearSelection(); leaveContext(); canvas_.changeSVGContent(); }; /** * Return from a group context to the regular kind, make any previously * disabled elements enabled again. * @function module:draw.leaveContext * @fires module:svgcanvas.SvgCanvas#event:contextset * @returns {void} */ var leaveContext = function leaveContext() { var len = disabledElems.length; if (len) { for (var i = 0; i < len; i++) { var elem = disabledElems[i]; var orig = canvas_.elData(elem, 'orig_opac'); if (orig !== 1) { elem.setAttribute('opacity', orig); } else { elem.removeAttribute('opacity'); } elem.setAttribute('style', 'pointer-events: inherit'); } disabledElems = []; canvas_.clearSelection(true); canvas_.call('contextset', null); } canvas_.setCurrentGroup(null); }; /** * Set the current context (for in-group editing). * @function module:draw.setContext * @param {Element} elem * @fires module:svgcanvas.SvgCanvas#event:contextset * @returns {void} */ var setContext = function setContext(elem) { leaveContext(); if (typeof elem === 'string') { elem = getElem(elem); } // Edit inside this group canvas_.setCurrentGroup(elem); // Disable other elements $$7(elem).parentsUntil('#svgcontent').andSelf().siblings().each(function () { var opac = this.getAttribute('opacity') || 1; // Store the original's opacity canvas_.elData(this, 'orig_opac', opac); this.setAttribute('opacity', opac * 0.33); this.setAttribute('style', 'pointer-events: none'); disabledElems.push(this); }); canvas_.clearSelection(); canvas_.call('contextset', canvas_.getCurrentGroup()); }; var REVERSE_NS = getReverseNS(); // Todo: Split out into core attributes, presentation attributes, etc. so consistent /** * This defines which elements and attributes that we support (or at least * don't remove). * @type {PlainObject} */ /* eslint-disable max-len */ var svgWhiteList_ = { // SVG Elements a: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'xlink:href', 'xlink:title'], circle: ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'r', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], clipPath: ['class', 'clipPathUnits', 'id'], defs: [], style: ['type'], desc: [], ellipse: ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], feGaussianBlur: ['class', 'color-interpolation-filters', 'id', 'requiredFeatures', 'stdDeviation'], feMorphology: ['class', 'in', 'operator', 'radius'], filter: ['class', 'color-interpolation-filters', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'requiredFeatures', 'width', 'x', 'xlink:href', 'y'], foreignObject: ['class', 'font-size', 'height', 'id', 'opacity', 'requiredFeatures', 'style', 'transform', 'width', 'x', 'y'], g: ['class', 'clip-path', 'clip-rule', 'id', 'display', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-anchor'], image: ['class', 'clip-path', 'clip-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:href', 'xlink:title', 'y'], line: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'y1', 'y2'], linearGradient: ['class', 'id', 'gradientTransform', 'gradientUnits', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'x1', 'x2', 'xlink:href', 'y1', 'y2'], marker: ['id', 'class', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'systemLanguage', 'viewBox'], mask: ['class', 'height', 'id', 'maskContentUnits', 'maskUnits', 'width', 'x', 'y'], metadata: ['class', 'id'], path: ['class', 'clip-path', 'clip-rule', 'd', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], pattern: ['class', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:href', 'y'], polygon: ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'class', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], polyline: ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], radialGradient: ['class', 'cx', 'cy', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'xlink:href'], rect: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'width', 'x', 'y'], stop: ['class', 'id', 'offset', 'requiredFeatures', 'stop-color', 'stop-opacity', 'style', 'systemLanguage'], svg: ['class', 'clip-path', 'clip-rule', 'filter', 'id', 'height', 'mask', 'preserveAspectRatio', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xmlns', 'xmlns:se', 'xmlns:xlink', 'y'], "switch": ['class', 'id', 'requiredFeatures', 'systemLanguage'], symbol: ['class', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'opacity', 'preserveAspectRatio', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'viewBox'], text: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'transform', 'x', 'xml:space', 'y'], textPath: ['class', 'id', 'method', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'transform', 'xlink:href'], title: [], tspan: ['class', 'clip-path', 'clip-rule', 'dx', 'dy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'rotate', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'textLength', 'transform', 'x', 'xml:space', 'y'], use: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'transform', 'width', 'x', 'xlink:href', 'y'], // MathML Elements annotation: ['encoding'], 'annotation-xml': ['encoding'], maction: ['actiontype', 'other', 'selection'], math: ['class', 'id', 'display', 'xmlns'], menclose: ['notation'], merror: [], mfrac: ['linethickness'], mi: ['mathvariant'], mmultiscripts: [], mn: [], mo: ['fence', 'lspace', 'maxsize', 'minsize', 'rspace', 'stretchy'], mover: [], mpadded: ['lspace', 'width', 'height', 'depth', 'voffset'], mphantom: [], mprescripts: [], mroot: [], mrow: ['xlink:href', 'xlink:type', 'xmlns:xlink'], mspace: ['depth', 'height', 'width'], msqrt: [], mstyle: ['displaystyle', 'mathbackground', 'mathcolor', 'mathvariant', 'scriptlevel'], msub: [], msubsup: [], msup: [], mtable: ['align', 'columnalign', 'columnlines', 'columnspacing', 'displaystyle', 'equalcolumns', 'equalrows', 'frame', 'rowalign', 'rowlines', 'rowspacing', 'width'], mtd: ['columnalign', 'columnspan', 'rowalign', 'rowspan'], mtext: [], mtr: ['columnalign', 'rowalign'], munder: [], munderover: [], none: [], semantics: [] }; /* eslint-enable max-len */ // Produce a Namespace-aware version of svgWhitelist var svgWhiteListNS_ = {}; Object.entries(svgWhiteList_).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), elt = _ref2[0], atts = _ref2[1]; var attNS = {}; Object.entries(atts).forEach(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), i = _ref4[0], att = _ref4[1]; if (att.includes(':')) { var v = att.split(':'); attNS[v[1]] = NS[v[0].toUpperCase()]; } else { attNS[att] = att === 'xmlns' ? NS.XMLNS : null; } }); svgWhiteListNS_[elt] = attNS; }); /** * Sanitizes the input node and its children. * It only keeps what is allowed from our whitelist defined above. * @function module:sanitize.sanitizeSvg * @param {Text|Element} node - The DOM element to be checked (we'll also check its children) or text node to be cleaned up * @returns {void} */ var sanitizeSvg = function sanitizeSvg(node) { // Cleanup text nodes if (node.nodeType === 3) { // 3 === TEXT_NODE // Trim whitespace node.nodeValue = node.nodeValue.replace(/^\s+|\s+$/g, ''); // Remove if empty if (!node.nodeValue.length) { node.remove(); } } // We only care about element nodes. // Automatically return for all non-element nodes, such as comments, etc. if (node.nodeType !== 1) { // 1 == ELEMENT_NODE return; } var doc = node.ownerDocument; var parent = node.parentNode; // can parent ever be null here? I think the root node's parent is the document... if (!doc || !parent) { return; } var allowedAttrs = svgWhiteList_[node.nodeName]; var allowedAttrsNS = svgWhiteListNS_[node.nodeName]; // if this element is supported, sanitize it if (typeof allowedAttrs !== 'undefined') { var seAttrs = []; var i = node.attributes.length; while (i--) { // if the attribute is not in our whitelist, then remove it // could use jQuery's inArray(), but I don't know if that's any better var attr = node.attributes.item(i); var attrName = attr.nodeName; var attrLocalName = attr.localName; var attrNsURI = attr.namespaceURI; // Check that an attribute with the correct localName in the correct namespace is on // our whitelist or is a namespace declaration for one of our allowed namespaces if (!({}.hasOwnProperty.call(allowedAttrsNS, attrLocalName) && attrNsURI === allowedAttrsNS[attrLocalName] && attrNsURI !== NS.XMLNS) && !(attrNsURI === NS.XMLNS && REVERSE_NS[attr.value])) { // TODO(codedread): Programmatically add the se: attributes to the NS-aware whitelist. // Bypassing the whitelist to allow se: prefixes. // Is there a more appropriate way to do this? if (attrName.startsWith('se:') || attrName.startsWith('data-')) { seAttrs.push([attrName, attr.value]); } node.removeAttributeNS(attrNsURI, attrLocalName); } // Add spaces before negative signs where necessary if (isGecko()) { switch (attrName) { case 'transform': case 'gradientTransform': case 'patternTransform': { var val = attr.value.replace(/(\d)-/g, '$1 -'); // const val = attr.value.replace(/(?<digit>\d)-/g, '$<digit> -'); node.setAttribute(attrName, val); break; } } } // For the style attribute, rewrite it in terms of XML presentational attributes if (attrName === 'style') { var props = attr.value.split(';'); var p = props.length; while (p--) { var _props$p$split = props[p].split(':'), _props$p$split2 = _slicedToArray(_props$p$split, 2), name = _props$p$split2[0], _val = _props$p$split2[1]; var styleAttrName = (name || '').trim(); var styleAttrVal = (_val || '').trim(); // Now check that this attribute is supported if (allowedAttrs.includes(styleAttrName)) { node.setAttribute(styleAttrName, styleAttrVal); } } node.removeAttribute('style'); } } Object.values(seAttrs).forEach(function (_ref5) { var _ref6 = _slicedToArray(_ref5, 2), att = _ref6[0], val = _ref6[1]; node.setAttributeNS(NS.SE, att, val); }); // for some elements that have a xlink:href, ensure the URI refers to a local element // (but not for links) var href = getHref(node); if (href && ['filter', 'linearGradient', 'pattern', 'radialGradient', 'textPath', 'use'].includes(node.nodeName)) { // TODO: we simply check if the first character is a #, is this bullet-proof? if (href[0] !== '#') { // remove the attribute (but keep the element) setHref(node, ''); node.removeAttributeNS(NS.XLINK, 'href'); } } // Safari crashes on a <use> without a xlink:href, so we just remove the node here if (node.nodeName === 'use' && !getHref(node)) { node.remove(); return; } // if the element has attributes pointing to a non-local reference, // need to remove the attribute Object.values(['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke'], function (attr) { var val = node.getAttribute(attr); if (val) { val = getUrlFromAttr(val); // simply check for first character being a '#' if (val && val[0] !== '#') { node.setAttribute(attr, ''); node.removeAttribute(attr); } } }); // recurse to children i = node.childNodes.length; while (i--) { sanitizeSvg(node.childNodes.item(i)); } // else (element not supported), remove it } else { // remove all children from this node and insert them before this node // TODO: in the case of animation elements this will hardly ever be correct var children = []; while (node.hasChildNodes()) { children.push(parent.insertBefore(node.firstChild, node)); } // remove this node from the document altogether node.remove(); // call sanitizeSvg on each of those children var _i = children.length; while (_i--) { sanitizeSvg(children[_i]); } } }; var $$8 = jQuery; // this is how we map paths to our preferred relative segment types var pathMap$1 = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a', 'H', 'h', 'V', 'v', 'S', 's', 'T', 't']; /** * @interface module:coords.EditorContext */ /** * @function module:coords.EditorContext#getGridSnapping * @returns {boolean} */ /** * @function module:coords.EditorContext#getDrawing * @returns {module:draw.Drawing} */ /** * @function module:coords.EditorContext#getSVGRoot * @returns {SVGSVGElement} */ var editorContext_$2 = null; /** * @function module:coords.init * @param {module:svgcanvas.SvgCanvas#event:pointsAdded} editorContext * @returns {void} */ var init$4 = function init(editorContext) { editorContext_$2 = editorContext; }; /** * Applies coordinate changes to an element based on the given matrix. * @name module:coords.remapElement * @type {module:path.EditorContext#remapElement} */ var remapElement = function remapElement(selected, changes, m) { var remap = function remap(x, y) { return transformPoint(x, y, m); }, scalew = function scalew(w) { return m.a * w; }, scaleh = function scaleh(h) { return m.d * h; }, doSnapping = editorContext_$2.getGridSnapping() && selected.parentNode.parentNode.localName === 'svg', finishUp = function finishUp() { if (doSnapping) { Object.entries(changes).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), o = _ref2[0], value = _ref2[1]; changes[o] = snapToGrid(value); }); } assignAttributes(selected, changes, 1000, true); }, box = getBBox(selected); for (var i = 0; i < 2; i++) { var type = i === 0 ? 'fill' : 'stroke'; var attrVal = selected.getAttribute(type); if (attrVal && attrVal.startsWith('url(')) { if (m.a < 0 || m.d < 0) { var grad = getRefElem(attrVal); var newgrad = grad.cloneNode(true); if (m.a < 0) { // flip x var x1 = newgrad.getAttribute('x1'); var x2 = newgrad.getAttribute('x2'); newgrad.setAttribute('x1', -(x1 - 1)); newgrad.setAttribute('x2', -(x2 - 1)); } if (m.d < 0) { // flip y var y1 = newgrad.getAttribute('y1'); var y2 = newgrad.getAttribute('y2'); newgrad.setAttribute('y1', -(y1 - 1)); newgrad.setAttribute('y2', -(y2 - 1)); } newgrad.id = editorContext_$2.getDrawing().getNextId(); findDefs().append(newgrad); selected.setAttribute(type, 'url(#' + newgrad.id + ')'); } // Not really working :( // if (selected.tagName === 'path') { // reorientGrads(selected, m); // } } } var elName = selected.tagName; if (elName === 'g' || elName === 'text' || elName === 'tspan' || elName === 'use') { // if it was a translate, then just update x,y if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && (m.e !== 0 || m.f !== 0)) { // [T][M] = [M][T'] // therefore [T'] = [M_inv][T][M] var existing = transformListToTransform(selected).matrix, tNew = matrixMultiply(existing.inverse(), m, existing); changes.x = Number.parseFloat(changes.x) + tNew.e; changes.y = Number.parseFloat(changes.y) + tNew.f; } else { // we just absorb all matrices into the element and don't do any remapping var chlist = getTransformList(selected); var mt = editorContext_$2.getSVGRoot().createSVGTransform(); mt.setMatrix(matrixMultiply(transformListToTransform(chlist).matrix, m)); chlist.clear(); chlist.appendItem(mt); } } // now we have a set of changes and an applied reduced transform list // we apply the changes directly to the DOM switch (elName) { case 'foreignObject': case 'rect': case 'image': { // Allow images to be inverted (give them matrix when flipped) if (elName === 'image' && (m.a < 0 || m.d < 0)) { // Convert to matrix var _chlist = getTransformList(selected); var _mt = editorContext_$2.getSVGRoot().createSVGTransform(); _mt.setMatrix(matrixMultiply(transformListToTransform(_chlist).matrix, m)); _chlist.clear(); _chlist.appendItem(_mt); } else { var pt1 = remap(changes.x, changes.y); changes.width = scalew(changes.width); changes.height = scaleh(changes.height); changes.x = pt1.x + Math.min(0, changes.width); changes.y = pt1.y + Math.min(0, changes.height); changes.width = Math.abs(changes.width); changes.height = Math.abs(changes.height); } finishUp(); break; } case 'ellipse': { var c = remap(changes.cx, changes.cy); changes.cx = c.x; changes.cy = c.y; changes.rx = scalew(changes.rx); changes.ry = scaleh(changes.ry); changes.rx = Math.abs(changes.rx); changes.ry = Math.abs(changes.ry); finishUp(); break; } case 'circle': { var _c = remap(changes.cx, changes.cy); changes.cx = _c.x; changes.cy = _c.y; // take the minimum of the new selected box's dimensions for the new circle radius var tbox = transformBox(box.x, box.y, box.width, box.height, m); var w = tbox.tr.x - tbox.tl.x, h = tbox.bl.y - tbox.tl.y; changes.r = Math.min(w / 2, h / 2); if (changes.r) { changes.r = Math.abs(changes.r); } finishUp(); break; } case 'line': { var _pt = remap(changes.x1, changes.y1); var pt2 = remap(changes.x2, changes.y2); changes.x1 = _pt.x; changes.y1 = _pt.y; changes.x2 = pt2.x; changes.y2 = pt2.y; } // Fallthrough case 'text': case 'tspan': case 'use': { finishUp(); break; } case 'g': { var gsvg = $$8(selected).data('gsvg'); if (gsvg) { assignAttributes(gsvg, changes, 1000, true); } break; } case 'polyline': case 'polygon': { var len = changes.points.length; for (var _i = 0; _i < len; ++_i) { var pt = changes.points[_i]; var _remap = remap(pt.x, pt.y), x = _remap.x, y = _remap.y; changes.points[_i].x = x; changes.points[_i].y = y; } // const len = changes.points.length; var pstr = ''; for (var _i2 = 0; _i2 < len; ++_i2) { var _pt2 = changes.points[_i2]; pstr += _pt2.x + ',' + _pt2.y + ' '; } selected.setAttribute('points', pstr); break; } case 'path': { var segList = selected.pathSegList; var _len = segList.numberOfItems; changes.d = []; for (var _i3 = 0; _i3 < _len; ++_i3) { var seg = segList.getItem(_i3); changes.d[_i3] = { type: seg.pathSegType, x: seg.x, y: seg.y, x1: seg.x1, y1: seg.y1, x2: seg.x2, y2: seg.y2, r1: seg.r1, r2: seg.r2, angle: seg.angle, largeArcFlag: seg.largeArcFlag, sweepFlag: seg.sweepFlag }; } _len = changes.d.length; var firstseg = changes.d[0], currentpt = remap(firstseg.x, firstseg.y); changes.d[0].x = currentpt.x; changes.d[0].y = currentpt.y; for (var _i4 = 1; _i4 < _len; ++_i4) { var _seg = changes.d[_i4]; var _type = _seg.type; // if absolute or first segment, we want to remap x, y, x1, y1, x2, y2 // if relative, we want to scalew, scaleh if (_type % 2 === 0) { // absolute var thisx = _seg.x !== undefined ? _seg.x : currentpt.x, // for V commands thisy = _seg.y !== undefined ? _seg.y : currentpt.y; // for H commands var _pt3 = remap(thisx, thisy); var _pt4 = remap(_seg.x1, _seg.y1); var _pt5 = remap(_seg.x2, _seg.y2); _seg.x = _pt3.x; _seg.y = _pt3.y; _seg.x1 = _pt4.x; _seg.y1 = _pt4.y; _seg.x2 = _pt5.x; _seg.y2 = _pt5.y; _seg.r1 = scalew(_seg.r1); _seg.r2 = scaleh(_seg.r2); } else { // relative _seg.x = scalew(_seg.x); _seg.y = scaleh(_seg.y); _seg.x1 = scalew(_seg.x1); _seg.y1 = scaleh(_seg.y1); _seg.x2 = scalew(_seg.x2); _seg.y2 = scaleh(_seg.y2); _seg.r1 = scalew(_seg.r1); _seg.r2 = scaleh(_seg.r2); } } // for each segment var dstr = ''; _len = changes.d.length; for (var _i5 = 0; _i5 < _len; ++_i5) { var _seg2 = changes.d[_i5]; var _type2 = _seg2.type; dstr += pathMap$1[_type2]; switch (_type2) { case 13: // relative horizontal line (h) case 12: // absolute horizontal line (H) dstr += _seg2.x + ' '; break; case 15: // relative vertical line (v) case 14: // absolute vertical line (V) dstr += _seg2.y + ' '; break; case 3: // relative move (m) case 5: // relative line (l) case 19: // relative smooth quad (t) case 2: // absolute move (M) case 4: // absolute line (L) case 18: // absolute smooth quad (T) dstr += _seg2.x + ',' + _seg2.y + ' '; break; case 7: // relative cubic (c) case 6: // absolute cubic (C) dstr += _seg2.x1 + ',' + _seg2.y1 + ' ' + _seg2.x2 + ',' + _seg2.y2 + ' ' + _seg2.x + ',' + _seg2.y + ' '; break; case 9: // relative quad (q) case 8: // absolute quad (Q) dstr += _seg2.x1 + ',' + _seg2.y1 + ' ' + _seg2.x + ',' + _seg2.y + ' '; break; case 11: // relative elliptical arc (a) case 10: // absolute elliptical arc (A) dstr += _seg2.r1 + ',' + _seg2.r2 + ' ' + _seg2.angle + ' ' + Number(_seg2.largeArcFlag) + ' ' + Number(_seg2.sweepFlag) + ' ' + _seg2.x + ',' + _seg2.y + ' '; break; case 17: // relative smooth cubic (s) case 16: // absolute smooth cubic (S) dstr += _seg2.x2 + ',' + _seg2.y2 + ' ' + _seg2.x + ',' + _seg2.y + ' '; break; } } selected.setAttribute('d', dstr); break; } } }; /* globals jQuery */ var $$9 = jQueryPluginSVG(jQuery); var context_; /** * @interface module:recalculate.EditorContext */ /** * @function module:recalculate.EditorContext#getSVGRoot * @returns {SVGSVGElement} The root DOM element */ /** * @function module:recalculate.EditorContext#getStartTransform * @returns {string} */ /** * @function module:recalculate.EditorContext#setStartTransform * @param {string} transform * @returns {void} */ /** * @function module:recalculate.init * @param {module:recalculate.EditorContext} editorContext * @returns {void} */ var init$5 = function init(editorContext) { context_ = editorContext; }; /** * Updates a `<clipPath>`s values based on the given translation of an element. * @function module:recalculate.updateClipPath * @param {string} attr - The clip-path attribute value with the clipPath's ID * @param {Float} tx - The translation's x value * @param {Float} ty - The translation's y value * @returns {void} */ var updateClipPath = function updateClipPath(attr, tx, ty) { var path = getRefElem(attr).firstChild; var cpXform = getTransformList(path); var newxlate = context_.getSVGRoot().createSVGTransform(); newxlate.setTranslate(tx, ty); cpXform.appendItem(newxlate); // Update clipPath's dimensions recalculateDimensions(path); }; /** * Decides the course of action based on the element's transform list. * @function module:recalculate.recalculateDimensions * @param {Element} selected - The DOM element to recalculate * @returns {Command} Undo command object with the resulting change */ var recalculateDimensions = function recalculateDimensions(selected) { if (isNullish(selected)) { return null; } // Firefox Issue - 1081 if (selected.nodeName === 'svg' && navigator.userAgent.includes('Firefox/20')) { return null; } var svgroot = context_.getSVGRoot(); var tlist = getTransformList(selected); // remove any unnecessary transforms if (tlist && tlist.numberOfItems > 0) { var k = tlist.numberOfItems; var noi = k; while (k--) { var xform = tlist.getItem(k); if (xform.type === 0) { tlist.removeItem(k); // remove identity matrices } else if (xform.type === 1) { if (isIdentity(xform.matrix)) { if (noi === 1) { // Overcome Chrome bug (though only when noi is 1) with // `removeItem` preventing `removeAttribute` from // subsequently working // See https://bugs.chromium.org/p/chromium/issues/detail?id=843901 selected.removeAttribute('transform'); return null; } tlist.removeItem(k); } // remove zero-degree rotations } else if (xform.type === 4) { if (xform.angle === 0) { tlist.removeItem(k); } } } // End here if all it has is a rotation if (tlist.numberOfItems === 1 && getRotationAngle(selected)) { return null; } } // if this element had no transforms, we are done if (!tlist || tlist.numberOfItems === 0) { // Chrome apparently had a bug that requires clearing the attribute first. selected.setAttribute('transform', ''); // However, this still next line currently doesn't work at all in Chrome selected.removeAttribute('transform'); // selected.transform.baseVal.clear(); // Didn't help for Chrome bug return null; } // TODO: Make this work for more than 2 if (tlist) { var mxs = []; var _k = tlist.numberOfItems; while (_k--) { var _xform = tlist.getItem(_k); if (_xform.type === 1) { mxs.push([_xform.matrix, _k]); } else if (mxs.length) { mxs = []; } } if (mxs.length === 2) { var mNew = svgroot.createSVGTransformFromMatrix(matrixMultiply(mxs[1][0], mxs[0][0])); tlist.removeItem(mxs[0][1]); tlist.removeItem(mxs[1][1]); tlist.insertItemBefore(mNew, mxs[1][1]); } // combine matrix + translate _k = tlist.numberOfItems; if (_k >= 2 && tlist.getItem(_k - 2).type === 1 && tlist.getItem(_k - 1).type === 2) { var mt = svgroot.createSVGTransform(); var m = matrixMultiply(tlist.getItem(_k - 2).matrix, tlist.getItem(_k - 1).matrix); mt.setMatrix(m); tlist.removeItem(_k - 2); tlist.removeItem(_k - 2); tlist.appendItem(mt); } } // If it still has a single [M] or [R][M], return null too (prevents BatchCommand from being returned). switch (selected.tagName) { // Ignore these elements, as they can absorb the [M] case 'line': case 'polyline': case 'polygon': case 'path': break; default: if (tlist.numberOfItems === 1 && tlist.getItem(0).type === 1 || tlist.numberOfItems === 2 && tlist.getItem(0).type === 1 && tlist.getItem(0).type === 4) { return null; } } // Grouped SVG element var gsvg = $$9(selected).data('gsvg'); // we know we have some transforms, so set up return variable var batchCmd = new BatchCommand('Transform'); // store initial values that will be affected by reducing the transform list var changes = {}; var initial = null; var attrs = []; switch (selected.tagName) { case 'line': attrs = ['x1', 'y1', 'x2', 'y2']; break; case 'circle': attrs = ['cx', 'cy', 'r']; break; case 'ellipse': attrs = ['cx', 'cy', 'rx', 'ry']; break; case 'foreignObject': case 'rect': case 'image': attrs = ['width', 'height', 'x', 'y']; break; case 'use': case 'text': case 'tspan': attrs = ['x', 'y']; break; case 'polygon': case 'polyline': { initial = {}; initial.points = selected.getAttribute('points'); var list = selected.points; var len = list.numberOfItems; changes.points = new Array(len); for (var i = 0; i < len; ++i) { var pt = list.getItem(i); changes.points[i] = { x: pt.x, y: pt.y }; } break; } case 'path': initial = {}; initial.d = selected.getAttribute('d'); changes.d = selected.getAttribute('d'); break; } // switch on element type to get initial values if (attrs.length) { changes = $$9(selected).attr(attrs); $$9.each(changes, function (attr, val) { changes[attr] = convertToNum(attr, val); }); } else if (gsvg) { // GSVG exception changes = { x: $$9(gsvg).attr('x') || 0, y: $$9(gsvg).attr('y') || 0 }; } // if we haven't created an initial array in polygon/polyline/path, then // make a copy of initial values and include the transform if (isNullish(initial)) { initial = $$9.extend(true, {}, changes); $$9.each(initial, function (attr, val) { initial[attr] = convertToNum(attr, val); }); } // save the start transform value too initial.transform = context_.getStartTransform() || ''; var oldcenter, newcenter; // if it's a regular group, we have special processing to flatten transforms if (selected.tagName === 'g' && !gsvg || selected.tagName === 'a') { var box = getBBox(selected); oldcenter = { x: box.x + box.width / 2, y: box.y + box.height / 2 }; newcenter = transformPoint(box.x + box.width / 2, box.y + box.height / 2, transformListToTransform(tlist).matrix); // let m = svgroot.createSVGMatrix(); // temporarily strip off the rotate and save the old center var gangle = getRotationAngle(selected); if (gangle) { var a = gangle * Math.PI / 180; var s; if (Math.abs(a) > 1.0e-10) { s = Math.sin(a) / (1 - Math.cos(a)); } else { // TODO: This blows up if the angle is exactly 0! s = 2 / a; } for (var _i = 0; _i < tlist.numberOfItems; ++_i) { var _xform2 = tlist.getItem(_i); if (_xform2.type === 4) { // extract old center through mystical arts var rm = _xform2.matrix; oldcenter.y = (s * rm.e + rm.f) / 2; oldcenter.x = (rm.e - s * rm.f) / 2; tlist.removeItem(_i); break; } } } var N = tlist.numberOfItems; var tx = 0, ty = 0, operation = 0; var firstM; if (N) { firstM = tlist.getItem(0).matrix; } var oldStartTransform; // first, if it was a scale then the second-last transform will be it if (N >= 3 && tlist.getItem(N - 2).type === 3 && tlist.getItem(N - 3).type === 2 && tlist.getItem(N - 1).type === 2) { operation = 3; // scale // if the children are unrotated, pass the scale down directly // otherwise pass the equivalent matrix() down directly var tm = tlist.getItem(N - 3).matrix, sm = tlist.getItem(N - 2).matrix, tmn = tlist.getItem(N - 1).matrix; var children = selected.childNodes; var c = children.length; while (c--) { var child = children.item(c); tx = 0; ty = 0; if (child.nodeType === 1) { var childTlist = getTransformList(child); // some children might not have a transform (<metadata>, <defs>, etc) if (!childTlist) { continue; } var _m = transformListToTransform(childTlist).matrix; // Convert a matrix to a scale if applicable // if (hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) { // if (m.b==0 && m.c==0 && m.e==0 && m.f==0) { // childTlist.removeItem(0); // const translateOrigin = svgroot.createSVGTransform(), // scale = svgroot.createSVGTransform(), // translateBack = svgroot.createSVGTransform(); // translateOrigin.setTranslate(0, 0); // scale.setScale(m.a, m.d); // translateBack.setTranslate(0, 0); // childTlist.appendItem(translateBack); // childTlist.appendItem(scale); // childTlist.appendItem(translateOrigin); // } // } var angle = getRotationAngle(child); oldStartTransform = context_.getStartTransform(); // const childxforms = []; context_.setStartTransform(child.getAttribute('transform')); if (angle || hasMatrixTransform(childTlist)) { var e2t = svgroot.createSVGTransform(); e2t.setMatrix(matrixMultiply(tm, sm, tmn, _m)); childTlist.clear(); childTlist.appendItem(e2t); // childxforms.push(e2t); // if not rotated or skewed, push the [T][S][-T] down to the child } else { // update the transform list with translate,scale,translate // slide the [T][S][-T] from the front to the back // [T][S][-T][M] = [M][T2][S2][-T2] // (only bringing [-T] to the right of [M]) // [T][S][-T][M] = [T][S][M][-T2] // [-T2] = [M_inv][-T][M] var t2n = matrixMultiply(_m.inverse(), tmn, _m); // [T2] is always negative translation of [-T2] var t2 = svgroot.createSVGMatrix(); t2.e = -t2n.e; t2.f = -t2n.f; // [T][S][-T][M] = [M][T2][S2][-T2] // [S2] = [T2_inv][M_inv][T][S][-T][M][-T2_inv] var s2 = matrixMultiply(t2.inverse(), _m.inverse(), tm, sm, tmn, _m, t2n.inverse()); var translateOrigin = svgroot.createSVGTransform(), scale = svgroot.createSVGTransform(), translateBack = svgroot.createSVGTransform(); translateOrigin.setTranslate(t2n.e, t2n.f); scale.setScale(s2.a, s2.d); translateBack.setTranslate(t2.e, t2.f); childTlist.appendItem(translateBack); childTlist.appendItem(scale); childTlist.appendItem(translateOrigin); // childxforms.push(translateBack); // childxforms.push(scale); // childxforms.push(translateOrigin); // logMatrix(translateBack.matrix); // logMatrix(scale.matrix); } // not rotated batchCmd.addSubCommand(recalculateDimensions(child)); // TODO: If any <use> have this group as a parent and are // referencing this child, then we need to impose a reverse // scale on it so that when it won't get double-translated // const uses = selected.getElementsByTagNameNS(NS.SVG, 'use'); // const href = '#' + child.id; // let u = uses.length; // while (u--) { // const useElem = uses.item(u); // if (href == getHref(useElem)) { // const usexlate = svgroot.createSVGTransform(); // usexlate.setTranslate(-tx,-ty); // getTransformList(useElem).insertItemBefore(usexlate,0); // batchCmd.addSubCommand( recalculateDimensions(useElem) ); // } // } context_.setStartTransform(oldStartTransform); } // element } // for each child // Remove these transforms from group tlist.removeItem(N - 1); tlist.removeItem(N - 2); tlist.removeItem(N - 3); } else if (N >= 3 && tlist.getItem(N - 1).type === 1) { operation = 3; // scale var _m2 = transformListToTransform(tlist).matrix; var _e2t = svgroot.createSVGTransform(); _e2t.setMatrix(_m2); tlist.clear(); tlist.appendItem(_e2t); // next, check if the first transform was a translate // if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ] // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] } else if ((N === 1 || N > 1 && tlist.getItem(1).type !== 3) && tlist.getItem(0).type === 2) { operation = 2; // translate var T_M = transformListToTransform(tlist).matrix; tlist.removeItem(0); var mInv = transformListToTransform(tlist).matrix.inverse(); var M2 = matrixMultiply(mInv, T_M); tx = M2.e; ty = M2.f; if (tx !== 0 || ty !== 0) { // we pass the translates down to the individual children var _children = selected.childNodes; var _c = _children.length; var clipPathsDone = []; while (_c--) { var _child = _children.item(_c); if (_child.nodeType === 1) { // Check if child has clip-path if (_child.getAttribute('clip-path')) { // tx, ty var attr = _child.getAttribute('clip-path'); if (!clipPathsDone.includes(attr)) { updateClipPath(attr, tx, ty); clipPathsDone.push(attr); } } oldStartTransform = context_.getStartTransform(); context_.setStartTransform(_child.getAttribute('transform')); var _childTlist = getTransformList(_child); // some children might not have a transform (<metadata>, <defs>, etc) if (_childTlist) { var newxlate = svgroot.createSVGTransform(); newxlate.setTranslate(tx, ty); if (_childTlist.numberOfItems) { _childTlist.insertItemBefore(newxlate, 0); } else { _childTlist.appendItem(newxlate); } batchCmd.addSubCommand(recalculateDimensions(_child)); // If any <use> have this group as a parent and are // referencing this child, then impose a reverse translate on it // so that when it won't get double-translated var uses = selected.getElementsByTagNameNS(NS.SVG, 'use'); var href = '#' + _child.id; var u = uses.length; while (u--) { var useElem = uses.item(u); if (href === getHref(useElem)) { var usexlate = svgroot.createSVGTransform(); usexlate.setTranslate(-tx, -ty); getTransformList(useElem).insertItemBefore(usexlate, 0); batchCmd.addSubCommand(recalculateDimensions(useElem)); } } context_.setStartTransform(oldStartTransform); } } } context_.setStartTransform(oldStartTransform); } // else, a matrix imposition from a parent group // keep pushing it down to the children } else if (N === 1 && tlist.getItem(0).type === 1 && !gangle) { operation = 1; var _m3 = tlist.getItem(0).matrix, _children2 = selected.childNodes; var _c2 = _children2.length; while (_c2--) { var _child2 = _children2.item(_c2); if (_child2.nodeType === 1) { oldStartTransform = context_.getStartTransform(); context_.setStartTransform(_child2.getAttribute('transform')); var _childTlist2 = getTransformList(_child2); if (!_childTlist2) { continue; } var em = matrixMultiply(_m3, transformListToTransform(_childTlist2).matrix); var e2m = svgroot.createSVGTransform(); e2m.setMatrix(em); _childTlist2.clear(); _childTlist2.appendItem(e2m, 0); batchCmd.addSubCommand(recalculateDimensions(_child2)); context_.setStartTransform(oldStartTransform); // Convert stroke // TODO: Find out if this should actually happen somewhere else var sw = _child2.getAttribute('stroke-width'); if (_child2.getAttribute('stroke') !== 'none' && !isNaN(sw)) { var avg = (Math.abs(em.a) + Math.abs(em.d)) / 2; _child2.setAttribute('stroke-width', sw * avg); } } } tlist.clear(); // else it was just a rotate } else { if (gangle) { var newRot = svgroot.createSVGTransform(); newRot.setRotate(gangle, newcenter.x, newcenter.y); if (tlist.numberOfItems) { tlist.insertItemBefore(newRot, 0); } else { tlist.appendItem(newRot); } } if (tlist.numberOfItems === 0) { selected.removeAttribute('transform'); } return null; } // if it was a translate, put back the rotate at the new center if (operation === 2) { if (gangle) { newcenter = { x: oldcenter.x + firstM.e, y: oldcenter.y + firstM.f }; var _newRot = svgroot.createSVGTransform(); _newRot.setRotate(gangle, newcenter.x, newcenter.y); if (tlist.numberOfItems) { tlist.insertItemBefore(_newRot, 0); } else { tlist.appendItem(_newRot); } } // if it was a resize } else if (operation === 3) { var _m4 = transformListToTransform(tlist).matrix; var roldt = svgroot.createSVGTransform(); roldt.setRotate(gangle, oldcenter.x, oldcenter.y); var rold = roldt.matrix; var rnew = svgroot.createSVGTransform(); rnew.setRotate(gangle, newcenter.x, newcenter.y); var rnewInv = rnew.matrix.inverse(), _mInv = _m4.inverse(), extrat = matrixMultiply(_mInv, rnewInv, rold, _m4); tx = extrat.e; ty = extrat.f; if (tx !== 0 || ty !== 0) { // now push this transform down to the children // we pass the translates down to the individual children var _children3 = selected.childNodes; var _c3 = _children3.length; while (_c3--) { var _child3 = _children3.item(_c3); if (_child3.nodeType === 1) { oldStartTransform = context_.getStartTransform(); context_.setStartTransform(_child3.getAttribute('transform')); var _childTlist3 = getTransformList(_child3); var _newxlate = svgroot.createSVGTransform(); _newxlate.setTranslate(tx, ty); if (_childTlist3.numberOfItems) { _childTlist3.insertItemBefore(_newxlate, 0); } else { _childTlist3.appendItem(_newxlate); } batchCmd.addSubCommand(recalculateDimensions(_child3)); context_.setStartTransform(oldStartTransform); } } } if (gangle) { if (tlist.numberOfItems) { tlist.insertItemBefore(rnew, 0); } else { tlist.appendItem(rnew); } } } // else, it's a non-group } else { // TODO: box might be null for some elements (<metadata> etc), need to handle this var _box = getBBox(selected); // Paths (and possbly other shapes) will have no BBox while still in <defs>, // but we still may need to recalculate them (see issue 595). // TODO: Figure out how to get BBox from these elements in case they // have a rotation transform if (!_box && selected.tagName !== 'path') return null; var _m5; // = svgroot.createSVGMatrix(); // temporarily strip off the rotate and save the old center var _angle = getRotationAngle(selected); if (_angle) { oldcenter = { x: _box.x + _box.width / 2, y: _box.y + _box.height / 2 }; newcenter = transformPoint(_box.x + _box.width / 2, _box.y + _box.height / 2, transformListToTransform(tlist).matrix); var _a = _angle * Math.PI / 180; var _s = Math.abs(_a) > 1.0e-10 ? Math.sin(_a) / (1 - Math.cos(_a)) // TODO: This blows up if the angle is exactly 0! : 2 / _a; for (var _i2 = 0; _i2 < tlist.numberOfItems; ++_i2) { var _xform3 = tlist.getItem(_i2); if (_xform3.type === 4) { // extract old center through mystical arts var _rm = _xform3.matrix; oldcenter.y = (_s * _rm.e + _rm.f) / 2; oldcenter.x = (_rm.e - _s * _rm.f) / 2; tlist.removeItem(_i2); break; } } } // 2 = translate, 3 = scale, 4 = rotate, 1 = matrix imposition var _operation = 0; var _N = tlist.numberOfItems; // Check if it has a gradient with userSpaceOnUse, in which case // adjust it by recalculating the matrix transform. // TODO: Make this work in Webkit using transformlist.SVGTransformList if (!isWebkit()) { var fill = selected.getAttribute('fill'); if (fill && fill.startsWith('url(')) { var paint = getRefElem(fill); var type = 'pattern'; if (paint.tagName !== type) type = 'gradient'; var attrVal = paint.getAttribute(type + 'Units'); if (attrVal === 'userSpaceOnUse') { // Update the userSpaceOnUse element _m5 = transformListToTransform(tlist).matrix; var gtlist = getTransformList(paint); var gmatrix = transformListToTransform(gtlist).matrix; _m5 = matrixMultiply(_m5, gmatrix); var mStr = 'matrix(' + [_m5.a, _m5.b, _m5.c, _m5.d, _m5.e, _m5.f].join(',') + ')'; paint.setAttribute(type + 'Transform', mStr); } } } // first, if it was a scale of a non-skewed element, then the second-last // transform will be the [S] // if we had [M][T][S][T] we want to extract the matrix equivalent of // [T][S][T] and push it down to the element if (_N >= 3 && tlist.getItem(_N - 2).type === 3 && tlist.getItem(_N - 3).type === 2 && tlist.getItem(_N - 1).type === 2) { // Removed this so a <use> with a given [T][S][T] would convert to a matrix. // Is that bad? // && selected.nodeName != 'use' _operation = 3; // scale _m5 = transformListToTransform(tlist, _N - 3, _N - 1).matrix; tlist.removeItem(_N - 1); tlist.removeItem(_N - 2); tlist.removeItem(_N - 3); // if we had [T][S][-T][M], then this was a skewed element being resized // Thus, we simply combine it all into one matrix } else if (_N === 4 && tlist.getItem(_N - 1).type === 1) { _operation = 3; // scale _m5 = transformListToTransform(tlist).matrix; var _e2t2 = svgroot.createSVGTransform(); _e2t2.setMatrix(_m5); tlist.clear(); tlist.appendItem(_e2t2); // reset the matrix so that the element is not re-mapped _m5 = svgroot.createSVGMatrix(); // if we had [R][T][S][-T][M], then this was a rotated matrix-element // if we had [T1][M] we want to transform this into [M][T2] // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2] // down to the element } else if ((_N === 1 || _N > 1 && tlist.getItem(1).type !== 3) && tlist.getItem(0).type === 2) { _operation = 2; // translate var oldxlate = tlist.getItem(0).matrix, meq = transformListToTransform(tlist, 1).matrix, meqInv = meq.inverse(); _m5 = matrixMultiply(meqInv, oldxlate, meq); tlist.removeItem(0); // else if this child now has a matrix imposition (from a parent group) // we might be able to simplify } else if (_N === 1 && tlist.getItem(0).type === 1 && !_angle) { // Remap all point-based elements _m5 = transformListToTransform(tlist).matrix; switch (selected.tagName) { case 'line': changes = $$9(selected).attr(['x1', 'y1', 'x2', 'y2']); // Fallthrough case 'polyline': case 'polygon': changes.points = selected.getAttribute('points'); if (changes.points) { var _list = selected.points; var _len = _list.numberOfItems; changes.points = new Array(_len); for (var _i3 = 0; _i3 < _len; ++_i3) { var _pt = _list.getItem(_i3); changes.points[_i3] = { x: _pt.x, y: _pt.y }; } } // Fallthrough case 'path': changes.d = selected.getAttribute('d'); _operation = 1; tlist.clear(); break; } // if it was a rotation, put the rotate back and return without a command // (this function has zero work to do for a rotate()) } else { // operation = 4; // rotation if (_angle) { var _newRot2 = svgroot.createSVGTransform(); _newRot2.setRotate(_angle, newcenter.x, newcenter.y); if (tlist.numberOfItems) { tlist.insertItemBefore(_newRot2, 0); } else { tlist.appendItem(_newRot2); } } if (tlist.numberOfItems === 0) { selected.removeAttribute('transform'); } return null; } // if it was a translate or resize, we need to remap the element and absorb the xform if (_operation === 1 || _operation === 2 || _operation === 3) { remapElement(selected, changes, _m5); } // if we are remapping // if it was a translate, put back the rotate at the new center if (_operation === 2) { if (_angle) { if (!hasMatrixTransform(tlist)) { newcenter = { x: oldcenter.x + _m5.e, y: oldcenter.y + _m5.f }; } var _newRot3 = svgroot.createSVGTransform(); _newRot3.setRotate(_angle, newcenter.x, newcenter.y); if (tlist.numberOfItems) { tlist.insertItemBefore(_newRot3, 0); } else { tlist.appendItem(_newRot3); } } // We have special processing for tspans: Tspans are not transformable // but they can have x,y coordinates (sigh). Thus, if this was a translate, // on a text element, also translate any tspan children. if (selected.tagName === 'text') { var _children4 = selected.childNodes; var _c4 = _children4.length; while (_c4--) { var _child4 = _children4.item(_c4); if (_child4.tagName === 'tspan') { var tspanChanges = { x: $$9(_child4).attr('x') || 0, y: $$9(_child4).attr('y') || 0 }; remapElement(_child4, tspanChanges, _m5); } } } // [Rold][M][T][S][-T] became [Rold][M] // we want it to be [Rnew][M][Tr] where Tr is the // translation required to re-center it // Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M] } else if (_operation === 3 && _angle) { var _transformListToTrans = transformListToTransform(tlist), matrix = _transformListToTrans.matrix; var _roldt = svgroot.createSVGTransform(); _roldt.setRotate(_angle, oldcenter.x, oldcenter.y); var _rold = _roldt.matrix; var _rnew = svgroot.createSVGTransform(); _rnew.setRotate(_angle, newcenter.x, newcenter.y); var _rnewInv = _rnew.matrix.inverse(); var _mInv2 = matrix.inverse(); var _extrat = matrixMultiply(_mInv2, _rnewInv, _rold, matrix); remapElement(selected, changes, _extrat); if (_angle) { if (tlist.numberOfItems) { tlist.insertItemBefore(_rnew, 0); } else { tlist.appendItem(_rnew); } } } } // a non-group // if the transform list has been emptied, remove it if (tlist.numberOfItems === 0) { selected.removeAttribute('transform'); } batchCmd.addSubCommand(new ChangeElementCommand(selected, initial)); return batchCmd; }; var $$a = jQuery; var svgFactory_; var config_; var selectorManager_; // A Singleton var gripRadius = isTouch() ? 10 : 4; /** * Private class for DOM element selection boxes. */ var Selector = /*#__PURE__*/function () { /** * @param {Integer} id - Internally identify the selector * @param {Element} elem - DOM element associated with this selector * @param {module:utilities.BBoxObject} [bbox] - Optional bbox to use for initialization (prevents duplicate `getBBox` call). */ function Selector(id, elem, bbox) { _classCallCheck(this, Selector); // this is the selector's unique number this.id = id; // this holds a reference to the element for which this selector is being used this.selectedElement = elem; // this is a flag used internally to track whether the selector is being used or not this.locked = true; // this holds a reference to the <g> element that holds all visual elements of the selector this.selectorGroup = svgFactory_.createSVGElement({ element: 'g', attr: { id: 'selectorGroup' + this.id } }); // this holds a reference to the path rect this.selectorRect = this.selectorGroup.appendChild(svgFactory_.createSVGElement({ element: 'path', attr: { id: 'selectedBox' + this.id, fill: 'none', stroke: '#22C', 'stroke-width': '1', 'stroke-dasharray': '5,5', // need to specify this so that the rect is not selectable style: 'pointer-events:none' } })); // this holds a reference to the grip coordinates for this selector this.gripCoords = { nw: null, n: null, ne: null, e: null, se: null, s: null, sw: null, w: null }; this.reset(this.selectedElement, bbox); } /** * Used to reset the id and element that the selector is attached to. * @param {Element} e - DOM element associated with this selector * @param {module:utilities.BBoxObject} bbox - Optional bbox to use for reset (prevents duplicate getBBox call). * @returns {void} */ _createClass(Selector, [{ key: "reset", value: function reset(e, bbox) { this.locked = true; this.selectedElement = e; this.resize(bbox); this.selectorGroup.setAttribute('display', 'inline'); } /** * Show the resize grips of this selector. * @param {boolean} show - Indicates whether grips should be shown or not * @returns {void} */ }, { key: "showGrips", value: function showGrips(show) { var bShow = show ? 'inline' : 'none'; selectorManager_.selectorGripsGroup.setAttribute('display', bShow); var elem = this.selectedElement; this.hasGrips = show; if (elem && show) { this.selectorGroup.append(selectorManager_.selectorGripsGroup); Selector.updateGripCursors(getRotationAngle(elem)); } } /** * Updates the selector to match the element's size. * @param {module:utilities.BBoxObject} [bbox] - BBox to use for resize (prevents duplicate getBBox call). * @returns {void} */ }, { key: "resize", value: function resize(bbox) { var selectedBox = this.selectorRect, mgr = selectorManager_, selectedGrips = mgr.selectorGrips, selected = this.selectedElement, sw = selected.getAttribute('stroke-width'), currentZoom = svgFactory_.getCurrentZoom(); var offset = 1 / currentZoom; if (selected.getAttribute('stroke') !== 'none' && !isNaN(sw)) { offset += sw / 2; } var tagName = selected.tagName; if (tagName === 'text') { offset += 2 / currentZoom; } // loop and transform our bounding box until we reach our first rotation var tlist = getTransformList(selected); var m = transformListToTransform(tlist).matrix; // This should probably be handled somewhere else, but for now // it keeps the selection box correctly positioned when zoomed m.e *= currentZoom; m.f *= currentZoom; if (!bbox) { bbox = getBBox(selected); } // TODO: getBBox (previous line) already knows to call getStrokedBBox when tagName === 'g'. Remove this? // TODO: getBBox doesn't exclude 'gsvg' and calls getStrokedBBox for any 'g'. Should getBBox be updated? if (tagName === 'g' && !$$a.data(selected, 'gsvg')) { // The bbox for a group does not include stroke vals, so we // get the bbox based on its children. var strokedBbox = getStrokedBBox([selected.childNodes]); if (strokedBbox) { bbox = strokedBbox; } } // apply the transforms var l = bbox.x, t = bbox.y, w = bbox.width, h = bbox.height; // bbox = {x: l, y: t, width: w, height: h}; // Not in use // we need to handle temporary transforms too // if skewed, get its transformed box, then find its axis-aligned bbox // * offset *= currentZoom; var nbox = transformBox(l * currentZoom, t * currentZoom, w * currentZoom, h * currentZoom, m), aabox = nbox.aabox; var nbax = aabox.x - offset, nbay = aabox.y - offset, nbaw = aabox.width + offset * 2, nbah = aabox.height + offset * 2; // now if the shape is rotated, un-rotate it var cx = nbax + nbaw / 2, cy = nbay + nbah / 2; var angle = getRotationAngle(selected); if (angle) { var rot = svgFactory_.svgRoot().createSVGTransform(); rot.setRotate(-angle, cx, cy); var rotm = rot.matrix; nbox.tl = transformPoint(nbox.tl.x, nbox.tl.y, rotm); nbox.tr = transformPoint(nbox.tr.x, nbox.tr.y, rotm); nbox.bl = transformPoint(nbox.bl.x, nbox.bl.y, rotm); nbox.br = transformPoint(nbox.br.x, nbox.br.y, rotm); // calculate the axis-aligned bbox var tl = nbox.tl; var minx = tl.x, miny = tl.y, maxx = tl.x, maxy = tl.y; var min = Math.min, max = Math.max; minx = min(minx, min(nbox.tr.x, min(nbox.bl.x, nbox.br.x))) - offset; miny = min(miny, min(nbox.tr.y, min(nbox.bl.y, nbox.br.y))) - offset; maxx = max(maxx, max(nbox.tr.x, max(nbox.bl.x, nbox.br.x))) + offset; maxy = max(maxy, max(nbox.tr.y, max(nbox.bl.y, nbox.br.y))) + offset; nbax = minx; nbay = miny; nbaw = maxx - minx; nbah = maxy - miny; } var dstr = 'M' + nbax + ',' + nbay + ' L' + (nbax + nbaw) + ',' + nbay + ' ' + (nbax + nbaw) + ',' + (nbay + nbah) + ' ' + nbax + ',' + (nbay + nbah) + 'z'; selectedBox.setAttribute('d', dstr); var xform = angle ? 'rotate(' + [angle, cx, cy].join(',') + ')' : ''; this.selectorGroup.setAttribute('transform', xform); // TODO(codedread): Is this needed? // if (selected === selectedElements[0]) { this.gripCoords = { nw: [nbax, nbay], ne: [nbax + nbaw, nbay], sw: [nbax, nbay + nbah], se: [nbax + nbaw, nbay + nbah], n: [nbax + nbaw / 2, nbay], w: [nbax, nbay + nbah / 2], e: [nbax + nbaw, nbay + nbah / 2], s: [nbax + nbaw / 2, nbay + nbah] }; Object.entries(this.gripCoords).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), dir = _ref2[0], coords = _ref2[1]; selectedGrips[dir].setAttribute('cx', coords[0]); selectedGrips[dir].setAttribute('cy', coords[1]); }); // we want to go 20 pixels in the negative transformed y direction, ignoring scale mgr.rotateGripConnector.setAttribute('x1', nbax + nbaw / 2); mgr.rotateGripConnector.setAttribute('y1', nbay); mgr.rotateGripConnector.setAttribute('x2', nbax + nbaw / 2); mgr.rotateGripConnector.setAttribute('y2', nbay - gripRadius * 5); mgr.rotateGrip.setAttribute('cx', nbax + nbaw / 2); mgr.rotateGrip.setAttribute('cy', nbay - gripRadius * 5); // } } // STATIC methods /** * Updates cursors for corner grips on rotation so arrows point the right way. * @param {Float} angle - Current rotation angle in degrees * @returns {void} */ }], [{ key: "updateGripCursors", value: function updateGripCursors(angle) { var dirArr = Object.keys(selectorManager_.selectorGrips); var steps = Math.round(angle / 45); if (steps < 0) { steps += 8; } while (steps > 0) { dirArr.push(dirArr.shift()); steps--; } Object.values(selectorManager_.selectorGrips).forEach(function (gripElement, i) { gripElement.setAttribute('style', 'cursor:' + dirArr[i] + '-resize'); }); } }]); return Selector; }(); /** * Manage all selector objects (selection boxes). */ var SelectorManager = /*#__PURE__*/function () { /** * Sets up properties and calls `initGroup`. */ function SelectorManager() { _classCallCheck(this, SelectorManager); // this will hold the <g> element that contains all selector rects/grips this.selectorParentGroup = null; // this is a special rect that is used for multi-select this.rubberBandBox = null; // this will hold objects of type Selector (see above) this.selectors = []; // this holds a map of SVG elements to their Selector object this.selectorMap = {}; // this holds a reference to the grip elements this.selectorGrips = { nw: null, n: null, ne: null, e: null, se: null, s: null, sw: null, w: null }; this.selectorGripsGroup = null; this.rotateGripConnector = null; this.rotateGrip = null; this.initGroup(); } /** * Resets the parent selector group element. * @returns {void} */ _createClass(SelectorManager, [{ key: "initGroup", value: function initGroup() { var _this = this; // remove old selector parent group if it existed if (this.selectorParentGroup && this.selectorParentGroup.parentNode) { this.selectorParentGroup.remove(); } // create parent selector group and add it to svgroot this.selectorParentGroup = svgFactory_.createSVGElement({ element: 'g', attr: { id: 'selectorParentGroup' } }); this.selectorGripsGroup = svgFactory_.createSVGElement({ element: 'g', attr: { display: 'none' } }); this.selectorParentGroup.append(this.selectorGripsGroup); svgFactory_.svgRoot().append(this.selectorParentGroup); this.selectorMap = {}; this.selectors = []; this.rubberBandBox = null; // add the corner grips Object.keys(this.selectorGrips).forEach(function (dir) { var grip = svgFactory_.createSVGElement({ element: 'circle', attr: { id: 'selectorGrip_resize_' + dir, fill: '#22C', r: gripRadius, style: 'cursor:' + dir + '-resize', // This expands the mouse-able area of the grips making them // easier to grab with the mouse. // This works in Opera and WebKit, but does not work in Firefox // see https://bugzilla.mozilla.org/show_bug.cgi?id=500174 'stroke-width': 2, 'pointer-events': 'all' } }); $$a.data(grip, 'dir', dir); $$a.data(grip, 'type', 'resize'); _this.selectorGrips[dir] = _this.selectorGripsGroup.appendChild(grip); }); // add rotator elems this.rotateGripConnector = this.selectorGripsGroup.appendChild(svgFactory_.createSVGElement({ element: 'line', attr: { id: 'selectorGrip_rotateconnector', stroke: '#22C', 'stroke-width': '1' } })); this.rotateGrip = this.selectorGripsGroup.appendChild(svgFactory_.createSVGElement({ element: 'circle', attr: { id: 'selectorGrip_rotate', fill: 'lime', r: gripRadius, stroke: '#22C', 'stroke-width': 2, style: 'cursor:url(' + config_.imgPath + 'rotate.png) 12 12, auto;' } })); $$a.data(this.rotateGrip, 'type', 'rotate'); if ($$a('#canvasBackground').length) { return; } var _config_$dimensions = _slicedToArray(config_.dimensions, 2), width = _config_$dimensions[0], height = _config_$dimensions[1]; var canvasbg = svgFactory_.createSVGElement({ element: 'svg', attr: { id: 'canvasBackground', width: width, height: height, x: 0, y: 0, overflow: isWebkit() ? 'none' : 'visible', // Chrome 7 has a problem with this when zooming out style: 'pointer-events:none' } }); var rect = svgFactory_.createSVGElement({ element: 'rect', attr: { width: '100%', height: '100%', x: 0, y: 0, 'stroke-width': 1, stroke: '#000', fill: '#FFF', style: 'pointer-events:none' } }); // Both Firefox and WebKit are too slow with this filter region (especially at higher // zoom levels) and Opera has at least one bug // if (!isOpera()) rect.setAttribute('filter', 'url(#canvashadow)'); canvasbg.append(rect); svgFactory_.svgRoot().insertBefore(canvasbg, svgFactory_.svgContent()); // Ok to replace above with `svgFactory_.svgContent().before(canvasbg);`? } /** * * @param {Element} elem - DOM element to get the selector for * @param {module:utilities.BBoxObject} [bbox] - Optional bbox to use for reset (prevents duplicate getBBox call). * @returns {Selector} The selector based on the given element */ }, { key: "requestSelector", value: function requestSelector(elem, bbox) { if (isNullish(elem)) { return null; } var N = this.selectors.length; // If we've already acquired one for this element, return it. if (_typeof(this.selectorMap[elem.id]) === 'object') { this.selectorMap[elem.id].locked = true; return this.selectorMap[elem.id]; } for (var i = 0; i < N; ++i) { if (this.selectors[i] && !this.selectors[i].locked) { this.selectors[i].locked = true; this.selectors[i].reset(elem, bbox); this.selectorMap[elem.id] = this.selectors[i]; return this.selectors[i]; } } // if we reached here, no available selectors were found, we create one this.selectors[N] = new Selector(N, elem, bbox); this.selectorParentGroup.append(this.selectors[N].selectorGroup); this.selectorMap[elem.id] = this.selectors[N]; return this.selectors[N]; } /** * Removes the selector of the given element (hides selection box). * * @param {Element} elem - DOM element to remove the selector for * @returns {void} */ }, { key: "releaseSelector", value: function releaseSelector(elem) { if (isNullish(elem)) { return; } var N = this.selectors.length, sel = this.selectorMap[elem.id]; if (!sel.locked) { // TODO(codedread): Ensure this exists in this module. console.log('WARNING! selector was released but was already unlocked'); // eslint-disable-line no-console } for (var i = 0; i < N; ++i) { if (this.selectors[i] && this.selectors[i] === sel) { delete this.selectorMap[elem.id]; sel.locked = false; sel.selectedElement = null; sel.showGrips(false); // remove from DOM and store reference in JS but only if it exists in the DOM try { sel.selectorGroup.setAttribute('display', 'none'); } catch (e) {} break; } } } /** * @returns {SVGRectElement} The rubberBandBox DOM element. This is the rectangle drawn by * the user for selecting/zooming */ }, { key: "getRubberBandBox", value: function getRubberBandBox() { if (!this.rubberBandBox) { this.rubberBandBox = this.selectorParentGroup.appendChild(svgFactory_.createSVGElement({ element: 'rect', attr: { id: 'selectorRubberBand', fill: '#22C', 'fill-opacity': 0.15, stroke: '#22C', 'stroke-width': 0.5, display: 'none', style: 'pointer-events:none' } })); } return this.rubberBandBox; } }]); return SelectorManager; }(); /** * An object that creates SVG elements for the canvas. * * @interface module:select.SVGFactory */ /** * @function module:select.SVGFactory#createSVGElement * @param {module:utilities.EditorContext#addSVGElementFromJson} jsonMap * @returns {SVGElement} */ /** * @function module:select.SVGFactory#svgRoot * @returns {SVGSVGElement} */ /** * @function module:select.SVGFactory#svgContent * @returns {SVGSVGElement} */ /** * @function module:select.SVGFactory#getCurrentZoom * @returns {Float} The current zoom level */ /** * @typedef {GenericArray} module:select.Dimensions * @property {Integer} length 2 * @property {Float} 0 Width * @property {Float} 1 Height */ /** * @typedef {PlainObject} module:select.Config * @property {string} imgPath * @property {module:select.Dimensions} dimensions */ /** * Initializes this module. * @function module:select.init * @param {module:select.Config} config - An object containing configurable parameters (imgPath) * @param {module:select.SVGFactory} svgFactory - An object implementing the SVGFactory interface. * @returns {void} */ var init$6 = function init(config, svgFactory) { config_ = config; svgFactory_ = svgFactory; selectorManager_ = new SelectorManager(); }; /** * @function module:select.getSelectorManager * @returns {module:select.SelectorManager} The SelectorManager instance. */ var getSelectorManager = function getSelectorManager() { return selectorManager_; }; var $$b = jQueryPluginSVG(jQuery); var MoveElementCommand$1 = MoveElementCommand, InsertElementCommand$1 = InsertElementCommand, RemoveElementCommand$1 = RemoveElementCommand, ChangeElementCommand$1 = ChangeElementCommand, BatchCommand$1 = BatchCommand, UndoManager$1 = UndoManager, HistoryEventTypes$1 = HistoryEventTypes; if (!window.console) { window.console = {}; window.console.log = function (str) { /* */ }; window.console.dir = function (str) { /* */ }; } if (window.opera) { window.console.log = function (str) { window.opera.postError(str); }; window.console.dir = function (str) { /* */ }; } // Reenable after fixing eslint-plugin-jsdoc to handle /** * The main SvgCanvas class that manages all SVG-related functions. * @memberof module:svgcanvas * * @borrows module:coords.remapElement as #remapElement * @borrows module:recalculate.recalculateDimensions as #recalculateDimensions * * @borrows module:utilities.cleanupElement as #cleanupElement * @borrows module:utilities.getStrokedBBoxDefaultVisible as #getStrokedBBox * @borrows module:utilities.getVisibleElements as #getVisibleElements * @borrows module:utilities.findDefs as #findDefs * @borrows module:utilities.getUrlFromAttr as #getUrlFromAttr * @borrows module:utilities.getHref as #getHref * @borrows module:utilities.setHref as #setHref * @borrows module:utilities.getRotationAngle as #getRotationAngle * @borrows module:utilities.getBBox as #getBBox * @borrows module:utilities.getElem as #getElem * @borrows module:utilities.getRefElem as #getRefElem * @borrows module:utilities.assignAttributes as #assignAttributes * * @borrows module:SVGTransformList.getTransformList as #getTransformList * @borrows module:math.matrixMultiply as #matrixMultiply * @borrows module:math.hasMatrixTransform as #hasMatrixTransform * @borrows module:math.transformListToTransform as #transformListToTransform * @borrows module:units.convertToNum as #convertToNum * @borrows module:sanitize.sanitizeSvg as #sanitizeSvg * @borrows module:path.pathActions.linkControlPoints as #linkControlPoints */ var SvgCanvas = /** * @param {HTMLElement} container - The container HTML element that should hold the SVG root element * @param {module:SVGEditor.curConfig} config - An object that contains configuration data */ function SvgCanvas(container, config) { _classCallCheck(this, SvgCanvas); // Alias Namespace constants // Default configuration options var curConfig = { show_outside_canvas: true, selectNew: true, dimensions: [640, 480] }; // Update config with new one if given if (config) { $$b.extend(curConfig, config); } // Array with width/height of canvas var dimensions = curConfig.dimensions; var canvas = this; // "document" element associated with the container (same as window.document using default svg-editor.js) // NOTE: This is not actually a SVG document, but an HTML document. // JFH const svgdoc = container.ownerDocument; var svgdoc = window.document; // This is a container for the document being edited, not the document itself. /** * @name module:svgcanvas~svgroot * @type {SVGSVGElement} */ var svgroot = svgdoc.importNode(text2xml('<svg id="svgroot" xmlns="' + NS.SVG + '" xlinkns="' + NS.XLINK + '" ' + 'width="' + dimensions[0] + '" height="' + dimensions[1] + '" x="' + dimensions[0] + '" y="' + dimensions[1] + '" overflow="visible">' + '<defs>' + '<filter id="canvashadow" filterUnits="objectBoundingBox">' + '<feGaussianBlur in="SourceAlpha" stdDeviation="4" result="blur"/>' + '<feOffset in="blur" dx="5" dy="5" result="offsetBlur"/>' + '<feMerge>' + '<feMergeNode in="offsetBlur"/>' + '<feMergeNode in="SourceGraphic"/>' + '</feMerge>' + '</filter>' + '</defs>' + '</svg>').documentElement, true); container.append(svgroot); /** * The actual element that represents the final output SVG element. * @name module:svgcanvas~svgcontent * @type {SVGSVGElement} */ var svgcontent = svgdoc.createElementNS(NS.SVG, 'svg'); /** * This function resets the svgcontent element while keeping it in the DOM. * @function module:svgcanvas.SvgCanvas#clearSvgContentElement * @returns {void} */ var clearSvgContentElement = canvas.clearSvgContentElement = function () { $$b(svgcontent).empty(); // TODO: Clear out all other attributes first? $$b(svgcontent).attr({ id: 'svgcontent', width: dimensions[0], height: dimensions[1], x: dimensions[0], y: dimensions[1], overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden', xmlns: NS.SVG, 'xmlns:se': NS.SE, 'xmlns:xlink': NS.XLINK }).appendTo(svgroot); // TODO: make this string optional and set by the client var comment = svgdoc.createComment(' Created with SVG-edit - https://github.com/SVG-Edit/svgedit'); svgcontent.append(comment); }; clearSvgContentElement(); // Prefix string for element IDs var idprefix = 'svg_'; /** * Changes the ID prefix to the given value. * @function module:svgcanvas.SvgCanvas#setIdPrefix * @param {string} p - String with the new prefix * @returns {void} */ canvas.setIdPrefix = function (p) { idprefix = p; }; /** * Current `draw.Drawing` object. * @type {module:draw.Drawing} * @name module:svgcanvas.SvgCanvas#current_drawing_ */ canvas.current_drawing_ = new Drawing(svgcontent, idprefix); /** * Returns the current Drawing. * @name module:svgcanvas.SvgCanvas#getCurrentDrawing * @type {module:draw.DrawCanvasInit#getCurrentDrawing} */ var getCurrentDrawing = canvas.getCurrentDrawing = function () { return canvas.current_drawing_; }; /** * Float displaying the current zoom level (1 = 100%, .5 = 50%, etc.). * @type {Float} */ var currentZoom = 1; // pointer to current group (for in-group editing) var currentGroup = null; // Object containing data for the currently selected styles var allProperties = { shape: { fill: (curConfig.initFill.color === 'none' ? '' : '#') + curConfig.initFill.color, fill_paint: null, fill_opacity: curConfig.initFill.opacity, stroke: '#' + curConfig.initStroke.color, stroke_paint: null, stroke_opacity: curConfig.initStroke.opacity, stroke_width: curConfig.initStroke.width, stroke_dasharray: 'none', stroke_linejoin: 'miter', stroke_linecap: 'butt', opacity: curConfig.initOpacity } }; allProperties.text = $$b.extend(true, {}, allProperties.shape); $$b.extend(allProperties.text, { fill: '#000000', stroke_width: curConfig.text && curConfig.text.stroke_width, font_size: curConfig.text && curConfig.text.font_size, font_family: curConfig.text && curConfig.text.font_family }); // Current shape style properties var curShape = allProperties.shape; // Array with all the currently selected elements // default size of 1 until it needs to grow bigger var selectedElements = []; /** * @typedef {PlainObject} module:svgcanvas.SVGAsJSON * @property {string} element * @property {PlainObject<string, string>} attr * @property {module:svgcanvas.SVGAsJSON[]} children */ /** * @function module:svgcanvas.SvgCanvas#getContentElem * @param {Text|Element} data * @returns {module:svgcanvas.SVGAsJSON} */ var getJsonFromSvgElement = this.getJsonFromSvgElement = function (data) { // Text node if (data.nodeType === 3) return data.nodeValue; var retval = { element: data.tagName, // namespace: nsMap[data.namespaceURI], attr: {}, children: [] }; // Iterate attributes for (var i = 0, attr; attr = data.attributes[i]; i++) { retval.attr[attr.name] = attr.value; } // Iterate children for (var _i = 0, node; node = data.childNodes[_i]; _i++) { retval.children[_i] = getJsonFromSvgElement(node); } return retval; }; /** * This should really be an intersection implementing all rather than a union. * @name module:svgcanvas.SvgCanvas#addSVGElementFromJson * @type {module:utilities.EditorContext#addSVGElementFromJson|module:path.EditorContext#addSVGElementFromJson} */ var addSVGElementFromJson = this.addSVGElementFromJson = function (data) { if (typeof data === 'string') return svgdoc.createTextNode(data); var shape = getElem(data.attr.id); // if shape is a path but we need to create a rect/ellipse, then remove the path var currentLayer = getCurrentDrawing().getCurrentLayer(); if (shape && data.element !== shape.tagName) { shape.remove(); shape = null; } if (!shape) { var ns = data.namespace || NS.SVG; shape = svgdoc.createElementNS(ns, data.element); if (currentLayer) { (currentGroup || currentLayer).append(shape); } } if (data.curStyles) { assignAttributes(shape, { fill: curShape.fill, stroke: curShape.stroke, 'stroke-width': curShape.stroke_width, 'stroke-dasharray': curShape.stroke_dasharray, 'stroke-linejoin': curShape.stroke_linejoin, 'stroke-linecap': curShape.stroke_linecap, 'stroke-opacity': curShape.stroke_opacity, 'fill-opacity': curShape.fill_opacity, opacity: curShape.opacity / 2, style: 'pointer-events:inherit' }); } assignAttributes(shape, data.attr); cleanupElement(shape); // Children if (data.children) { data.children.forEach(function (child) { shape.append(addSVGElementFromJson(child)); }); } return shape; }; canvas.getTransformList = getTransformList; canvas.matrixMultiply = matrixMultiply; canvas.hasMatrixTransform = hasMatrixTransform; canvas.transformListToTransform = transformListToTransform; /** * @type {module:utilities.EditorContext#getBaseUnit} */ var getBaseUnit = function getBaseUnit() { return curConfig.baseUnit; }; /** * Initialize from units.js. * Send in an object implementing the ElementContainer interface (see units.js). */ init( /** * @implements {module:units.ElementContainer} */ { getBaseUnit: getBaseUnit, getElement: getElem, getHeight: function getHeight() { return svgcontent.getAttribute('height') / currentZoom; }, getWidth: function getWidth() { return svgcontent.getAttribute('width') / currentZoom; }, getRoundDigits: function getRoundDigits() { return saveOptions.round_digits; } }); canvas.convertToNum = convertToNum; /** * This should really be an intersection implementing all rather than a union. * @type {module:draw.DrawCanvasInit#getSVGContent|module:utilities.EditorContext#getSVGContent} */ var getSVGContent = function getSVGContent() { return svgcontent; }; /** * Should really be an intersection with all needing to apply rather than a union. * @name module:svgcanvas.SvgCanvas#getSelectedElements * @type {module:utilities.EditorContext#getSelectedElements|module:draw.DrawCanvasInit#getSelectedElements|module:path.EditorContext#getSelectedElements} */ var getSelectedElements = this.getSelectedElems = function () { return selectedElements; }; var pathActions$1 = pathActions; /** * This should actually be an intersection as all interfaces should be met. * @type {module:utilities.EditorContext#getSVGRoot|module:recalculate.EditorContext#getSVGRoot|module:coords.EditorContext#getSVGRoot|module:path.EditorContext#getSVGRoot} */ var getSVGRoot = function getSVGRoot() { return svgroot; }; init$1( /** * @implements {module:utilities.EditorContext} */ { pathActions: pathActions$1, // Ok since not modifying getSVGContent: getSVGContent, addSVGElementFromJson: addSVGElementFromJson, getSelectedElements: getSelectedElements, getDOMDocument: function getDOMDocument() { return svgdoc; }, getDOMContainer: function getDOMContainer() { return container; }, getSVGRoot: getSVGRoot, // TODO: replace this mostly with a way to get the current drawing. getBaseUnit: getBaseUnit, getSnappingStep: function getSnappingStep() { return curConfig.snappingStep; } }); canvas.findDefs = findDefs; canvas.getUrlFromAttr = getUrlFromAttr; canvas.getHref = getHref; canvas.setHref = setHref; /* const getBBox = */ canvas.getBBox = getBBox; canvas.getRotationAngle = getRotationAngle; canvas.getElem = getElem; canvas.getRefElem = getRefElem; canvas.assignAttributes = assignAttributes; this.cleanupElement = cleanupElement; /** * This should actually be an intersection not a union as all should apply. * @type {module:coords.EditorContext#getGridSnapping|module:path.EditorContext#getGridSnapping} */ var getGridSnapping = function getGridSnapping() { return curConfig.gridSnapping; }; init$4( /** * @implements {module:coords.EditorContext} */ { getDrawing: function getDrawing() { return getCurrentDrawing(); }, getSVGRoot: getSVGRoot, getGridSnapping: getGridSnapping }); this.remapElement = remapElement; init$5( /** * @implements {module:recalculate.EditorContext} */ { getSVGRoot: getSVGRoot, getStartTransform: function getStartTransform() { return startTransform; }, setStartTransform: function setStartTransform(transform) { startTransform = transform; } }); this.recalculateDimensions = recalculateDimensions; // import from sanitize.js var nsMap = getReverseNS(); canvas.sanitizeSvg = sanitizeSvg; /** * @name undoMgr * @memberof module:svgcanvas.SvgCanvas# * @type {module:history.HistoryEventHandler} */ var undoMgr = canvas.undoMgr = new UndoManager$1({ /** * @param {string} eventType One of the HistoryEvent types * @param {module:history.HistoryCommand} cmd Fulfills the HistoryCommand interface * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ handleHistoryEvent: function handleHistoryEvent(eventType, cmd) { var EventTypes = HistoryEventTypes$1; // TODO: handle setBlurOffsets. if (eventType === EventTypes.BEFORE_UNAPPLY || eventType === EventTypes.BEFORE_APPLY) { canvas.clearSelection(); } else if (eventType === EventTypes.AFTER_APPLY || eventType === EventTypes.AFTER_UNAPPLY) { var elems = cmd.elements(); canvas.pathActions.clear(); call('changed', elems); var cmdType = cmd.type(); var isApply = eventType === EventTypes.AFTER_APPLY; if (cmdType === 'MoveElementCommand') { var parent = isApply ? cmd.newParent : cmd.oldParent; if (parent === svgcontent) { identifyLayers(); } } else if (cmdType === 'InsertElementCommand' || cmdType === 'RemoveElementCommand') { if (cmd.parent === svgcontent) { identifyLayers(); } if (cmdType === 'InsertElementCommand') { if (isApply) { restoreRefElems(cmd.elem); } } else if (!isApply) { restoreRefElems(cmd.elem); } if (cmd.elem && cmd.elem.tagName === 'use') { setUseData(cmd.elem); } } else if (cmdType === 'ChangeElementCommand') { // if we are changing layer names, re-identify all layers if (cmd.elem.tagName === 'title' && cmd.elem.parentNode.parentNode === svgcontent) { identifyLayers(); } var values = isApply ? cmd.newValues : cmd.oldValues; // If stdDeviation was changed, update the blur. if (values.stdDeviation) { canvas.setBlurOffsets(cmd.elem.parentNode, values.stdDeviation); } // This is resolved in later versions of webkit, perhaps we should // have a featured detection for correct 'use' behavior? // —————————— // Remove & Re-add hack for Webkit (issue 775) // if (cmd.elem.tagName === 'use' && isWebkit()) { // const {elem} = cmd; // if (!elem.getAttribute('x') && !elem.getAttribute('y')) { // const parent = elem.parentNode; // const sib = elem.nextSibling; // elem.remove(); // parent.insertBefore(elem, sib); // // Ok to replace above with this? `sib.before(elem);` // } // } } } } }); /** * This should really be an intersection applying to all types rather than a union. * @name module:svgcanvas~addCommandToHistory * @type {module:path.EditorContext#addCommandToHistory|module:draw.DrawCanvasInit#addCommandToHistory} */ var addCommandToHistory = function addCommandToHistory(cmd) { canvas.undoMgr.addCommandToHistory(cmd); }; /** * This should really be an intersection applying to all types rather than a union. * @name module:svgcanvas.SvgCanvas#getZoom * @type {module:path.EditorContext#getCurrentZoom|module:select.SVGFactory#getCurrentZoom} */ var getCurrentZoom = this.getZoom = function () { return currentZoom; }; /** * This method rounds the incoming value to the nearest value based on the `currentZoom` * @name module:svgcanvas.SvgCanvas#round * @type {module:path.EditorContext#round} */ var round = this.round = function (val) { return Number.parseInt(val * currentZoom) / currentZoom; }; init$6(curConfig, /** * Export to select.js. * @implements {module:select.SVGFactory} */ { createSVGElement: function createSVGElement(jsonMap) { return canvas.addSVGElementFromJson(jsonMap); }, svgRoot: function svgRoot() { return svgroot; }, svgContent: function svgContent() { return svgcontent; }, getCurrentZoom: getCurrentZoom }); /** * This object manages selectors for us. * @name module:svgcanvas.SvgCanvas#selectorManager * @type {module:select.SelectorManager} */ var selectorManager = this.selectorManager = getSelectorManager(); /** * @name module:svgcanvas.SvgCanvas#getNextId * @type {module:path.EditorContext#getNextId} */ var getNextId = canvas.getNextId = function () { return getCurrentDrawing().getNextId(); }; /** * @name module:svgcanvas.SvgCanvas#getId * @type {module:path.EditorContext#getId} */ var getId = canvas.getId = function () { return getCurrentDrawing().getId(); }; /** * The "implements" should really be an intersection applying to all types rather than a union. * @name module:svgcanvas.SvgCanvas#call * @type {module:draw.DrawCanvasInit#call|module:path.EditorContext#call} */ var call = function call(ev, arg) { if (events[ev]) { return events[ev](window, arg); } return undefined; }; /** * Clears the selection. The 'selected' handler is then optionally called. * This should really be an intersection applying to all types rather than a union. * @name module:svgcanvas.SvgCanvas#clearSelection * @type {module:draw.DrawCanvasInit#clearSelection|module:path.EditorContext#clearSelection} * @fires module:svgcanvas.SvgCanvas#event:selected */ var clearSelection = this.clearSelection = function (noCall) { selectedElements.forEach(function (elem) { if (isNullish(elem)) { return; } selectorManager.releaseSelector(elem); }); selectedElements = []; if (!noCall) { call('selected', selectedElements); } }; /** * Adds a list of elements to the selection. The 'selected' handler is then called. * @name module:svgcanvas.SvgCanvas#addToSelection * @type {module:path.EditorContext#addToSelection} * @fires module:svgcanvas.SvgCanvas#event:selected */ var addToSelection = this.addToSelection = function (elemsToAdd, showGrips) { if (!elemsToAdd.length) { return; } // find the first null in our selectedElements array var j = 0; while (j < selectedElements.length) { if (isNullish(selectedElements[j])) { break; } ++j; } // now add each element consecutively var i = elemsToAdd.length; while (i--) { var elem = elemsToAdd[i]; if (!elem) { continue; } var bbox = getBBox(elem); if (!bbox) { continue; } if (elem.tagName === 'a' && elem.childNodes.length === 1) { // Make "a" element's child be the selected element elem = elem.firstChild; } // if it's not already there, add it if (!selectedElements.includes(elem)) { selectedElements[j] = elem; // only the first selectedBBoxes element is ever used in the codebase these days // if (j === 0) selectedBBoxes[0] = utilsGetBBox(elem); j++; var sel = selectorManager.requestSelector(elem, bbox); if (selectedElements.length > 1) { sel.showGrips(false); } } } if (!selectedElements.length) { return; } call('selected', selectedElements); if (selectedElements.length === 1) { selectorManager.requestSelector(selectedElements[0]).showGrips(showGrips); } // make sure the elements are in the correct order // See: https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition selectedElements.sort(function (a, b) { if (a && b && a.compareDocumentPosition) { return 3 - (b.compareDocumentPosition(a) & 6); // eslint-disable-line no-bitwise } if (isNullish(a)) { return 1; } return 0; }); // Make sure first elements are not null while (isNullish(selectedElements[0])) { selectedElements.shift(0); } }; /** * @type {module:path.EditorContext#getOpacity} */ var getOpacity = function getOpacity() { return curShape.opacity; }; /** * @name module:svgcanvas.SvgCanvas#getMouseTarget * @type {module:path.EditorContext#getMouseTarget} */ var getMouseTarget = this.getMouseTarget = function (evt) { if (isNullish(evt)) { return null; } var mouseTarget = evt.target; // if it was a <use>, Opera and WebKit return the SVGElementInstance if (mouseTarget.correspondingUseElement) { mouseTarget = mouseTarget.correspondingUseElement; } // for foreign content, go up until we find the foreignObject // WebKit browsers set the mouse target to the svgcanvas div if ([NS.MATH, NS.HTML].includes(mouseTarget.namespaceURI) && mouseTarget.id !== 'svgcanvas') { while (mouseTarget.nodeName !== 'foreignObject') { mouseTarget = mouseTarget.parentNode; if (!mouseTarget) { return svgroot; } } } // Get the desired mouseTarget with jQuery selector-fu // If it's root-like, select the root var currentLayer = getCurrentDrawing().getCurrentLayer(); if ([svgroot, container, svgcontent, currentLayer].includes(mouseTarget)) { return svgroot; } var $target = $$b(mouseTarget); // If it's a selection grip, return the grip parent if ($target.closest('#selectorParentGroup').length) { // While we could instead have just returned mouseTarget, // this makes it easier to indentify as being a selector grip return selectorManager.selectorParentGroup; } while (mouseTarget.parentNode !== (currentGroup || currentLayer)) { mouseTarget = mouseTarget.parentNode; } // // // go up until we hit a child of a layer // while (mouseTarget.parentNode.parentNode.tagName == 'g') { // mouseTarget = mouseTarget.parentNode; // } // Webkit bubbles the mouse event all the way up to the div, so we // set the mouseTarget to the svgroot like the other browsers // if (mouseTarget.nodeName.toLowerCase() == 'div') { // mouseTarget = svgroot; // } return mouseTarget; }; /** * @namespace {module:path.pathActions} pathActions * @memberof module:svgcanvas.SvgCanvas# * @see module:path.pathActions */ canvas.pathActions = pathActions$1; /** * @type {module:path.EditorContext#resetD} */ function resetD(p) { p.setAttribute('d', pathActions$1.convertPath(p)); } init$2( /** * @implements {module:path.EditorContext} */ { selectorManager: selectorManager, // Ok since not changing canvas: canvas, // Ok since not changing call: call, resetD: resetD, round: round, clearSelection: clearSelection, addToSelection: addToSelection, addCommandToHistory: addCommandToHistory, remapElement: remapElement, addSVGElementFromJson: addSVGElementFromJson, getGridSnapping: getGridSnapping, getOpacity: getOpacity, getSelectedElements: getSelectedElements, getContainer: function getContainer() { return container; }, setStarted: function setStarted(s) { started = s; }, getRubberBox: function getRubberBox() { return rubberBox; }, setRubberBox: function setRubberBox(rb) { rubberBox = rb; return rubberBox; }, /** * @param {PlainObject} ptsInfo * @param {boolean} ptsInfo.closedSubpath * @param {SVGCircleElement[]} ptsInfo.grips * @fires module:svgcanvas.SvgCanvas#event:pointsAdded * @fires module:svgcanvas.SvgCanvas#event:selected * @returns {void} */ addPtsToSelection: function addPtsToSelection(_ref) { var closedSubpath = _ref.closedSubpath, grips = _ref.grips; // TODO: Correct this: pathActions$1.canDeleteNodes = true; pathActions$1.closed_subpath = closedSubpath; call('pointsAdded', { closedSubpath: closedSubpath, grips: grips }); call('selected', grips); }, /** * @param {PlainObject} changes * @param {ChangeElementCommand} changes.cmd * @param {SVGPathElement} changes.elem * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ endChanges: function endChanges(_ref2) { var cmd = _ref2.cmd, elem = _ref2.elem; addCommandToHistory(cmd); call('changed', [elem]); }, getCurrentZoom: getCurrentZoom, getId: getId, getNextId: getNextId, getMouseTarget: getMouseTarget, getCurrentMode: function getCurrentMode() { return currentMode; }, setCurrentMode: function setCurrentMode(cm) { currentMode = cm; return currentMode; }, getDrawnPath: function getDrawnPath() { return drawnPath; }, setDrawnPath: function setDrawnPath(dp) { drawnPath = dp; return drawnPath; }, getSVGRoot: getSVGRoot }); // Interface strings, usually for title elements var uiStrings = {}; var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'; var refAttrs = ['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke']; var elData = $$b.data; // Animation element to change the opacity of any newly created element var opacAni = document.createElementNS(NS.SVG, 'animate'); $$b(opacAni).attr({ attributeName: 'opacity', begin: 'indefinite', dur: 1, fill: 'freeze' }).appendTo(svgroot); var restoreRefElems = function restoreRefElems(elem) { // Look for missing reference elements, restore any found var attrs = $$b(elem).attr(refAttrs); Object.values(attrs).forEach(function (val) { if (val && val.startsWith('url(')) { var id = getUrlFromAttr(val).substr(1); var ref = getElem(id); if (!ref) { findDefs().append(removedElements[id]); delete removedElements[id]; } } }); var childs = elem.getElementsByTagName('*'); if (childs.length) { for (var i = 0, l = childs.length; i < l; i++) { restoreRefElems(childs[i]); } } }; // (function () { // TODO For Issue 208: this is a start on a thumbnail // const svgthumb = svgdoc.createElementNS(NS.SVG, 'use'); // svgthumb.setAttribute('width', '100'); // svgthumb.setAttribute('height', '100'); // setHref(svgthumb, '#svgcontent'); // svgroot.append(svgthumb); // }()); /** * @typedef {PlainObject} module:svgcanvas.SaveOptions * @property {boolean} apply * @property {"embed"} [image] * @property {Integer} round_digits */ // Object to contain image data for raster images that were found encodable var encodableImages = {}, // Object with save options /** * @type {module:svgcanvas.SaveOptions} */ saveOptions = { round_digits: 5 }, // Object with IDs for imported files, to see if one was already added importIds = {}, // Current text style properties curText = allProperties.text, // Object to contain all included extensions extensions = {}, // Map of deleted reference elements removedElements = {}; var // String with image URL of last loadable image lastGoodImgUrl = curConfig.imgPath + 'logo.png', // Boolean indicating whether or not a draw action has been started started = false, // String with an element's initial transform attribute value startTransform = null, // String indicating the current editor mode currentMode = 'select', // String with the current direction in which an element is being resized currentResizeMode = 'none', // Current general properties curProperties = curShape, // Array with selected elements' Bounding box object // selectedBBoxes = new Array(1), // The DOM element that was just selected justSelected = null, // DOM element for selection rectangle drawn by the user rubberBox = null, // Array of current BBoxes, used in getIntersectionList(). curBBoxes = [], // Canvas point for the most recent right click lastClickPoint = null; this.runExtension = function (name, action, vars) { return this.runExtensions(action, vars, false, function (n) { return n === name; }); }; /** * @typedef {module:svgcanvas.ExtensionMouseDownStatus|module:svgcanvas.ExtensionMouseUpStatus|module:svgcanvas.ExtensionIDsUpdatedStatus|module:locale.ExtensionLocaleData[]|void} module:svgcanvas.ExtensionStatus * @tutorial ExtensionDocs */ /** * @callback module:svgcanvas.ExtensionVarBuilder * @param {string} name The name of the extension * @returns {module:svgcanvas.SvgCanvas#event:ext_addLangData} */ /** * @callback module:svgcanvas.ExtensionNameFilter * @param {string} name * @returns {boolean} */ /** * @todo Consider: Should this return an array by default, so extension results aren't overwritten? * @todo Would be easier to document if passing in object with key of action and vars as value; could then define an interface which tied both together * @function module:svgcanvas.SvgCanvas#runExtensions * @param {"mouseDown"|"mouseMove"|"mouseUp"|"zoomChanged"|"IDsUpdated"|"canvasUpdated"|"toolButtonStateUpdate"|"selectedChanged"|"elementTransition"|"elementChanged"|"langReady"|"langChanged"|"addLangData"|"onNewDocument"|"workareaResized"} action * @param {module:svgcanvas.SvgCanvas#event:ext_mouseDown|module:svgcanvas.SvgCanvas#event:ext_mouseMove|module:svgcanvas.SvgCanvas#event:ext_mouseUp|module:svgcanvas.SvgCanvas#event:ext_zoomChanged|module:svgcanvas.SvgCanvas#event:ext_IDsUpdated|module:svgcanvas.SvgCanvas#event:ext_canvasUpdated|module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate|module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementTransition|module:svgcanvas.SvgCanvas#event:ext_elementChanged|module:svgcanvas.SvgCanvas#event:ext_langReady|module:svgcanvas.SvgCanvas#event:ext_langChanged|module:svgcanvas.SvgCanvas#event:ext_addLangData|module:svgcanvas.SvgCanvas#event:ext_onNewDocument|module:svgcanvas.SvgCanvas#event:ext_workareaResized|module:svgcanvas.ExtensionVarBuilder} [vars] * @param {boolean} [returnArray] * @param {module:svgcanvas.ExtensionNameFilter} nameFilter * @returns {GenericArray<module:svgcanvas.ExtensionStatus>|module:svgcanvas.ExtensionStatus|false} See {@tutorial ExtensionDocs} on the ExtensionStatus. */ var runExtensions = this.runExtensions = function (action, vars, returnArray, nameFilter) { var result = returnArray ? [] : false; $$b.each(extensions, function (name, ext) { if (nameFilter && !nameFilter(name)) { return; } if (ext && action in ext) { if (typeof vars === 'function') { vars = vars(name); // ext, action } if (returnArray) { result.push(ext[action](vars)); } else { result = ext[action](vars); } } }); return result; }; /** * @typedef {PlainObject} module:svgcanvas.ExtensionMouseDownStatus * @property {boolean} started Indicates that creating/editing has started */ /** * @typedef {PlainObject} module:svgcanvas.ExtensionMouseUpStatus * @property {boolean} keep Indicates if the current element should be kept * @property {boolean} started Indicates if editing should still be considered as "started" * @property {Element} element The element being affected */ /** * @typedef {PlainObject} module:svgcanvas.ExtensionIDsUpdatedStatus * @property {string[]} remove Contains string IDs (used by `ext-connector.js`) */ /** * @interface module:svgcanvas.ExtensionInitResponse * @property {module:SVGEditor.ContextTool[]|PlainObject<string, module:SVGEditor.ContextTool>} [context_tools] * @property {module:SVGEditor.Button[]|PlainObject<Integer, module:SVGEditor.Button>} [buttons] * @property {string} [svgicons] The location of a local SVG or SVGz file */ /** * @function module:svgcanvas.ExtensionInitResponse#mouseDown * @param {module:svgcanvas.SvgCanvas#event:ext_mouseDown} arg * @returns {void|module:svgcanvas.ExtensionMouseDownStatus} */ /** * @function module:svgcanvas.ExtensionInitResponse#mouseMove * @param {module:svgcanvas.SvgCanvas#event:ext_mouseMove} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#mouseUp * @param {module:svgcanvas.SvgCanvas#event:ext_mouseUp} arg * @returns {module:svgcanvas.ExtensionMouseUpStatus} */ /** * @function module:svgcanvas.ExtensionInitResponse#zoomChanged * @param {module:svgcanvas.SvgCanvas#event:ext_zoomChanged} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#IDsUpdated * @param {module:svgcanvas.SvgCanvas#event:ext_IDsUpdated} arg * @returns {module:svgcanvas.ExtensionIDsUpdatedStatus} */ /** * @function module:svgcanvas.ExtensionInitResponse#canvasUpdated * @param {module:svgcanvas.SvgCanvas#event:ext_canvasUpdated} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#toolButtonStateUpdate * @param {module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#selectedChanged * @param {module:svgcanvas.SvgCanvas#event:ext_selectedChanged} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#elementTransition * @param {module:svgcanvas.SvgCanvas#event:ext_elementTransition} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#elementChanged * @param {module:svgcanvas.SvgCanvas#event:ext_elementChanged} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#langReady * @param {module:svgcanvas.SvgCanvas#event:ext_langReady} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#langChanged * @param {module:svgcanvas.SvgCanvas#event:ext_langChanged} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#addLangData * @param {module:svgcanvas.SvgCanvas#event:ext_addLangData} arg * @returns {Promise<module:locale.ExtensionLocaleData>} Resolves to {@link module:locale.ExtensionLocaleData} */ /** * @function module:svgcanvas.ExtensionInitResponse#onNewDocument * @param {module:svgcanvas.SvgCanvas#event:ext_onNewDocument} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#workareaResized * @param {module:svgcanvas.SvgCanvas#event:ext_workareaResized} arg * @returns {void} */ /** * @function module:svgcanvas.ExtensionInitResponse#callback * @this module:SVGEditor * @param {module:svgcanvas.SvgCanvas#event:ext_callback} arg * @returns {void} */ /** * @callback module:svgcanvas.ExtensionInitCallback * @this module:SVGEditor * @param {module:svgcanvas.ExtensionArgumentObject} arg * @returns {Promise<module:svgcanvas.ExtensionInitResponse|void>} Resolves to [ExtensionInitResponse]{@link module:svgcanvas.ExtensionInitResponse} or `undefined` */ /** * @typedef {PlainObject} module:svgcanvas.ExtensionInitArgs * @property {external:jQuery} $ * @property {module:SVGEditor~ImportLocale} importLocale */ /** * Add an extension to the editor. * @function module:svgcanvas.SvgCanvas#addExtension * @param {string} name - String with the ID of the extension. Used internally; no need for i18n. * @param {module:svgcanvas.ExtensionInitCallback} [extInitFunc] - Function supplied by the extension with its data * @param {module:svgcanvas.ExtensionInitArgs} initArgs * @fires module:svgcanvas.SvgCanvas#event:extension_added * @throws {TypeError|Error} `TypeError` if `extInitFunc` is not a function, `Error` * if extension of supplied name already exists * @returns {Promise<void>} Resolves to `undefined` */ this.addExtension = /*#__PURE__*/function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(name, extInitFunc, _ref3) { var jq, importLocale, argObj, extObj; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: jq = _ref3.$, importLocale = _ref3.importLocale; if (!(typeof extInitFunc !== 'function')) { _context.next = 3; break; } throw new TypeError('Function argument expected for `svgcanvas.addExtension`'); case 3: if (!(name in extensions)) { _context.next = 5; break; } throw new Error('Cannot add extension "' + name + '", an extension by that name already exists.'); case 5: // Provide private vars/funcs here. Is there a better way to do this? /** * @typedef {module:svgcanvas.PrivateMethods} module:svgcanvas.ExtensionArgumentObject * @property {SVGSVGElement} svgroot See {@link module:svgcanvas~svgroot} * @property {SVGSVGElement} svgcontent See {@link module:svgcanvas~svgcontent} * @property {!(string|Integer)} nonce See {@link module:draw.Drawing#getNonce} * @property {module:select.SelectorManager} selectorManager * @property {module:SVGEditor~ImportLocale} importLocale */ /** * @type {module:svgcanvas.ExtensionArgumentObject} * @see {@link module:svgcanvas.PrivateMethods} source for the other methods/properties */ argObj = $$b.extend(canvas.getPrivateMethods(), { $: jq, importLocale: importLocale, svgroot: svgroot, svgcontent: svgcontent, nonce: getCurrentDrawing().getNonce(), selectorManager: selectorManager }); _context.next = 8; return extInitFunc(argObj); case 8: extObj = _context.sent; if (extObj) { extObj.name = name; } extensions[name] = extObj; return _context.abrupt("return", call('extension_added', extObj)); case 12: case "end": return _context.stop(); } } }, _callee); })); return function (_x, _x2, _x3) { return _ref4.apply(this, arguments); }; }(); /** * This method sends back an array or a NodeList full of elements that * intersect the multi-select rubber-band-box on the currentLayer only. * * We brute-force `getIntersectionList` for browsers that do not support it (Firefox). * * Reference: * Firefox does not implement `getIntersectionList()`, see {@link https://bugzilla.mozilla.org/show_bug.cgi?id=501421}. * @function module:svgcanvas.SvgCanvas#getIntersectionList * @param {SVGRect} rect * @returns {Element[]|NodeList} Bbox elements */ var getIntersectionList = this.getIntersectionList = function (rect) { if (isNullish(rubberBox)) { return null; } var parent = currentGroup || getCurrentDrawing().getCurrentLayer(); var rubberBBox; if (!rect) { rubberBBox = rubberBox.getBBox(); var bb = svgcontent.createSVGRect(); ['x', 'y', 'width', 'height', 'top', 'right', 'bottom', 'left'].forEach(function (o) { bb[o] = rubberBBox[o] / currentZoom; }); rubberBBox = bb; } else { rubberBBox = svgcontent.createSVGRect(); rubberBBox.x = rect.x; rubberBBox.y = rect.y; rubberBBox.width = rect.width; rubberBBox.height = rect.height; } var resultList = null; if (!isIE()) { if (typeof svgroot.getIntersectionList === 'function') { // Offset the bbox of the rubber box by the offset of the svgcontent element. rubberBBox.x += Number.parseInt(svgcontent.getAttribute('x')); rubberBBox.y += Number.parseInt(svgcontent.getAttribute('y')); resultList = svgroot.getIntersectionList(rubberBBox, parent); } } if (isNullish(resultList) || typeof resultList.item !== 'function') { resultList = []; if (!curBBoxes.length) { // Cache all bboxes curBBoxes = getVisibleElementsAndBBoxes(parent); } var i = curBBoxes.length; while (i--) { if (!rubberBBox.width) { continue; } if (rectsIntersect(rubberBBox, curBBoxes[i].bbox)) { resultList.push(curBBoxes[i].elem); } } } // addToSelection expects an array, but it's ok to pass a NodeList // because using square-bracket notation is allowed: // https://www.w3.org/TR/DOM-Level-2-Core/ecma-script-binding.html return resultList; }; this.getStrokedBBox = getStrokedBBoxDefaultVisible; this.getVisibleElements = getVisibleElements; /** * @typedef {PlainObject} ElementAndBBox * @property {Element} elem - The element * @property {module:utilities.BBoxObject} bbox - The element's BBox as retrieved from `getStrokedBBoxDefaultVisible` */ /** * Get all elements that have a BBox (excludes `<defs>`, `<title>`, etc). * Note that 0-opacity, off-screen etc elements are still considered "visible" * for this function. * @function module:svgcanvas.SvgCanvas#getVisibleElementsAndBBoxes * @param {Element} parent - The parent DOM element to search within * @returns {ElementAndBBox[]} An array with objects that include: */ var getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function (parent) { if (!parent) { parent = $$b(svgcontent).children(); // Prevent layers from being included } var contentElems = []; $$b(parent).children().each(function (i, elem) { if (elem.getBBox) { contentElems.push({ elem: elem, bbox: getStrokedBBoxDefaultVisible([elem]) }); } }); return contentElems.reverse(); }; /** * Wrap an SVG element into a group element, mark the group as 'gsvg'. * @function module:svgcanvas.SvgCanvas#groupSvgElem * @param {Element} elem - SVG element to wrap * @returns {void} */ var groupSvgElem = this.groupSvgElem = function (elem) { var g = document.createElementNS(NS.SVG, 'g'); elem.replaceWith(g); $$b(g).append(elem).data('gsvg', elem)[0].id = getNextId(); }; // Set scope for these functions // Object to contain editor event names and callback functions var events = {}; canvas.call = call; /** * Array of what was changed (elements, layers). * @event module:svgcanvas.SvgCanvas#event:changed * @type {Element[]} */ /** * Array of selected elements. * @event module:svgcanvas.SvgCanvas#event:selected * @type {Element[]} */ /** * Array of selected elements. * @event module:svgcanvas.SvgCanvas#event:transition * @type {Element[]} */ /** * The Element is always `SVGGElement`? * If not `null`, will be the set current group element. * @event module:svgcanvas.SvgCanvas#event:contextset * @type {null|Element} */ /** * @event module:svgcanvas.SvgCanvas#event:pointsAdded * @type {PlainObject} * @property {boolean} closedSubpath * @property {SVGCircleElement[]} grips Grips elements */ /** * @event module:svgcanvas.SvgCanvas#event:zoomed * @type {PlainObject} * @property {Float} x * @property {Float} y * @property {Float} width * @property {Float} height * @property {0.5|2} factor * @see module:SVGEditor.BBoxObjectWithFactor */ /** * @event module:svgcanvas.SvgCanvas#event:updateCanvas * @type {PlainObject} * @property {false} center * @property {module:math.XYObject} newCtr */ /** * @typedef {PlainObject} module:svgcanvas.ExtensionInitResponsePlusName * @implements {module:svgcanvas.ExtensionInitResponse} * @property {string} name The extension's resolved ID (whether explicit or based on file name) */ /** * Generalized extension object response of * [`init()`]{@link module:svgcanvas.ExtensionInitCallback} * along with the name of the extension. * @event module:svgcanvas.SvgCanvas#event:extension_added * @type {module:svgcanvas.ExtensionInitResponsePlusName|void} */ /** * @event module:svgcanvas.SvgCanvas#event:extensions_added * @type {void} */ /** * @typedef {PlainObject} module:svgcanvas.Message * @property {any} data The data * @property {string} origin The origin */ /** * @event module:svgcanvas.SvgCanvas#event:message * @type {module:svgcanvas.Message} */ /** * SVG canvas converted to string. * @event module:svgcanvas.SvgCanvas#event:saved * @type {string} */ /** * @event module:svgcanvas.SvgCanvas#event:setnonce * @type {!(string|Integer)} */ /** * @event module:svgcanvas.SvgCanvas#event:unsetnonce * @type {void} */ /** * @event module:svgcanvas.SvgCanvas#event:zoomDone * @type {void} */ /** * @event module:svgcanvas.SvgCanvas#event:cleared * @type {void} */ /** * @event module:svgcanvas.SvgCanvas#event:exported * @type {module:svgcanvas.ImageExportedResults} */ /** * @event module:svgcanvas.SvgCanvas#event:exportedPDF * @type {module:svgcanvas.PDFExportedResults} */ /** * Creating a cover-all class until {@link https://github.com/jsdoc3/jsdoc/issues/1545} may be supported. * `undefined` may be returned by {@link module:svgcanvas.SvgCanvas#event:extension_added} if the extension's `init` returns `undefined` It is also the type for the following events "zoomDone", "unsetnonce", "cleared", and "extensions_added". * @event module:svgcanvas.SvgCanvas#event:GenericCanvasEvent * @type {module:svgcanvas.SvgCanvas#event:selected|module:svgcanvas.SvgCanvas#event:changed|module:svgcanvas.SvgCanvas#event:contextset|module:svgcanvas.SvgCanvas#event:pointsAdded|module:svgcanvas.SvgCanvas#event:extension_added|module:svgcanvas.SvgCanvas#event:extensions_added|module:svgcanvas.SvgCanvas#event:message|module:svgcanvas.SvgCanvas#event:transition|module:svgcanvas.SvgCanvas#event:zoomed|module:svgcanvas.SvgCanvas#event:updateCanvas|module:svgcanvas.SvgCanvas#event:saved|module:svgcanvas.SvgCanvas#event:exported|module:svgcanvas.SvgCanvas#event:exportedPDF|module:svgcanvas.SvgCanvas#event:setnonce|module:svgcanvas.SvgCanvas#event:unsetnonce|void} */ /** * The promise return, if present, resolves to `undefined` * (`extension_added`, `exported`, `saved`). * @typedef {Promise<void>|void} module:svgcanvas.EventHandlerReturn */ /** * @callback module:svgcanvas.EventHandler * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:GenericCanvasEvent} arg * @listens module:svgcanvas.SvgCanvas#event:GenericCanvasEvent * @returns {module:svgcanvas.EventHandlerReturn} */ /** * Attaches a callback function to an event. * @function module:svgcanvas.SvgCanvas#bind * @param {"changed"|"contextset"|"selected"|"pointsAdded"|"extension_added"|"extensions_added"|"message"|"transition"|"zoomed"|"updateCanvas"|"zoomDone"|"saved"|"exported"|"exportedPDF"|"setnonce"|"unsetnonce"|"cleared"} ev - String indicating the name of the event * @param {module:svgcanvas.EventHandler} f - The callback function to bind to the event * @returns {module:svgcanvas.EventHandler} The previous event */ canvas.bind = function (ev, f) { var old = events[ev]; events[ev] = f; return old; }; /** * Runs the SVG Document through the sanitizer and then updates its paths. * @function module:svgcanvas.SvgCanvas#prepareSvg * @param {XMLDocument} newDoc - The SVG DOM document * @returns {void} */ this.prepareSvg = function (newDoc) { this.sanitizeSvg(newDoc.documentElement); // convert paths into absolute commands var paths = _toConsumableArray(newDoc.getElementsByTagNameNS(NS.SVG, 'path')); paths.forEach(function (path) { path.setAttribute('d', pathActions$1.convertPath(path)); pathActions$1.fixEnd(path); }); }; /** * Hack for Firefox bugs where text element features aren't updated or get * messed up. See issue 136 and issue 137. * This function clones the element and re-selects it. * @function module:svgcanvas~ffClone * @todo Test for this bug on load and add it to "support" object instead of * browser sniffing * @param {Element} elem - The (text) DOM element to clone * @returns {Element} Cloned element */ var ffClone = function ffClone(elem) { if (!isGecko()) { return elem; } var clone = elem.cloneNode(true); elem.before(clone); elem.remove(); selectorManager.releaseSelector(elem); selectedElements[0] = clone; selectorManager.requestSelector(clone).showGrips(true); return clone; }; // `this.each` is deprecated, if any extension used this it can be recreated by doing this: // * @example $(canvas.getRootElem()).children().each(...) // * @function module:svgcanvas.SvgCanvas#each // this.each = function (cb) { // $(svgroot).children().each(cb); // }; /** * Removes any old rotations if present, prepends a new rotation at the * transformed center. * @function module:svgcanvas.SvgCanvas#setRotationAngle * @param {string|Float} val - The new rotation angle in degrees * @param {boolean} preventUndo - Indicates whether the action should be undoable or not * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.setRotationAngle = function (val, preventUndo) { // ensure val is the proper type val = Number.parseFloat(val); var elem = selectedElements[0]; var oldTransform = elem.getAttribute('transform'); var bbox = getBBox(elem); var cx = bbox.x + bbox.width / 2, cy = bbox.y + bbox.height / 2; var tlist = getTransformList(elem); // only remove the real rotational transform if present (i.e. at index=0) if (tlist.numberOfItems > 0) { var xform = tlist.getItem(0); if (xform.type === 4) { tlist.removeItem(0); } } // find Rnc and insert it if (val !== 0) { var center = transformPoint(cx, cy, transformListToTransform(tlist).matrix); var Rnc = svgroot.createSVGTransform(); Rnc.setRotate(val, center.x, center.y); if (tlist.numberOfItems) { tlist.insertItemBefore(Rnc, 0); } else { tlist.appendItem(Rnc); } } else if (tlist.numberOfItems === 0) { elem.removeAttribute('transform'); } if (!preventUndo) { // we need to undo it, then redo it so it can be undo-able! :) // TODO: figure out how to make changes to transform list undo-able cross-browser? var newTransform = elem.getAttribute('transform'); elem.setAttribute('transform', oldTransform); changeSelectedAttribute('transform', newTransform, selectedElements); call('changed', selectedElements); } // const pointGripContainer = getElem('pathpointgrip_container'); // if (elem.nodeName === 'path' && pointGripContainer) { // pathActions.setPointContainerTransform(elem.getAttribute('transform')); // } var selector = selectorManager.requestSelector(selectedElements[0]); selector.resize(); Selector.updateGripCursors(val); }; /** * Runs `recalculateDimensions` on the selected elements, * adding the changes to a single batch command. * @function module:svgcanvas.SvgCanvas#recalculateAllSelectedDimensions * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function () { var text = currentResizeMode === 'none' ? 'position' : 'size'; var batchCmd = new BatchCommand$1(text); var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; // if (getRotationAngle(elem) && !hasMatrixTransform(getTransformList(elem))) { continue; } var cmd = recalculateDimensions(elem); if (cmd) { batchCmd.addSubCommand(cmd); } } if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); call('changed', selectedElements); } }; /** * Debug tool to easily see the current matrix in the browser's console. * @function module:svgcanvas~logMatrix * @param {SVGMatrix} m The matrix * @returns {void} */ var logMatrix = function logMatrix(m) { console.log([m.a, m.b, m.c, m.d, m.e, m.f]); // eslint-disable-line no-console }; // Root Current Transformation Matrix in user units var rootSctm = null; /** * Group: Selection. */ // TODO: do we need to worry about selectedBBoxes here? /** * Selects only the given elements, shortcut for `clearSelection(); addToSelection()`. * @function module:svgcanvas.SvgCanvas#selectOnly * @param {Element[]} elems - an array of DOM elements to be selected * @param {boolean} showGrips - Indicates whether the resize grips should be shown * @returns {void} */ var selectOnly = this.selectOnly = function (elems, showGrips) { clearSelection(true); addToSelection(elems, showGrips); }; // TODO: could use slice here to make this faster? // TODO: should the 'selected' handler /** * Removes elements from the selection. * @function module:svgcanvas.SvgCanvas#removeFromSelection * @param {Element[]} elemsToRemove - An array of elements to remove from selection * @returns {void} */ /* const removeFromSelection = */ this.removeFromSelection = function (elemsToRemove) { if (isNullish(selectedElements[0])) { return; } if (!elemsToRemove.length) { return; } // find every element and remove it from our array copy var newSelectedItems = [], len = selectedElements.length; for (var i = 0; i < len; ++i) { var elem = selectedElements[i]; if (elem) { // keep the item if (!elemsToRemove.includes(elem)) { newSelectedItems.push(elem); } else { // remove the item and its selector selectorManager.releaseSelector(elem); } } } // the copy becomes the master now selectedElements = newSelectedItems; }; /** * Clears the selection, then adds all elements in the current layer to the selection. * @function module:svgcanvas.SvgCanvas#selectAllInCurrentLayer * @returns {void} */ this.selectAllInCurrentLayer = function () { var currentLayer = getCurrentDrawing().getCurrentLayer(); if (currentLayer) { currentMode = 'select'; selectOnly($$b(currentGroup || currentLayer).children()); } }; var drawnPath = null; // Mouse events (function () { var freehand = { minx: null, miny: null, maxx: null, maxy: null }; var THRESHOLD_DIST = 0.8, STEP_COUNT = 10; var dAttr = null, startX = null, startY = null, rStartX = null, rStartY = null, initBbox = {}, sumDistance = 0, controllPoint2 = { x: 0, y: 0 }, controllPoint1 = { x: 0, y: 0 }, start = { x: 0, y: 0 }, end = { x: 0, y: 0 }, bSpline = { x: 0, y: 0 }, nextPos = { x: 0, y: 0 }, parameter, nextParameter; var getBsplinePoint = function getBsplinePoint(t) { var spline = { x: 0, y: 0 }, p0 = controllPoint2, p1 = controllPoint1, p2 = start, p3 = end, S = 1.0 / 6.0, t2 = t * t, t3 = t2 * t; var m = [[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 0, 3, 0], [1, 4, 1, 0]]; spline.x = S * ((p0.x * m[0][0] + p1.x * m[0][1] + p2.x * m[0][2] + p3.x * m[0][3]) * t3 + (p0.x * m[1][0] + p1.x * m[1][1] + p2.x * m[1][2] + p3.x * m[1][3]) * t2 + (p0.x * m[2][0] + p1.x * m[2][1] + p2.x * m[2][2] + p3.x * m[2][3]) * t + (p0.x * m[3][0] + p1.x * m[3][1] + p2.x * m[3][2] + p3.x * m[3][3])); spline.y = S * ((p0.y * m[0][0] + p1.y * m[0][1] + p2.y * m[0][2] + p3.y * m[0][3]) * t3 + (p0.y * m[1][0] + p1.y * m[1][1] + p2.y * m[1][2] + p3.y * m[1][3]) * t2 + (p0.y * m[2][0] + p1.y * m[2][1] + p2.y * m[2][2] + p3.y * m[2][3]) * t + (p0.y * m[3][0] + p1.y * m[3][1] + p2.y * m[3][2] + p3.y * m[3][3])); return { x: spline.x, y: spline.y }; }; /** * Follows these conditions: * - When we are in a create mode, the element is added to the canvas but the * action is not recorded until mousing up. * - When we are in select mode, select the element, remember the position * and do nothing else. * @param {MouseEvent} evt * @fires module:svgcanvas.SvgCanvas#event:ext_mouseDown * @returns {void} */ var mouseDown = function mouseDown(evt) { if (canvas.spaceKey || evt.button === 1) { return; } var rightClick = evt.button === 2; if (evt.altKey) { // duplicate when dragging canvas.cloneSelectedElements(0, 0); } rootSctm = $$b('#svgcontent g')[0].getScreenCTM().inverse(); var pt = transformPoint(evt.pageX, evt.pageY, rootSctm), mouseX = pt.x * currentZoom, mouseY = pt.y * currentZoom; evt.preventDefault(); if (rightClick) { currentMode = 'select'; lastClickPoint = pt; } // This would seem to be unnecessary... // if (!['select', 'resize'].includes(currentMode)) { // setGradient(); // } var x = mouseX / currentZoom, y = mouseY / currentZoom; var mouseTarget = getMouseTarget(evt); if (mouseTarget.tagName === 'a' && mouseTarget.childNodes.length === 1) { mouseTarget = mouseTarget.firstChild; } // realX/y ignores grid-snap value var realX = x; rStartX = startX = x; var realY = y; rStartY = startY = y; if (curConfig.gridSnapping) { x = snapToGrid(x); y = snapToGrid(y); startX = snapToGrid(startX); startY = snapToGrid(startY); } // if it is a selector grip, then it must be a single element selected, // set the mouseTarget to that and update the mode to rotate/resize if (mouseTarget === selectorManager.selectorParentGroup && !isNullish(selectedElements[0])) { var grip = evt.target; var griptype = elData(grip, 'type'); // rotating if (griptype === 'rotate') { currentMode = 'rotate'; // resizing } else if (griptype === 'resize') { currentMode = 'resize'; currentResizeMode = elData(grip, 'dir'); } mouseTarget = selectedElements[0]; } startTransform = mouseTarget.getAttribute('transform'); var tlist = getTransformList(mouseTarget); switch (currentMode) { case 'select': started = true; currentResizeMode = 'none'; if (rightClick) { started = false; } if (mouseTarget !== svgroot) { // if this element is not yet selected, clear selection and select it if (!selectedElements.includes(mouseTarget)) { // only clear selection if shift is not pressed (otherwise, add // element to selection) if (!evt.shiftKey) { // No need to do the call here as it will be done on addToSelection clearSelection(true); } addToSelection([mouseTarget]); justSelected = mouseTarget; pathActions$1.clear(); } // else if it's a path, go into pathedit mode in mouseup if (!rightClick) { // insert a dummy transform so if the element(s) are moved it will have // a transform to use for its translate var _iterator = _createForOfIteratorHelper(selectedElements), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var selectedElement = _step.value; if (isNullish(selectedElement)) { continue; } var slist = getTransformList(selectedElement); if (slist.numberOfItems) { slist.insertItemBefore(svgroot.createSVGTransform(), 0); } else { slist.appendItem(svgroot.createSVGTransform()); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } } else if (!rightClick) { clearSelection(); currentMode = 'multiselect'; if (isNullish(rubberBox)) { rubberBox = selectorManager.getRubberBandBox(); } rStartX *= currentZoom; rStartY *= currentZoom; // console.log('p',[evt.pageX, evt.pageY]); // console.log('c',[evt.clientX, evt.clientY]); // console.log('o',[evt.offsetX, evt.offsetY]); // console.log('s',[startX, startY]); assignAttributes(rubberBox, { x: rStartX, y: rStartY, width: 0, height: 0, display: 'inline' }); } break; case 'zoom': started = true; if (isNullish(rubberBox)) { rubberBox = selectorManager.getRubberBandBox(); } assignAttributes(rubberBox, { x: realX * currentZoom, y: realX * currentZoom, width: 0, height: 0, display: 'inline' }); break; case 'resize': { started = true; startX = x; startY = y; // Getting the BBox from the selection box, since we know we // want to orient around it initBbox = getBBox($$b('#selectedBox0')[0]); var bb = {}; $$b.each(initBbox, function (key, val) { bb[key] = val / currentZoom; }); initBbox = bb; // append three dummy transforms to the tlist so that // we can translate,scale,translate in mousemove var pos = getRotationAngle(mouseTarget) ? 1 : 0; if (hasMatrixTransform(tlist)) { tlist.insertItemBefore(svgroot.createSVGTransform(), pos); tlist.insertItemBefore(svgroot.createSVGTransform(), pos); tlist.insertItemBefore(svgroot.createSVGTransform(), pos); } else { tlist.appendItem(svgroot.createSVGTransform()); tlist.appendItem(svgroot.createSVGTransform()); tlist.appendItem(svgroot.createSVGTransform()); if (supportsNonScalingStroke()) { // Handle crash for newer Chrome and Safari 6 (Mobile and Desktop): // https://code.google.com/p/svg-edit/issues/detail?id=904 // Chromium issue: https://code.google.com/p/chromium/issues/detail?id=114625 // TODO: Remove this workaround once vendor fixes the issue var iswebkit = isWebkit(); var delayedStroke; if (iswebkit) { delayedStroke = function delayedStroke(ele) { var stroke_ = ele.getAttribute('stroke'); ele.removeAttribute('stroke'); // Re-apply stroke after delay. Anything higher than 1 seems to cause flicker if (stroke_ !== null) setTimeout(function () { ele.setAttribute('stroke', stroke_); }, 0); }; } mouseTarget.style.vectorEffect = 'non-scaling-stroke'; if (iswebkit) { delayedStroke(mouseTarget); } var all = mouseTarget.getElementsByTagName('*'), len = all.length; for (var i = 0; i < len; i++) { if (!all[i].style) { // mathML continue; } all[i].style.vectorEffect = 'non-scaling-stroke'; if (iswebkit) { delayedStroke(all[i]); } } } } break; } case 'fhellipse': case 'fhrect': case 'fhpath': start.x = realX; start.y = realY; controllPoint1 = { x: 0, y: 0 }; controllPoint2 = { x: 0, y: 0 }; started = true; dAttr = realX + ',' + realY + ' '; // Commented out as doing nothing now: // strokeW = parseFloat(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width; addSVGElementFromJson({ element: 'polyline', curStyles: true, attr: { points: dAttr, id: getNextId(), fill: 'none', opacity: curShape.opacity / 2, 'stroke-linecap': 'round', style: 'pointer-events:none' } }); freehand.minx = realX; freehand.maxx = realX; freehand.miny = realY; freehand.maxy = realY; break; case 'image': { started = true; var newImage = addSVGElementFromJson({ element: 'image', attr: { x: x, y: y, width: 0, height: 0, id: getNextId(), opacity: curShape.opacity / 2, style: 'pointer-events:inherit' } }); setHref(newImage, lastGoodImgUrl); preventClickDefault(newImage); break; } case 'square': // TODO: once we create the rect, we lose information that this was a square // (for resizing purposes this could be important) // Fallthrough case 'rect': started = true; startX = x; startY = y; addSVGElementFromJson({ element: 'rect', curStyles: true, attr: { x: x, y: y, width: 0, height: 0, id: getNextId(), opacity: curShape.opacity / 2 } }); break; case 'line': { started = true; var strokeW = Number(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width; addSVGElementFromJson({ element: 'line', curStyles: true, attr: { x1: x, y1: y, x2: x, y2: y, id: getNextId(), stroke: curShape.stroke, 'stroke-width': strokeW, 'stroke-dasharray': curShape.stroke_dasharray, 'stroke-linejoin': curShape.stroke_linejoin, 'stroke-linecap': curShape.stroke_linecap, 'stroke-opacity': curShape.stroke_opacity, fill: 'none', opacity: curShape.opacity / 2, style: 'pointer-events:none' } }); break; } case 'circle': started = true; addSVGElementFromJson({ element: 'circle', curStyles: true, attr: { cx: x, cy: y, r: 0, id: getNextId(), opacity: curShape.opacity / 2 } }); break; case 'ellipse': started = true; addSVGElementFromJson({ element: 'ellipse', curStyles: true, attr: { cx: x, cy: y, rx: 0, ry: 0, id: getNextId(), opacity: curShape.opacity / 2 } }); break; case 'text': started = true; /* const newText = */ addSVGElementFromJson({ element: 'text', curStyles: true, attr: { x: x, y: y, id: getNextId(), fill: curText.fill, 'stroke-width': curText.stroke_width, 'font-size': curText.font_size, 'font-family': curText.font_family, 'text-anchor': 'middle', 'xml:space': 'preserve', opacity: curShape.opacity } }); // newText.textContent = 'text'; break; case 'path': // Fall through case 'pathedit': startX *= currentZoom; startY *= currentZoom; pathActions$1.mouseDown(evt, mouseTarget, startX, startY); started = true; break; case 'textedit': startX *= currentZoom; startY *= currentZoom; textActions.mouseDown(evt, mouseTarget, startX, startY); started = true; break; case 'rotate': started = true; // we are starting an undoable change (a drag-rotation) canvas.undoMgr.beginUndoableChange('transform', selectedElements); break; } /** * The main (left) mouse button is held down on the canvas area. * @event module:svgcanvas.SvgCanvas#event:ext_mouseDown * @type {PlainObject} * @property {MouseEvent} event The event object * @property {Float} start_x x coordinate on canvas * @property {Float} start_y y coordinate on canvas * @property {Element[]} selectedElements An array of the selected Elements */ var extResult = runExtensions('mouseDown', /** @type {module:svgcanvas.SvgCanvas#event:ext_mouseDown} */ { event: evt, start_x: startX, start_y: startY, selectedElements: selectedElements }, true); $$b.each(extResult, function (i, r) { if (r && r.started) { started = true; } }); }; // in this function we do not record any state changes yet (but we do update // any elements that are still being created, moved or resized on the canvas) /** * * @param {MouseEvent} evt * @fires module:svgcanvas.SvgCanvas#event:transition * @fires module:svgcanvas.SvgCanvas#event:ext_mouseMove * @returns {void} */ var mouseMove = function mouseMove(evt) { if (!started) { return; } if (evt.button === 1 || canvas.spaceKey) { return; } var i, xya, c, cx, cy, dx, dy, len, angle, box, selected = selectedElements[0]; var pt = transformPoint(evt.pageX, evt.pageY, rootSctm), mouseX = pt.x * currentZoom, mouseY = pt.y * currentZoom, shape = getElem(getId()); var realX = mouseX / currentZoom; var x = realX; var realY = mouseY / currentZoom; var y = realY; if (curConfig.gridSnapping) { x = snapToGrid(x); y = snapToGrid(y); } evt.preventDefault(); var tlist; switch (currentMode) { case 'select': { // we temporarily use a translate on the element(s) being dragged // this transform is removed upon mousing up and the element is // relocated to the new location if (selectedElements[0] !== null) { dx = x - startX; dy = y - startY; if (curConfig.gridSnapping) { dx = snapToGrid(dx); dy = snapToGrid(dy); } /* // Commenting out as currently has no effect if (evt.shiftKey) { xya = snapToAngle(startX, startY, x, y); ({x, y} = xya); } */ if (dx !== 0 || dy !== 0) { len = selectedElements.length; for (i = 0; i < len; ++i) { selected = selectedElements[i]; if (isNullish(selected)) { break; } // if (i === 0) { // const box = utilsGetBBox(selected); // selectedBBoxes[i].x = box.x + dx; // selectedBBoxes[i].y = box.y + dy; // } // update the dummy transform in our transform list // to be a translate var xform = svgroot.createSVGTransform(); tlist = getTransformList(selected); // Note that if Webkit and there's no ID for this // element, the dummy transform may have gotten lost. // This results in unexpected behaviour xform.setTranslate(dx, dy); if (tlist.numberOfItems) { tlist.replaceItem(xform, 0); } else { tlist.appendItem(xform); } // update our internal bbox that we're tracking while dragging selectorManager.requestSelector(selected).resize(); } call('transition', selectedElements); } } break; } case 'multiselect': { realX *= currentZoom; realY *= currentZoom; assignAttributes(rubberBox, { x: Math.min(rStartX, realX), y: Math.min(rStartY, realY), width: Math.abs(realX - rStartX), height: Math.abs(realY - rStartY) }); // for each selected: // - if newList contains selected, do nothing // - if newList doesn't contain selected, remove it from selected // - for any newList that was not in selectedElements, add it to selected var elemsToRemove = selectedElements.slice(), elemsToAdd = [], newList = getIntersectionList(); // For every element in the intersection, add if not present in selectedElements. len = newList.length; for (i = 0; i < len; ++i) { var intElem = newList[i]; // Found an element that was not selected before, so we should add it. if (!selectedElements.includes(intElem)) { elemsToAdd.push(intElem); } // Found an element that was already selected, so we shouldn't remove it. var foundInd = elemsToRemove.indexOf(intElem); if (foundInd !== -1) { elemsToRemove.splice(foundInd, 1); } } if (elemsToRemove.length > 0) { canvas.removeFromSelection(elemsToRemove); } if (elemsToAdd.length > 0) { canvas.addToSelection(elemsToAdd); } break; } case 'resize': { // we track the resize bounding box and translate/scale the selected element // while the mouse is down, when mouse goes up, we use this to recalculate // the shape's coordinates tlist = getTransformList(selected); var hasMatrix = hasMatrixTransform(tlist); box = hasMatrix ? initBbox : getBBox(selected); var left = box.x, top = box.y, _box = box, width = _box.width, height = _box.height; dx = x - startX; dy = y - startY; if (curConfig.gridSnapping) { dx = snapToGrid(dx); dy = snapToGrid(dy); height = snapToGrid(height); width = snapToGrid(width); } // if rotated, adjust the dx,dy values angle = getRotationAngle(selected); if (angle) { var r = Math.sqrt(dx * dx + dy * dy), theta = Math.atan2(dy, dx) - angle * Math.PI / 180.0; dx = r * Math.cos(theta); dy = r * Math.sin(theta); } // if not stretching in y direction, set dy to 0 // if not stretching in x direction, set dx to 0 if (!currentResizeMode.includes('n') && !currentResizeMode.includes('s')) { dy = 0; } if (!currentResizeMode.includes('e') && !currentResizeMode.includes('w')) { dx = 0; } var // ts = null, tx = 0, ty = 0, sy = height ? (height + dy) / height : 1, sx = width ? (width + dx) / width : 1; // if we are dragging on the north side, then adjust the scale factor and ty if (currentResizeMode.includes('n')) { sy = height ? (height - dy) / height : 1; ty = height; } // if we dragging on the east side, then adjust the scale factor and tx if (currentResizeMode.includes('w')) { sx = width ? (width - dx) / width : 1; tx = width; } // update the transform list with translate,scale,translate var translateOrigin = svgroot.createSVGTransform(), scale = svgroot.createSVGTransform(), translateBack = svgroot.createSVGTransform(); if (curConfig.gridSnapping) { left = snapToGrid(left); tx = snapToGrid(tx); top = snapToGrid(top); ty = snapToGrid(ty); } translateOrigin.setTranslate(-(left + tx), -(top + ty)); if (evt.shiftKey) { if (sx === 1) { sx = sy; } else { sy = sx; } } scale.setScale(sx, sy); translateBack.setTranslate(left + tx, top + ty); if (hasMatrix) { var diff = angle ? 1 : 0; tlist.replaceItem(translateOrigin, 2 + diff); tlist.replaceItem(scale, 1 + diff); tlist.replaceItem(translateBack, Number(diff)); } else { var N = tlist.numberOfItems; tlist.replaceItem(translateBack, N - 3); tlist.replaceItem(scale, N - 2); tlist.replaceItem(translateOrigin, N - 1); } selectorManager.requestSelector(selected).resize(); call('transition', selectedElements); break; } case 'zoom': { realX *= currentZoom; realY *= currentZoom; assignAttributes(rubberBox, { x: Math.min(rStartX * currentZoom, realX), y: Math.min(rStartY * currentZoom, realY), width: Math.abs(realX - rStartX * currentZoom), height: Math.abs(realY - rStartY * currentZoom) }); break; } case 'text': { assignAttributes(shape, { x: x, y: y }); break; } case 'line': { if (curConfig.gridSnapping) { x = snapToGrid(x); y = snapToGrid(y); } var x2 = x; var y2 = y; if (evt.shiftKey) { xya = snapToAngle(startX, startY, x2, y2); x2 = xya.x; y2 = xya.y; } shape.setAttribute('x2', x2); shape.setAttribute('y2', y2); break; } case 'foreignObject': // fall through case 'square': // fall through case 'rect': // fall through case 'image': { var square = currentMode === 'square' || evt.shiftKey; var w = Math.abs(x - startX), h = Math.abs(y - startY); var newX, newY; if (square) { w = h = Math.max(w, h); newX = startX < x ? startX : startX - w; newY = startY < y ? startY : startY - h; } else { newX = Math.min(startX, x); newY = Math.min(startY, y); } if (curConfig.gridSnapping) { w = snapToGrid(w); h = snapToGrid(h); newX = snapToGrid(newX); newY = snapToGrid(newY); } assignAttributes(shape, { width: w, height: h, x: newX, y: newY }); break; } case 'circle': { c = $$b(shape).attr(['cx', 'cy']); var _c = c; cx = _c.cx; cy = _c.cy; var rad = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)); if (curConfig.gridSnapping) { rad = snapToGrid(rad); } shape.setAttribute('r', rad); break; } case 'ellipse': { c = $$b(shape).attr(['cx', 'cy']); var _c2 = c; cx = _c2.cx; cy = _c2.cy; if (curConfig.gridSnapping) { x = snapToGrid(x); cx = snapToGrid(cx); y = snapToGrid(y); cy = snapToGrid(cy); } shape.setAttribute('rx', Math.abs(x - cx)); var ry = Math.abs(evt.shiftKey ? x - cx : y - cy); shape.setAttribute('ry', ry); break; } case 'fhellipse': case 'fhrect': { freehand.minx = Math.min(realX, freehand.minx); freehand.maxx = Math.max(realX, freehand.maxx); freehand.miny = Math.min(realY, freehand.miny); freehand.maxy = Math.max(realY, freehand.maxy); } // Fallthrough case 'fhpath': { // dAttr += + realX + ',' + realY + ' '; // shape.setAttribute('points', dAttr); end.x = realX; end.y = realY; if (controllPoint2.x && controllPoint2.y) { for (i = 0; i < STEP_COUNT - 1; i++) { parameter = i / STEP_COUNT; nextParameter = (i + 1) / STEP_COUNT; bSpline = getBsplinePoint(nextParameter); nextPos = bSpline; bSpline = getBsplinePoint(parameter); sumDistance += Math.sqrt((nextPos.x - bSpline.x) * (nextPos.x - bSpline.x) + (nextPos.y - bSpline.y) * (nextPos.y - bSpline.y)); if (sumDistance > THRESHOLD_DIST) { sumDistance -= THRESHOLD_DIST; // Faster than completely re-writing the points attribute. var point = svgcontent.createSVGPoint(); point.x = bSpline.x; point.y = bSpline.y; shape.points.appendItem(point); } } } controllPoint2 = { x: controllPoint1.x, y: controllPoint1.y }; controllPoint1 = { x: start.x, y: start.y }; start = { x: end.x, y: end.y }; break; // update path stretch line coordinates } case 'path': // fall through case 'pathedit': { x *= currentZoom; y *= currentZoom; if (curConfig.gridSnapping) { x = snapToGrid(x); y = snapToGrid(y); startX = snapToGrid(startX); startY = snapToGrid(startY); } if (evt.shiftKey) { var path = path$1; var x1, y1; if (path) { x1 = path.dragging ? path.dragging[0] : startX; y1 = path.dragging ? path.dragging[1] : startY; } else { x1 = startX; y1 = startY; } xya = snapToAngle(x1, y1, x, y); var _xya = xya; x = _xya.x; y = _xya.y; } if (rubberBox && rubberBox.getAttribute('display') !== 'none') { realX *= currentZoom; realY *= currentZoom; assignAttributes(rubberBox, { x: Math.min(rStartX * currentZoom, realX), y: Math.min(rStartY * currentZoom, realY), width: Math.abs(realX - rStartX * currentZoom), height: Math.abs(realY - rStartY * currentZoom) }); } pathActions$1.mouseMove(x, y); break; } case 'textedit': { x *= currentZoom; y *= currentZoom; // if (rubberBox && rubberBox.getAttribute('display') !== 'none') { // assignAttributes(rubberBox, { // x: Math.min(startX, x), // y: Math.min(startY, y), // width: Math.abs(x - startX), // height: Math.abs(y - startY) // }, 100); // } textActions.mouseMove(mouseX, mouseY); break; } case 'rotate': { box = getBBox(selected); cx = box.x + box.width / 2; cy = box.y + box.height / 2; var m = getMatrix(selected), center = transformPoint(cx, cy, m); cx = center.x; cy = center.y; angle = (Math.atan2(cy - y, cx - x) * (180 / Math.PI) - 90) % 360; if (curConfig.gridSnapping) { angle = snapToGrid(angle); } if (evt.shiftKey) { // restrict rotations to nice angles (WRS) var snap = 45; angle = Math.round(angle / snap) * snap; } canvas.setRotationAngle(angle < -180 ? 360 + angle : angle, true); call('transition', selectedElements); break; } } /** * The mouse has moved on the canvas area. * @event module:svgcanvas.SvgCanvas#event:ext_mouseMove * @type {PlainObject} * @property {MouseEvent} event The event object * @property {Float} mouse_x x coordinate on canvas * @property {Float} mouse_y y coordinate on canvas * @property {Element} selected Refers to the first selected element */ runExtensions('mouseMove', /** @type {module:svgcanvas.SvgCanvas#event:ext_mouseMove} */ { event: evt, mouse_x: mouseX, mouse_y: mouseY, selected: selected }); }; // mouseMove() // - in create mode, the element's opacity is set properly, we create an InsertElementCommand // and store it on the Undo stack // - in move/resize mode, the element's attributes which were affected by the move/resize are // identified, a ChangeElementCommand is created and stored on the stack for those attrs // this is done in when we recalculate the selected dimensions() /** * * @param {MouseEvent} evt * @fires module:svgcanvas.SvgCanvas#event:zoomed * @fires module:svgcanvas.SvgCanvas#event:changed * @fires module:svgcanvas.SvgCanvas#event:ext_mouseUp * @returns {void} */ var mouseUp = function mouseUp(evt) { if (evt.button === 2) { return; } var tempJustSelected = justSelected; justSelected = null; if (!started) { return; } var pt = transformPoint(evt.pageX, evt.pageY, rootSctm), mouseX = pt.x * currentZoom, mouseY = pt.y * currentZoom, x = mouseX / currentZoom, y = mouseY / currentZoom; var element = getElem(getId()); var keep = false; var realX = x; var realY = y; // TODO: Make true when in multi-unit mode started = false; var attrs, t; switch (currentMode) { // intentionally fall-through to select here case 'resize': case 'multiselect': if (!isNullish(rubberBox)) { rubberBox.setAttribute('display', 'none'); curBBoxes = []; } currentMode = 'select'; // Fallthrough case 'select': if (!isNullish(selectedElements[0])) { // if we only have one selected element if (isNullish(selectedElements[1])) { // set our current stroke/fill properties to the element's var selected = selectedElements[0]; switch (selected.tagName) { case 'g': case 'use': case 'image': case 'foreignObject': break; default: curProperties.fill = selected.getAttribute('fill'); curProperties.fill_opacity = selected.getAttribute('fill-opacity'); curProperties.stroke = selected.getAttribute('stroke'); curProperties.stroke_opacity = selected.getAttribute('stroke-opacity'); curProperties.stroke_width = selected.getAttribute('stroke-width'); curProperties.stroke_dasharray = selected.getAttribute('stroke-dasharray'); curProperties.stroke_linejoin = selected.getAttribute('stroke-linejoin'); curProperties.stroke_linecap = selected.getAttribute('stroke-linecap'); } if (selected.tagName === 'text') { curText.font_size = selected.getAttribute('font-size'); curText.font_family = selected.getAttribute('font-family'); } selectorManager.requestSelector(selected).showGrips(true); // This shouldn't be necessary as it was done on mouseDown... // call('selected', [selected]); } // always recalculate dimensions to strip off stray identity transforms recalculateAllSelectedDimensions(); // if it was being dragged/resized if (realX !== rStartX || realY !== rStartY) { var len = selectedElements.length; for (var i = 0; i < len; ++i) { if (isNullish(selectedElements[i])) { break; } if (!selectedElements[i].firstChild) { // Not needed for groups (incorrectly resizes elems), possibly not needed at all? selectorManager.requestSelector(selectedElements[i]).resize(); } } // no change in position/size, so maybe we should move to pathedit } else { t = evt.target; if (selectedElements[0].nodeName === 'path' && isNullish(selectedElements[1])) { pathActions$1.select(selectedElements[0]); // if it was a path // else, if it was selected and this is a shift-click, remove it from selection } else if (evt.shiftKey) { if (tempJustSelected !== t) { canvas.removeFromSelection([t]); } } } // no change in mouse position // Remove non-scaling stroke if (supportsNonScalingStroke()) { var elem = selectedElements[0]; if (elem) { elem.removeAttribute('style'); walkTree(elem, function (el) { el.removeAttribute('style'); }); } } } return; case 'zoom': { if (!isNullish(rubberBox)) { rubberBox.setAttribute('display', 'none'); } var factor = evt.shiftKey ? 0.5 : 2; call('zoomed', { x: Math.min(rStartX, realX), y: Math.min(rStartY, realY), width: Math.abs(realX - rStartX), height: Math.abs(realY - rStartY), factor: factor }); return; } case 'fhpath': { // Check that the path contains at least 2 points; a degenerate one-point path // causes problems. // Webkit ignores how we set the points attribute with commas and uses space // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870 sumDistance = 0; controllPoint2 = { x: 0, y: 0 }; controllPoint1 = { x: 0, y: 0 }; start = { x: 0, y: 0 }; end = { x: 0, y: 0 }; var coords = element.getAttribute('points'); var commaIndex = coords.indexOf(','); if (commaIndex >= 0) { keep = coords.includes(',', commaIndex + 1); } else { keep = coords.includes(' ', coords.indexOf(' ') + 1); } if (keep) { element = pathActions$1.smoothPolylineIntoPath(element); } break; } case 'line': attrs = $$b(element).attr(['x1', 'x2', 'y1', 'y2']); keep = attrs.x1 !== attrs.x2 || attrs.y1 !== attrs.y2; break; case 'foreignObject': case 'square': case 'rect': case 'image': attrs = $$b(element).attr(['width', 'height']); // Image should be kept regardless of size (use inherit dimensions later) keep = attrs.width || attrs.height || currentMode === 'image'; break; case 'circle': keep = element.getAttribute('r') !== '0'; break; case 'ellipse': attrs = $$b(element).attr(['rx', 'ry']); keep = attrs.rx || attrs.ry; break; case 'fhellipse': if (freehand.maxx - freehand.minx > 0 && freehand.maxy - freehand.miny > 0) { element = addSVGElementFromJson({ element: 'ellipse', curStyles: true, attr: { cx: (freehand.minx + freehand.maxx) / 2, cy: (freehand.miny + freehand.maxy) / 2, rx: (freehand.maxx - freehand.minx) / 2, ry: (freehand.maxy - freehand.miny) / 2, id: getId() } }); call('changed', [element]); keep = true; } break; case 'fhrect': if (freehand.maxx - freehand.minx > 0 && freehand.maxy - freehand.miny > 0) { element = addSVGElementFromJson({ element: 'rect', curStyles: true, attr: { x: freehand.minx, y: freehand.miny, width: freehand.maxx - freehand.minx, height: freehand.maxy - freehand.miny, id: getId() } }); call('changed', [element]); keep = true; } break; case 'text': keep = true; selectOnly([element]); textActions.start(element); break; case 'path': { // set element to null here so that it is not removed nor finalized element = null; // continue to be set to true so that mouseMove happens started = true; var res = pathActions$1.mouseUp(evt, element, mouseX, mouseY); element = res.element; keep = res.keep; break; } case 'pathedit': keep = true; element = null; pathActions$1.mouseUp(evt); break; case 'textedit': keep = false; element = null; textActions.mouseUp(evt, mouseX, mouseY); break; case 'rotate': { keep = true; element = null; currentMode = 'select'; var batchCmd = canvas.undoMgr.finishUndoableChange(); if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } // perform recalculation to weed out any stray identity transforms that might get stuck recalculateAllSelectedDimensions(); call('changed', selectedElements); break; } } /** * The main (left) mouse button is released (anywhere). * @event module:svgcanvas.SvgCanvas#event:ext_mouseUp * @type {PlainObject} * @property {MouseEvent} event The event object * @property {Float} mouse_x x coordinate on canvas * @property {Float} mouse_y y coordinate on canvas */ var extResult = runExtensions('mouseUp', /** @type {module:svgcanvas.SvgCanvas#event:ext_mouseUp} */ { event: evt, mouse_x: mouseX, mouse_y: mouseY }, true); $$b.each(extResult, function (i, r) { if (r) { keep = r.keep || keep; element = r.element; started = r.started || started; } }); if (!keep && !isNullish(element)) { getCurrentDrawing().releaseId(getId()); element.remove(); element = null; t = evt.target; // if this element is in a group, go up until we reach the top-level group // just below the layer groups // TODO: once we implement links, we also would have to check for <a> elements while (t && t.parentNode && t.parentNode.parentNode && t.parentNode.parentNode.tagName === 'g') { t = t.parentNode; } // if we are not in the middle of creating a path, and we've clicked on some shape, // then go to Select mode. // WebKit returns <div> when the canvas is clicked, Firefox/Opera return <svg> if ((currentMode !== 'path' || !drawnPath) && t && t.parentNode && t.parentNode.id !== 'selectorParentGroup' && t.id !== 'svgcanvas' && t.id !== 'svgroot') { // switch into "select" mode if we've clicked on an element canvas.setMode('select'); selectOnly([t], true); } } else if (!isNullish(element)) { /** * @name module:svgcanvas.SvgCanvas#addedNew * @type {boolean} */ canvas.addedNew = true; var aniDur = 0.2; var cAni; if (opacAni.beginElement && Number.parseFloat(element.getAttribute('opacity')) !== curShape.opacity) { cAni = $$b(opacAni).clone().attr({ to: curShape.opacity, dur: aniDur }).appendTo(element); try { // Fails in FF4 on foreignObject cAni[0].beginElement(); } catch (e) {} } else { aniDur = 0; } // Ideally this would be done on the endEvent of the animation, // but that doesn't seem to be supported in Webkit setTimeout(function () { if (cAni) { cAni.remove(); } element.setAttribute('opacity', curShape.opacity); element.setAttribute('style', 'pointer-events:inherit'); cleanupElement(element); if (currentMode === 'path') { pathActions$1.toEditMode(element); } else if (curConfig.selectNew) { selectOnly([element], true); } // we create the insert command that is stored on the stack // undo means to call cmd.unapply(), redo means to call cmd.apply() addCommandToHistory(new InsertElementCommand$1(element)); call('changed', [element]); }, aniDur * 1000); } startTransform = null; }; var dblClick = function dblClick(evt) { var evtTarget = evt.target; var parent = evtTarget.parentNode; var mouseTarget = getMouseTarget(evt); var _mouseTarget = mouseTarget, tagName = _mouseTarget.tagName; if (tagName === 'text' && currentMode !== 'textedit') { var pt = transformPoint(evt.pageX, evt.pageY, rootSctm); textActions.select(mouseTarget, pt.x, pt.y); } // Do nothing if already in current group if (parent === currentGroup) { return; } if ((tagName === 'g' || tagName === 'a') && getRotationAngle(mouseTarget)) { // TODO: Allow method of in-group editing without having to do // this (similar to editing rotated paths) // Ungroup and regroup pushGroupProperties(mouseTarget); mouseTarget = selectedElements[0]; clearSelection(true); } // Reset context if (currentGroup) { leaveContext(); } if (parent.tagName !== 'g' && parent.tagName !== 'a' || parent === getCurrentDrawing().getCurrentLayer() || mouseTarget === selectorManager.selectorParentGroup) { // Escape from in-group edit return; } setContext(mouseTarget); }; // prevent links from being followed in the canvas var handleLinkInCanvas = function handleLinkInCanvas(e) { e.preventDefault(); return false; }; // Added mouseup to the container here. // TODO(codedread): Figure out why after the Closure compiler, the window mouseup is ignored. $$b(container).mousedown(mouseDown).mousemove(mouseMove).click(handleLinkInCanvas).dblclick(dblClick).mouseup(mouseUp); // $(window).mouseup(mouseUp); // TODO(rafaelcastrocouto): User preference for shift key and zoom factor $$b(container).bind('mousewheel DOMMouseScroll', /** * @param {Event} e * @fires module:svgcanvas.SvgCanvas#event:updateCanvas * @fires module:svgcanvas.SvgCanvas#event:zoomDone * @returns {void} */ function (e) { if (!e.shiftKey) { return; } e.preventDefault(); var evt = e.originalEvent; rootSctm = $$b('#svgcontent g')[0].getScreenCTM().inverse(); var workarea = $$b('#workarea'); var scrbar = 15; var rulerwidth = curConfig.showRulers ? 16 : 0; // mouse relative to content area in content pixels var pt = transformPoint(evt.pageX, evt.pageY, rootSctm); // full work area width in screen pixels var editorFullW = workarea.width(); var editorFullH = workarea.height(); // work area width minus scroll and ruler in screen pixels var editorW = editorFullW - scrbar - rulerwidth; var editorH = editorFullH - scrbar - rulerwidth; // work area width in content pixels var workareaViewW = editorW * rootSctm.a; var workareaViewH = editorH * rootSctm.d; // content offset from canvas in screen pixels var wOffset = workarea.offset(); var wOffsetLeft = wOffset.left + rulerwidth; var wOffsetTop = wOffset.top + rulerwidth; var delta = evt.wheelDelta ? evt.wheelDelta : evt.detail ? -evt.detail : 0; if (!delta) { return; } var factor = Math.max(3 / 4, Math.min(4 / 3, delta)); var wZoom, hZoom; if (factor > 1) { wZoom = Math.ceil(editorW / workareaViewW * factor * 100) / 100; hZoom = Math.ceil(editorH / workareaViewH * factor * 100) / 100; } else { wZoom = Math.floor(editorW / workareaViewW * factor * 100) / 100; hZoom = Math.floor(editorH / workareaViewH * factor * 100) / 100; } var zoomlevel = Math.min(wZoom, hZoom); zoomlevel = Math.min(10, Math.max(0.01, zoomlevel)); if (zoomlevel === currentZoom) { return; } factor = zoomlevel / currentZoom; // top left of workarea in content pixels before zoom var topLeftOld = transformPoint(wOffsetLeft, wOffsetTop, rootSctm); // top left of workarea in content pixels after zoom var topLeftNew = { x: pt.x - (pt.x - topLeftOld.x) / factor, y: pt.y - (pt.y - topLeftOld.y) / factor }; // top left of workarea in canvas pixels relative to content after zoom var topLeftNewCanvas = { x: topLeftNew.x * zoomlevel, y: topLeftNew.y * zoomlevel }; // new center in canvas pixels var newCtr = { x: topLeftNewCanvas.x - rulerwidth + editorFullW / 2, y: topLeftNewCanvas.y - rulerwidth + editorFullH / 2 }; canvas.setZoom(zoomlevel); $$b('#zoom').val((zoomlevel * 100).toFixed(1)); call('updateCanvas', { center: false, newCtr: newCtr }); call('zoomDone'); }); })(); /* eslint-disable jsdoc/require-property */ /** * Group: Text edit functions * Functions relating to editing text elements. * @namespace {PlainObject} textActions * @memberof module:svgcanvas.SvgCanvas# */ var textActions = canvas.textActions = function () { /* eslint-enable jsdoc/require-property */ var curtext; var textinput; var cursor; var selblock; var blinker; var chardata = []; var textbb; // , transbb; var matrix; var lastX, lastY; var allowDbl; /** * * @param {Integer} index * @returns {void} */ function setCursor(index) { var empty = textinput.value === ''; $$b(textinput).focus(); if (!arguments.length) { if (empty) { index = 0; } else { if (textinput.selectionEnd !== textinput.selectionStart) { return; } index = textinput.selectionEnd; } } var charbb = chardata[index]; if (!empty) { textinput.setSelectionRange(index, index); } cursor = getElem('text_cursor'); if (!cursor) { cursor = document.createElementNS(NS.SVG, 'line'); assignAttributes(cursor, { id: 'text_cursor', stroke: '#333', 'stroke-width': 1 }); cursor = getElem('selectorParentGroup').appendChild(cursor); } if (!blinker) { blinker = setInterval(function () { var show = cursor.getAttribute('display') === 'none'; cursor.setAttribute('display', show ? 'inline' : 'none'); }, 600); } var startPt = ptToScreen(charbb.x, textbb.y); var endPt = ptToScreen(charbb.x, textbb.y + textbb.height); assignAttributes(cursor, { x1: startPt.x, y1: startPt.y, x2: endPt.x, y2: endPt.y, visibility: 'visible', display: 'inline' }); if (selblock) { selblock.setAttribute('d', ''); } } /** * * @param {Integer} start * @param {Integer} end * @param {boolean} skipInput * @returns {void} */ function setSelection(start, end, skipInput) { if (start === end) { setCursor(end); return; } if (!skipInput) { textinput.setSelectionRange(start, end); } selblock = getElem('text_selectblock'); if (!selblock) { selblock = document.createElementNS(NS.SVG, 'path'); assignAttributes(selblock, { id: 'text_selectblock', fill: 'green', opacity: 0.5, style: 'pointer-events:none' }); getElem('selectorParentGroup').append(selblock); } var startbb = chardata[start]; var endbb = chardata[end]; cursor.setAttribute('visibility', 'hidden'); var tl = ptToScreen(startbb.x, textbb.y), tr = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y), bl = ptToScreen(startbb.x, textbb.y + textbb.height), br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height); var dstr = 'M' + tl.x + ',' + tl.y + ' L' + tr.x + ',' + tr.y + ' ' + br.x + ',' + br.y + ' ' + bl.x + ',' + bl.y + 'z'; assignAttributes(selblock, { d: dstr, display: 'inline' }); } /** * * @param {Float} mouseX * @param {Float} mouseY * @returns {Integer} */ function getIndexFromPoint(mouseX, mouseY) { // Position cursor here var pt = svgroot.createSVGPoint(); pt.x = mouseX; pt.y = mouseY; // No content, so return 0 if (chardata.length === 1) { return 0; } // Determine if cursor should be on left or right of character var charpos = curtext.getCharNumAtPosition(pt); if (charpos < 0) { // Out of text range, look at mouse coords charpos = chardata.length - 2; if (mouseX <= chardata[0].x) { charpos = 0; } } else if (charpos >= chardata.length - 2) { charpos = chardata.length - 2; } var charbb = chardata[charpos]; var mid = charbb.x + charbb.width / 2; if (mouseX > mid) { charpos++; } return charpos; } /** * * @param {Float} mouseX * @param {Float} mouseY * @returns {void} */ function setCursorFromPoint(mouseX, mouseY) { setCursor(getIndexFromPoint(mouseX, mouseY)); } /** * * @param {Float} x * @param {Float} y * @param {boolean} apply * @returns {void} */ function setEndSelectionFromPoint(x, y, apply) { var i1 = textinput.selectionStart; var i2 = getIndexFromPoint(x, y); var start = Math.min(i1, i2); var end = Math.max(i1, i2); setSelection(start, end, !apply); } /** * * @param {Float} xIn * @param {Float} yIn * @returns {module:math.XYObject} */ function screenToPt(xIn, yIn) { var out = { x: xIn, y: yIn }; out.x /= currentZoom; out.y /= currentZoom; if (matrix) { var pt = transformPoint(out.x, out.y, matrix.inverse()); out.x = pt.x; out.y = pt.y; } return out; } /** * * @param {Float} xIn * @param {Float} yIn * @returns {module:math.XYObject} */ function ptToScreen(xIn, yIn) { var out = { x: xIn, y: yIn }; if (matrix) { var pt = transformPoint(out.x, out.y, matrix); out.x = pt.x; out.y = pt.y; } out.x *= currentZoom; out.y *= currentZoom; return out; } /* // Not currently in use function hideCursor () { if (cursor) { cursor.setAttribute('visibility', 'hidden'); } } */ /** * * @param {Event} evt * @returns {void} */ function selectAll(evt) { setSelection(0, curtext.textContent.length); $$b(this).unbind(evt); } /** * * @param {Event} evt * @returns {void} */ function selectWord(evt) { if (!allowDbl || !curtext) { return; } var ept = transformPoint(evt.pageX, evt.pageY, rootSctm), mouseX = ept.x * currentZoom, mouseY = ept.y * currentZoom; var pt = screenToPt(mouseX, mouseY); var index = getIndexFromPoint(pt.x, pt.y); var str = curtext.textContent; var first = str.substr(0, index).replace(/[a-z\d]+$/i, '').length; var m = str.substr(index).match(/^[a-z\d]+/i); var last = (m ? m[0].length : 0) + index; setSelection(first, last); // Set tripleclick $$b(evt.target).click(selectAll); setTimeout(function () { $$b(evt.target).unbind('click', selectAll); }, 300); } return ( /** @lends module:svgcanvas.SvgCanvas#textActions */ { /** * @param {Element} target * @param {Float} x * @param {Float} y * @returns {void} */ select: function select(target, x, y) { curtext = target; textActions.toEditMode(x, y); }, /** * @param {Element} elem * @returns {void} */ start: function start(elem) { curtext = elem; textActions.toEditMode(); }, /** * @param {external:MouseEvent} evt * @param {Element} mouseTarget * @param {Float} startX * @param {Float} startY * @returns {void} */ mouseDown: function mouseDown(evt, mouseTarget, startX, startY) { var pt = screenToPt(startX, startY); textinput.focus(); setCursorFromPoint(pt.x, pt.y); lastX = startX; lastY = startY; // TODO: Find way to block native selection }, /** * @param {Float} mouseX * @param {Float} mouseY * @returns {void} */ mouseMove: function mouseMove(mouseX, mouseY) { var pt = screenToPt(mouseX, mouseY); setEndSelectionFromPoint(pt.x, pt.y); }, /** * @param {external:MouseEvent} evt * @param {Float} mouseX * @param {Float} mouseY * @returns {void} */ mouseUp: function mouseUp(evt, mouseX, mouseY) { var pt = screenToPt(mouseX, mouseY); setEndSelectionFromPoint(pt.x, pt.y, true); // TODO: Find a way to make this work: Use transformed BBox instead of evt.target // if (lastX === mouseX && lastY === mouseY // && !rectsIntersect(transbb, {x: pt.x, y: pt.y, width: 0, height: 0})) { // textActions.toSelectMode(true); // } if (evt.target !== curtext && mouseX < lastX + 2 && mouseX > lastX - 2 && mouseY < lastY + 2 && mouseY > lastY - 2) { textActions.toSelectMode(true); } }, /** * @function * @param {Integer} index * @returns {void} */ setCursor: setCursor, /** * @param {Float} x * @param {Float} y * @returns {void} */ toEditMode: function toEditMode(x, y) { allowDbl = false; currentMode = 'textedit'; selectorManager.requestSelector(curtext).showGrips(false); // Make selector group accept clicks /* const selector = */ selectorManager.requestSelector(curtext); // Do we need this? Has side effect of setting lock, so keeping for now, but next line wasn't being used // const sel = selector.selectorRect; textActions.init(); $$b(curtext).css('cursor', 'text'); // if (supportsEditableText()) { // curtext.setAttribute('editable', 'simple'); // return; // } if (!arguments.length) { setCursor(); } else { var pt = screenToPt(x, y); setCursorFromPoint(pt.x, pt.y); } setTimeout(function () { allowDbl = true; }, 300); }, /** * @param {boolean|Element} selectElem * @fires module:svgcanvas.SvgCanvas#event:selected * @returns {void} */ toSelectMode: function toSelectMode(selectElem) { currentMode = 'select'; clearInterval(blinker); blinker = null; if (selblock) { $$b(selblock).attr('display', 'none'); } if (cursor) { $$b(cursor).attr('visibility', 'hidden'); } $$b(curtext).css('cursor', 'move'); if (selectElem) { clearSelection(); $$b(curtext).css('cursor', 'move'); call('selected', [curtext]); addToSelection([curtext], true); } if (curtext && !curtext.textContent.length) { // No content, so delete canvas.deleteSelectedElements(); } $$b(textinput).blur(); curtext = false; // if (supportsEditableText()) { // curtext.removeAttribute('editable'); // } }, /** * @param {Element} elem * @returns {void} */ setInputElem: function setInputElem(elem) { textinput = elem; // $(textinput).blur(hideCursor); }, /** * @returns {void} */ clear: function clear() { if (currentMode === 'textedit') { textActions.toSelectMode(); } }, /** * @param {Element} inputElem Not in use * @returns {void} */ init: function init(inputElem) { if (!curtext) { return; } var i, end; // if (supportsEditableText()) { // curtext.select(); // return; // } if (!curtext.parentNode) { // Result of the ffClone, need to get correct element curtext = selectedElements[0]; selectorManager.requestSelector(curtext).showGrips(false); } var str = curtext.textContent; var len = str.length; var xform = curtext.getAttribute('transform'); textbb = getBBox(curtext); matrix = xform ? getMatrix(curtext) : null; chardata = []; chardata.length = len; textinput.focus(); $$b(curtext).unbind('dblclick', selectWord).dblclick(selectWord); if (!len) { end = { x: textbb.x + textbb.width / 2, width: 0 }; } for (i = 0; i < len; i++) { var start = curtext.getStartPositionOfChar(i); end = curtext.getEndPositionOfChar(i); if (!supportsGoodTextCharPos()) { var offset = canvas.contentW * currentZoom; start.x -= offset; end.x -= offset; start.x /= currentZoom; end.x /= currentZoom; } // Get a "bbox" equivalent for each character. Uses the // bbox data of the actual text for y, height purposes // TODO: Decide if y, width and height are actually necessary chardata[i] = { x: start.x, y: textbb.y, // start.y? width: end.x - start.x, height: textbb.height }; } // Add a last bbox for cursor at end of text chardata.push({ x: end.x, width: 0 }); setSelection(textinput.selectionStart, textinput.selectionEnd, true); } } ); }(); /** * Group: Serialization. */ /** * Looks at DOM elements inside the `<defs>` to see if they are referred to, * removes them from the DOM if they are not. * @function module:svgcanvas.SvgCanvas#removeUnusedDefElems * @returns {Integer} The number of elements that were removed */ var removeUnusedDefElems = this.removeUnusedDefElems = function () { var defs = svgcontent.getElementsByTagNameNS(NS.SVG, 'defs'); if (!defs || !defs.length) { return 0; } // if (!defs.firstChild) { return; } var defelemUses = []; var numRemoved = 0; var attrs = ['fill', 'stroke', 'filter', 'marker-start', 'marker-mid', 'marker-end']; var alen = attrs.length; var allEls = svgcontent.getElementsByTagNameNS(NS.SVG, '*'); var allLen = allEls.length; var i, j; for (i = 0; i < allLen; i++) { var el = allEls[i]; for (j = 0; j < alen; j++) { var ref = getUrlFromAttr(el.getAttribute(attrs[j])); if (ref) { defelemUses.push(ref.substr(1)); } } // gradients can refer to other gradients var href = getHref(el); if (href && href.startsWith('#')) { defelemUses.push(href.substr(1)); } } var defelems = $$b(defs).find('linearGradient, radialGradient, filter, marker, svg, symbol'); i = defelems.length; while (i--) { var defelem = defelems[i]; var id = defelem.id; if (!defelemUses.includes(id)) { // Not found, so remove (but remember) removedElements[id] = defelem; defelem.remove(); numRemoved++; } } return numRemoved; }; /** * Main function to set up the SVG content for output. * @function module:svgcanvas.SvgCanvas#svgCanvasToString * @returns {string} The SVG image for output */ this.svgCanvasToString = function () { // keep calling it until there are none to remove while (removeUnusedDefElems() > 0) {} // eslint-disable-line no-empty pathActions$1.clear(true); // Keep SVG-Edit comment on top $$b.each(svgcontent.childNodes, function (i, node) { if (i && node.nodeType === 8 && node.data.includes('Created with')) { svgcontent.firstChild.before(node); } }); // Move out of in-group editing mode if (currentGroup) { leaveContext(); selectOnly([currentGroup]); } var nakedSvgs = []; // Unwrap gsvg if it has no special attributes (only id and style) $$b(svgcontent).find('g:data(gsvg)').each(function () { var attrs = this.attributes; var len = attrs.length; for (var i = 0; i < len; i++) { if (attrs[i].nodeName === 'id' || attrs[i].nodeName === 'style') { len--; } } // No significant attributes, so ungroup if (len <= 0) { var svg = this.firstChild; nakedSvgs.push(svg); $$b(this).replaceWith(svg); } }); var output = this.svgToString(svgcontent, 0); // Rewrap gsvg if (nakedSvgs.length) { $$b(nakedSvgs).each(function () { groupSvgElem(this); }); } return output; }; /** * Sub function ran on each SVG element to convert it to a string as desired. * @function module:svgcanvas.SvgCanvas#svgToString * @param {Element} elem - The SVG element to convert * @param {Integer} indent - Number of spaces to indent this tag * @returns {string} The given element as an SVG tag */ this.svgToString = function (elem, indent) { var out = []; var unit = curConfig.baseUnit; var unitRe = new RegExp('^-?[\\d\\.]+' + unit + '$'); if (elem) { cleanupElement(elem); var attrs = _toConsumableArray(elem.attributes); var childs = elem.childNodes; attrs.sort(function (a, b) { return a.name > b.name ? -1 : 1; }); for (var i = 0; i < indent; i++) { out.push(' '); } out.push('<'); out.push(elem.nodeName); if (elem.id === 'svgcontent') { // Process root element separately var res = getResolution(); var vb = ''; // TODO: Allow this by dividing all values by current baseVal // Note that this also means we should properly deal with this on import // if (curConfig.baseUnit !== 'px') { // const unit = curConfig.baseUnit; // const unitM = getTypeMap()[unit]; // res.w = shortFloat(res.w / unitM); // res.h = shortFloat(res.h / unitM); // vb = ' viewBox="' + [0, 0, res.w, res.h].join(' ') + '"'; // res.w += unit; // res.h += unit; // } if (unit !== 'px') { res.w = convertUnit(res.w, unit) + unit; res.h = convertUnit(res.h, unit) + unit; } out.push(' width="' + res.w + '" height="' + res.h + '"' + vb + ' xmlns="' + NS.SVG + '"'); var nsuris = {}; // Check elements for namespaces, add if found $$b(elem).find('*').andSelf().each(function () { // const el = this; // for some elements have no attribute var uri = this.namespaceURI; if (uri && !nsuris[uri] && nsMap[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml') { nsuris[uri] = true; out.push(' xmlns:' + nsMap[uri] + '="' + uri + '"'); } $$b.each(this.attributes, function (i, attr) { var u = attr.namespaceURI; if (u && !nsuris[u] && nsMap[u] !== 'xmlns' && nsMap[u] !== 'xml') { nsuris[u] = true; out.push(' xmlns:' + nsMap[u] + '="' + u + '"'); } }); }); var _i2 = attrs.length; var attrNames = ['width', 'height', 'xmlns', 'x', 'y', 'viewBox', 'id', 'overflow']; while (_i2--) { var attr = attrs[_i2]; var attrVal = toXml(attr.value); // Namespaces have already been dealt with, so skip if (attr.nodeName.startsWith('xmlns:')) { continue; } // only serialize attributes we don't use internally if (attrVal !== '' && !attrNames.includes(attr.localName)) { if (!attr.namespaceURI || nsMap[attr.namespaceURI]) { out.push(' '); out.push(attr.nodeName); out.push('="'); out.push(attrVal); out.push('"'); } } } } else { // Skip empty defs if (elem.nodeName === 'defs' && !elem.firstChild) { return ''; } var mozAttrs = ['-moz-math-font-style', '_moz-math-font-style']; for (var _i3 = attrs.length - 1; _i3 >= 0; _i3--) { var _attr = attrs[_i3]; var _attrVal = toXml(_attr.value); // remove bogus attributes added by Gecko if (mozAttrs.includes(_attr.localName)) { continue; } if (_attrVal === 'null') { var styleName = _attr.localName.replace(/-[a-z]/g, function (s) { return s[1].toUpperCase(); }); if (Object.prototype.hasOwnProperty.call(elem.style, styleName)) { continue; } } if (_attrVal !== '') { if (_attrVal.startsWith('pointer-events')) { continue; } if (_attr.localName === 'class' && _attrVal.startsWith('se_')) { continue; } out.push(' '); if (_attr.localName === 'd') { _attrVal = pathActions$1.convertPath(elem, true); } if (!isNaN(_attrVal)) { _attrVal = shortFloat(_attrVal); } else if (unitRe.test(_attrVal)) { _attrVal = shortFloat(_attrVal) + unit; } // Embed images when saving if (saveOptions.apply && elem.nodeName === 'image' && _attr.localName === 'href' && saveOptions.images && saveOptions.images === 'embed') { var img = encodableImages[_attrVal]; if (img) { _attrVal = img; } } // map various namespaces to our fixed namespace prefixes // (the default xmlns attribute itself does not get a prefix) if (!_attr.namespaceURI || _attr.namespaceURI === NS.SVG || nsMap[_attr.namespaceURI]) { out.push(_attr.nodeName); out.push('="'); out.push(_attrVal); out.push('"'); } } } } if (elem.hasChildNodes()) { out.push('>'); indent++; var bOneLine = false; for (var _i4 = 0; _i4 < childs.length; _i4++) { var child = childs.item(_i4); switch (child.nodeType) { case 1: // element node out.push('\n'); out.push(this.svgToString(child, indent)); break; case 3: { // text node var str = child.nodeValue.replace(/^\s+|\s+$/g, ''); if (str !== '') { bOneLine = true; out.push(String(toXml(str))); } break; } case 4: // cdata node out.push('\n'); out.push(new Array(indent + 1).join(' ')); out.push('<![CDATA['); out.push(child.nodeValue); out.push(']]>'); break; case 8: // comment out.push('\n'); out.push(new Array(indent + 1).join(' ')); out.push('<!--'); out.push(child.data); out.push('-->'); break; } // switch on node type } indent--; if (!bOneLine) { out.push('\n'); for (var _i5 = 0; _i5 < indent; _i5++) { out.push(' '); } } out.push('</'); out.push(elem.nodeName); out.push('>'); } else { out.push('/>'); } } return out.join(''); }; // end svgToString() /** * Function to run when image data is found. * @callback module:svgcanvas.ImageEmbeddedCallback * @param {string|false} result Data URL * @returns {void} */ /** * Converts a given image file to a data URL when possible, then runs a given callback. * @function module:svgcanvas.SvgCanvas#embedImage * @param {string} src - The path/URL of the image * @returns {Promise<string|false>} Resolves to a Data URL (string|false) */ this.embedImage = function (src) { // Todo: Remove this Promise in favor of making an async/await `Image.load` utility // eslint-disable-next-line promise/avoid-new return new Promise(function (resolve, reject) { // load in the image and once it's loaded, get the dimensions $$b(new Image()).load(function (response, status, xhr) { if (status === 'error') { reject(new Error('Error loading image: ' + xhr.status + ' ' + xhr.statusText)); return; } // create a canvas the same size as the raster image var cvs = document.createElement('canvas'); cvs.width = this.width; cvs.height = this.height; // load the raster image into the canvas cvs.getContext('2d').drawImage(this, 0, 0); // retrieve the data: URL try { var urldata = ';svgedit_url=' + encodeURIComponent(src); urldata = cvs.toDataURL().replace(';base64', urldata + ';base64'); encodableImages[src] = urldata; } catch (e) { encodableImages[src] = false; } lastGoodImgUrl = src; resolve(encodableImages[src]); }).attr('src', src); }); }; /** * Sets a given URL to be a "last good image" URL. * @function module:svgcanvas.SvgCanvas#setGoodImage * @param {string} val * @returns {void} */ this.setGoodImage = function (val) { lastGoodImgUrl = val; }; /** * Does nothing by default, handled by optional widget/extension. * @function module:svgcanvas.SvgCanvas#open * @returns {void} */ this.open = function () { /* */ }; /** * Serializes the current drawing into SVG XML text and passes it to the 'saved' handler. * This function also includes the XML prolog. Clients of the `SvgCanvas` bind their save * function to the 'saved' event. * @function module:svgcanvas.SvgCanvas#save * @param {module:svgcanvas.SaveOptions} opts * @fires module:svgcanvas.SvgCanvas#event:saved * @returns {void} */ this.save = function (opts) { // remove the selected outline before serializing clearSelection(); // Update save options if provided if (opts) { $$b.extend(saveOptions, opts); } saveOptions.apply = true; // no need for doctype, see https://jwatt.org/svg/authoring/#doctype-declaration var str = this.svgCanvasToString(); call('saved', str); }; /** * @typedef {PlainObject} module:svgcanvas.IssuesAndCodes * @property {string[]} issueCodes The locale-independent code names * @property {string[]} issues The localized descriptions */ /** * Codes only is useful for locale-independent detection. * @returns {module:svgcanvas.IssuesAndCodes} */ function getIssues() { // remove the selected outline before serializing clearSelection(); // Check for known CanVG issues var issues = []; var issueCodes = []; // Selector and notice var issueList = { feGaussianBlur: uiStrings.exportNoBlur, foreignObject: uiStrings.exportNoforeignObject, '[stroke-dasharray]': uiStrings.exportNoDashArray }; var content = $$b(svgcontent); // Add font/text check if Canvas Text API is not implemented if (!('font' in $$b('<canvas>')[0].getContext('2d'))) { issueList.text = uiStrings.exportNoText; } $$b.each(issueList, function (sel, descr) { if (content.find(sel).length) { issueCodes.push(sel); issues.push(descr); } }); return { issues: issues, issueCodes: issueCodes }; } /** * @typedef {"feGaussianBlur"|"foreignObject"|"[stroke-dasharray]"|"text"} module:svgcanvas.IssueCode */ /** * @typedef {PlainObject} module:svgcanvas.ImageExportedResults * @property {string} datauri Contents as a Data URL * @property {string} bloburl May be the empty string * @property {string} svg The SVG contents as a string * @property {string[]} issues The localization messages of `issueCodes` * @property {module:svgcanvas.IssueCode[]} issueCodes CanVG issues found with the SVG * @property {"PNG"|"JPEG"|"BMP"|"WEBP"|"ICO"} type The chosen image type * @property {"image/png"|"image/jpeg"|"image/bmp"|"image/webp"} mimeType The image MIME type * @property {Float} quality A decimal between 0 and 1 (for use with JPEG or WEBP) * @property {string} exportWindowName A convenience for passing along a `window.name` to target a window on which the export could be added */ /** * Generates a PNG (or JPG, BMP, WEBP) Data URL based on the current image, * then calls "exported" with an object including the string, image * information, and any issues found. * @function module:svgcanvas.SvgCanvas#rasterExport * @param {"PNG"|"JPEG"|"BMP"|"WEBP"|"ICO"} [imgType="PNG"] * @param {Float} [quality] Between 0 and 1 * @param {string} [exportWindowName] * @param {PlainObject} [opts] * @param {boolean} [opts.avoidEvent] * @fires module:svgcanvas.SvgCanvas#event:exported * @todo Confirm/fix ICO type * @returns {Promise<module:svgcanvas.ImageExportedResults>} Resolves to {@link module:svgcanvas.ImageExportedResults} */ this.rasterExport = /*#__PURE__*/function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(imgType, quality, exportWindowName) { var opts, type, mimeType, _getIssues, issues, issueCodes, svg, c, _args2 = arguments; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: opts = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : {}; type = imgType === 'ICO' ? 'BMP' : imgType || 'PNG'; mimeType = 'image/' + type.toLowerCase(); _getIssues = getIssues(), issues = _getIssues.issues, issueCodes = _getIssues.issueCodes; svg = this.svgCanvasToString(); if (!$$b('#export_canvas').length) { $$b('<canvas>', { id: 'export_canvas' }).hide().appendTo('body'); } c = $$b('#export_canvas')[0]; c.width = canvas.contentW; c.height = canvas.contentH; _context2.next = 11; return canvg(c, svg); case 11: return _context2.abrupt("return", new Promise(function (resolve, reject) { var dataURLType = type.toLowerCase(); var datauri = quality ? c.toDataURL('image/' + dataURLType, quality) : c.toDataURL('image/' + dataURLType); var bloburl; /** * Called when `bloburl` is available for export. * @returns {void} */ function done() { var obj = { datauri: datauri, bloburl: bloburl, svg: svg, issues: issues, issueCodes: issueCodes, type: imgType, mimeType: mimeType, quality: quality, exportWindowName: exportWindowName }; if (!opts.avoidEvent) { call('exported', obj); } resolve(obj); } if (c.toBlob) { c.toBlob(function (blob) { bloburl = createObjectURL(blob); done(); }, mimeType, quality); return; } bloburl = dataURLToObjectURL(datauri); done(); })); case 12: case "end": return _context2.stop(); } } }, _callee2, this); })); return function (_x4, _x5, _x6) { return _ref5.apply(this, arguments); }; }(); /** * @typedef {void|"save"|"arraybuffer"|"blob"|"datauristring"|"dataurlstring"|"dataurlnewwindow"|"datauri"|"dataurl"} external:jsPDF.OutputType * @todo Newer version to add also allows these `outputType` values "bloburi"|"bloburl" which return strings, so document here and for `outputType` of `module:svgcanvas.PDFExportedResults` below if added */ /** * @typedef {PlainObject} module:svgcanvas.PDFExportedResults * @property {string} svg The SVG PDF output * @property {string|ArrayBuffer|Blob|window} output The output based on the `outputType`; * if `undefined`, "datauristring", "dataurlstring", "datauri", * or "dataurl", will be a string (`undefined` gives a document, while the others * build as Data URLs; "datauri" and "dataurl" change the location of the current page); if * "arraybuffer", will return `ArrayBuffer`; if "blob", returns a `Blob`; * if "dataurlnewwindow", will change the current page's location and return a string * if in Safari and no window object is found; otherwise opens in, and returns, a new `window` * object; if "save", will have the same return as "dataurlnewwindow" if * `navigator.getUserMedia` support is found without `URL.createObjectURL` support; otherwise * returns `undefined` but attempts to save * @property {external:jsPDF.OutputType} outputType * @property {string[]} issues The human-readable localization messages of corresponding `issueCodes` * @property {module:svgcanvas.IssueCode[]} issueCodes * @property {string} exportWindowName */ /** * Generates a PDF based on the current image, then calls "exportedPDF" with * an object including the string, the data URL, and any issues found. * @function module:svgcanvas.SvgCanvas#exportPDF * @param {string} [exportWindowName] Will also be used for the download file name here * @param {external:jsPDF.OutputType} [outputType="dataurlstring"] * @fires module:svgcanvas.SvgCanvas#event:exportedPDF * @returns {Promise<module:svgcanvas.PDFExportedResults>} Resolves to {@link module:svgcanvas.PDFExportedResults} */ this.exportPDF = /*#__PURE__*/function () { var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(exportWindowName) { var outputType, res, orientation, unit, doc, docTitle, _getIssues2, issues, issueCodes, obj, _args3 = arguments; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: outputType = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : isChrome() ? 'save' : undefined; res = getResolution(); orientation = res.w > res.h ? 'landscape' : 'portrait'; unit = 'pt'; // curConfig.baseUnit; // We could use baseUnit, but that is presumably not intended for export purposes // Todo: Give options to use predefined jsPDF formats like "a4", etc. from pull-down (with option to keep customizable) doc = g({ orientation: orientation, unit: unit, format: [res.w, res.h] // , compressPdf: true }); docTitle = getDocumentTitle(); doc.setProperties({ title: docTitle /* , subject: '', author: '', keywords: '', creator: '' */ }); _getIssues2 = getIssues(), issues = _getIssues2.issues, issueCodes = _getIssues2.issueCodes; // const svg = this.svgCanvasToString(); // await doc.addSvgAsImage(svg) _context3.next = 10; return doc.svg(svgcontent, { x: 0, y: 0, width: res.w, height: res.h }); case 10: // doc.output('save'); // Works to open in a new // window; todo: configure this and other export // options to optionally work in this manner as // opposed to opening a new tab outputType = outputType || 'dataurlstring'; obj = { issues: issues, issueCodes: issueCodes, exportWindowName: exportWindowName, outputType: outputType }; obj.output = doc.output(outputType, outputType === 'save' ? exportWindowName || 'svg.pdf' : undefined); call('exportedPDF', obj); return _context3.abrupt("return", obj); case 15: case "end": return _context3.stop(); } } }, _callee3); })); return function (_x7) { return _ref6.apply(this, arguments); }; }(); /** * Returns the current drawing as raw SVG XML text. * @function module:svgcanvas.SvgCanvas#getSvgString * @returns {string} The current drawing as raw SVG XML text. */ this.getSvgString = function () { saveOptions.apply = false; return this.svgCanvasToString(); }; /** * This function determines whether to use a nonce in the prefix, when * generating IDs for future documents in SVG-Edit. * If you're controlling SVG-Edit externally, and want randomized IDs, call * this BEFORE calling `svgCanvas.setSvgString`. * @function module:svgcanvas.SvgCanvas#randomizeIds * @param {boolean} [enableRandomization] If true, adds a nonce to the prefix. Thus * `svgCanvas.randomizeIds() <==> svgCanvas.randomizeIds(true)` * @returns {void} */ this.randomizeIds = function (enableRandomization) { if (arguments.length > 0 && enableRandomization === false) { randomizeIds(false, getCurrentDrawing()); } else { randomizeIds(true, getCurrentDrawing()); } }; /** * Ensure each element has a unique ID. * @function module:svgcanvas.SvgCanvas#uniquifyElems * @param {Element} g - The parent element of the tree to give unique IDs * @returns {void} */ var uniquifyElems = this.uniquifyElems = function (g) { var ids = {}; // TODO: Handle markers and connectors. These are not yet re-identified properly // as their referring elements do not get remapped. // // <marker id='se_marker_end_svg_7'/> // <polyline id='svg_7' se:connector='svg_1 svg_6' marker-end='url(#se_marker_end_svg_7)'/> // // Problem #1: if svg_1 gets renamed, we do not update the polyline's se:connector attribute // Problem #2: if the polyline svg_7 gets renamed, we do not update the marker id nor the polyline's marker-end attribute var refElems = ['filter', 'linearGradient', 'pattern', 'radialGradient', 'symbol', 'textPath', 'use']; walkTree(g, function (n) { // if it's an element node if (n.nodeType === 1) { // and the element has an ID if (n.id) { // and we haven't tracked this ID yet if (!(n.id in ids)) { // add this id to our map ids[n.id] = { elem: null, attrs: [], hrefs: [] }; } ids[n.id].elem = n; } // now search for all attributes on this element that might refer // to other elements $$b.each(refAttrs, function (i, attr) { var attrnode = n.getAttributeNode(attr); if (attrnode) { // the incoming file has been sanitized, so we should be able to safely just strip off the leading # var url = getUrlFromAttr(attrnode.value), refid = url ? url.substr(1) : null; if (refid) { if (!(refid in ids)) { // add this id to our map ids[refid] = { elem: null, attrs: [], hrefs: [] }; } ids[refid].attrs.push(attrnode); } } }); // check xlink:href now var href = getHref(n); // TODO: what if an <image> or <a> element refers to an element internally? if (href && refElems.includes(n.nodeName)) { var refid = href.substr(1); if (refid) { if (!(refid in ids)) { // add this id to our map ids[refid] = { elem: null, attrs: [], hrefs: [] }; } ids[refid].hrefs.push(n); } } } }); // in ids, we now have a map of ids, elements and attributes, let's re-identify for (var oldid in ids) { if (!oldid) { continue; } var elem = ids[oldid].elem; if (elem) { var newid = getNextId(); // assign element its new id elem.id = newid; // remap all url() attributes var attrs = ids[oldid].attrs; var j = attrs.length; while (j--) { var attr = attrs[j]; attr.ownerElement.setAttribute(attr.name, 'url(#' + newid + ')'); } // remap all href attributes var hreffers = ids[oldid].hrefs; var k = hreffers.length; while (k--) { var hreffer = hreffers[k]; setHref(hreffer, '#' + newid); } } } }; /** * Assigns reference data for each use element. * @function module:svgcanvas.SvgCanvas#setUseData * @param {Element} parent * @returns {void} */ var setUseData = this.setUseData = function (parent) { var elems = $$b(parent); if (parent.tagName !== 'use') { elems = elems.find('use'); } elems.each(function () { var id = getHref(this).substr(1); var refElem = getElem(id); if (!refElem) { return; } $$b(this).data('ref', refElem); if (refElem.tagName === 'symbol' || refElem.tagName === 'svg') { $$b(this).data('symbol', refElem).data('ref', refElem); } }); }; /** * Converts gradients from userSpaceOnUse to objectBoundingBox. * @function module:svgcanvas.SvgCanvas#convertGradients * @param {Element} elem * @returns {void} */ var convertGradients = this.convertGradients = function (elem) { var elems = $$b(elem).find('linearGradient, radialGradient'); if (!elems.length && isWebkit()) { // Bug in webkit prevents regular *Gradient selector search elems = $$b(elem).find('*').filter(function () { return this.tagName.includes('Gradient'); }); } elems.each(function () { var grad = this; if ($$b(grad).attr('gradientUnits') === 'userSpaceOnUse') { // TODO: Support more than one element with this ref by duplicating parent grad var fillStrokeElems = $$b(svgcontent).find('[fill="url(#' + grad.id + ')"],[stroke="url(#' + grad.id + ')"]'); if (!fillStrokeElems.length) { return; } // get object's bounding box var bb = getBBox(fillStrokeElems[0]); // This will occur if the element is inside a <defs> or a <symbol>, // in which we shouldn't need to convert anyway. if (!bb) { return; } if (grad.tagName === 'linearGradient') { var gCoords = $$b(grad).attr(['x1', 'y1', 'x2', 'y2']); // If has transform, convert var tlist = grad.gradientTransform.baseVal; if (tlist && tlist.numberOfItems > 0) { var m = transformListToTransform(tlist).matrix; var pt1 = transformPoint(gCoords.x1, gCoords.y1, m); var pt2 = transformPoint(gCoords.x2, gCoords.y2, m); gCoords.x1 = pt1.x; gCoords.y1 = pt1.y; gCoords.x2 = pt2.x; gCoords.y2 = pt2.y; grad.removeAttribute('gradientTransform'); } $$b(grad).attr({ x1: (gCoords.x1 - bb.x) / bb.width, y1: (gCoords.y1 - bb.y) / bb.height, x2: (gCoords.x2 - bb.x) / bb.width, y2: (gCoords.y2 - bb.y) / bb.height }); grad.removeAttribute('gradientUnits'); } // else { // Note: radialGradient elements cannot be easily converted // because userSpaceOnUse will keep circular gradients, while // objectBoundingBox will x/y scale the gradient according to // its bbox. // // For now we'll do nothing, though we should probably have // the gradient be updated as the element is moved, as // inkscape/illustrator do. // // const gCoords = $(grad).attr(['cx', 'cy', 'r']); // // $(grad).attr({ // cx: (gCoords.cx - bb.x) / bb.width, // cy: (gCoords.cy - bb.y) / bb.height, // r: gCoords.r // }); // // grad.removeAttribute('gradientUnits'); // } } }); }; /** * Converts selected/given `<use>` or child SVG element to a group. * @function module:svgcanvas.SvgCanvas#convertToGroup * @param {Element} elem * @fires module:svgcanvas.SvgCanvas#event:selected * @returns {void} */ var convertToGroup = this.convertToGroup = function (elem) { if (!elem) { elem = selectedElements[0]; } var $elem = $$b(elem); var batchCmd = new BatchCommand$1(); var ts; if ($elem.data('gsvg')) { // Use the gsvg as the new group var svg = elem.firstChild; var pt = $$b(svg).attr(['x', 'y']); $$b(elem.firstChild.firstChild).unwrap(); $$b(elem).removeData('gsvg'); var tlist = getTransformList(elem); var xform = svgroot.createSVGTransform(); xform.setTranslate(pt.x, pt.y); tlist.appendItem(xform); recalculateDimensions(elem); call('selected', [elem]); } else if ($elem.data('symbol')) { elem = $elem.data('symbol'); ts = $elem.attr('transform'); var pos = $elem.attr(['x', 'y']); var vb = elem.getAttribute('viewBox'); if (vb) { var nums = vb.split(' '); pos.x -= Number(nums[0]); pos.y -= Number(nums[1]); } // Not ideal, but works ts += ' translate(' + (pos.x || 0) + ',' + (pos.y || 0) + ')'; var prev = $elem.prev(); // Remove <use> element batchCmd.addSubCommand(new RemoveElementCommand$1($elem[0], $elem[0].nextSibling, $elem[0].parentNode)); $elem.remove(); // See if other elements reference this symbol var hasMore = $$b(svgcontent).find('use:data(symbol)').length; var g = svgdoc.createElementNS(NS.SVG, 'g'); var childs = elem.childNodes; var i; for (i = 0; i < childs.length; i++) { g.append(childs[i].cloneNode(true)); } // Duplicate the gradients for Gecko, since they weren't included in the <symbol> if (isGecko()) { var dupeGrads = $$b(findDefs()).children('linearGradient,radialGradient,pattern').clone(); $$b(g).append(dupeGrads); } if (ts) { g.setAttribute('transform', ts); } var parent = elem.parentNode; uniquifyElems(g); // Put the dupe gradients back into <defs> (after uniquifying them) if (isGecko()) { $$b(findDefs()).append($$b(g).find('linearGradient,radialGradient,pattern')); } // now give the g itself a new id g.id = getNextId(); prev.after(g); if (parent) { if (!hasMore) { // remove symbol/svg element var _elem = elem, nextSibling = _elem.nextSibling; elem.remove(); batchCmd.addSubCommand(new RemoveElementCommand$1(elem, nextSibling, parent)); } batchCmd.addSubCommand(new InsertElementCommand$1(g)); } setUseData(g); if (isGecko()) { convertGradients(findDefs()); } else { convertGradients(g); } // recalculate dimensions on the top-level children so that unnecessary transforms // are removed walkTreePost(g, function (n) { try { recalculateDimensions(n); } catch (e) { console.log(e); // eslint-disable-line no-console } }); // Give ID for any visible element missing one $$b(g).find(visElems).each(function () { if (!this.id) { this.id = getNextId(); } }); selectOnly([g]); var cm = pushGroupProperties(g, true); if (cm) { batchCmd.addSubCommand(cm); } addCommandToHistory(batchCmd); } else { console.log('Unexpected element to ungroup:', elem); // eslint-disable-line no-console } }; /** * This function sets the current drawing as the input SVG XML. * @function module:svgcanvas.SvgCanvas#setSvgString * @param {string} xmlString - The SVG as XML text. * @param {boolean} [preventUndo=false] - Indicates if we want to do the * changes without adding them to the undo stack - e.g. for initializing a * drawing on page load. * @fires module:svgcanvas.SvgCanvas#event:setnonce * @fires module:svgcanvas.SvgCanvas#event:unsetnonce * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {boolean} This function returns `false` if the set was * unsuccessful, `true` otherwise. */ this.setSvgString = function (xmlString, preventUndo) { try { // convert string into XML document var newDoc = text2xml(xmlString); if (newDoc.firstElementChild && newDoc.firstElementChild.namespaceURI !== NS.SVG) { return false; } this.prepareSvg(newDoc); var batchCmd = new BatchCommand$1('Change Source'); // remove old svg document var _svgcontent = svgcontent, nextSibling = _svgcontent.nextSibling; svgcontent.remove(); var oldzoom = svgcontent; batchCmd.addSubCommand(new RemoveElementCommand$1(oldzoom, nextSibling, svgroot)); // set new svg document // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode() if (svgdoc.adoptNode) { svgcontent = svgdoc.adoptNode(newDoc.documentElement); } else { svgcontent = svgdoc.importNode(newDoc.documentElement, true); } svgroot.append(svgcontent); var content = $$b(svgcontent); canvas.current_drawing_ = new Drawing(svgcontent, idprefix); // retrieve or set the nonce var nonce = getCurrentDrawing().getNonce(); if (nonce) { call('setnonce', nonce); } else { call('unsetnonce'); } // change image href vals if possible content.find('image').each(function () { var image = this; preventClickDefault(image); var val = getHref(this); if (val) { if (val.startsWith('data:')) { // Check if an SVG-edit data URI var m = val.match(/svgedit_url=(.*?);/); // const m = val.match(/svgedit_url=(?<url>.*?);/); if (m) { var url = decodeURIComponent(m[1]); // const url = decodeURIComponent(m.groups.url); $$b(new Image()).load(function () { image.setAttributeNS(NS.XLINK, 'xlink:href', url); }).attr('src', url); } } // Add to encodableImages if it loads canvas.embedImage(val); } }); // Wrap child SVGs in group elements content.find('svg').each(function () { // Skip if it's in a <defs> if ($$b(this).closest('defs').length) { return; } uniquifyElems(this); // Check if it already has a gsvg group var pa = this.parentNode; if (pa.childNodes.length === 1 && pa.nodeName === 'g') { $$b(pa).data('gsvg', this); pa.id = pa.id || getNextId(); } else { groupSvgElem(this); } }); // For Firefox: Put all paint elems in defs if (isGecko()) { content.find('linearGradient, radialGradient, pattern').appendTo(findDefs()); } // Set ref element for <use> elements // TODO: This should also be done if the object is re-added through "redo" setUseData(content); convertGradients(content[0]); var attrs = { id: 'svgcontent', overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden' }; var percs = false; // determine proper size if (content.attr('viewBox')) { var vb = content.attr('viewBox').split(' '); attrs.width = vb[2]; attrs.height = vb[3]; // handle content that doesn't have a viewBox } else { $$b.each(['width', 'height'], function (i, dim) { // Set to 100 if not given var val = content.attr(dim) || '100%'; if (String(val).substr(-1) === '%') { // Use user units if percentage given percs = true; } else { attrs[dim] = convertToNum(dim, val); } }); } // identify layers identifyLayers(); // Give ID for any visible layer children missing one content.children().find(visElems).each(function () { if (!this.id) { this.id = getNextId(); } }); // Percentage width/height, so let's base it on visible elements if (percs) { var bb = getStrokedBBoxDefaultVisible(); attrs.width = bb.width + bb.x; attrs.height = bb.height + bb.y; } // Just in case negative numbers are given or // result from the percs calculation if (attrs.width <= 0) { attrs.width = 100; } if (attrs.height <= 0) { attrs.height = 100; } content.attr(attrs); this.contentW = attrs.width; this.contentH = attrs.height; batchCmd.addSubCommand(new InsertElementCommand$1(svgcontent)); // update root to the correct size var changes = content.attr(['width', 'height']); batchCmd.addSubCommand(new ChangeElementCommand$1(svgroot, changes)); // reset zoom currentZoom = 1; // reset transform lists resetListMap(); clearSelection(); clearData(); svgroot.append(selectorManager.selectorParentGroup); if (!preventUndo) addCommandToHistory(batchCmd); call('changed', [svgcontent]); } catch (e) { console.log(e); // eslint-disable-line no-console return false; } return true; }; /** * This function imports the input SVG XML as a `<symbol>` in the `<defs>`, then adds a * `<use>` to the current layer. * @function module:svgcanvas.SvgCanvas#importSvgString * @param {string} xmlString - The SVG as XML text. * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {null|Element} This function returns null if the import was unsuccessful, or the element otherwise. * @todo * - properly handle if namespace is introduced by imported content (must add to svgcontent * and update all prefixes in the imported node) * - properly handle recalculating dimensions, `recalculateDimensions()` doesn't handle * arbitrary transform lists, but makes some assumptions about how the transform list * was obtained */ this.importSvgString = function (xmlString) { var j, ts, useEl; try { // Get unique ID var uid = encode64(xmlString.length + xmlString).substr(0, 32); var useExisting = false; // Look for symbol and make sure symbol exists in image if (importIds[uid]) { if ($$b(importIds[uid].symbol).parents('#svgroot').length) { useExisting = true; } } var batchCmd = new BatchCommand$1('Import Image'); var symbol; if (useExisting) { symbol = importIds[uid].symbol; ts = importIds[uid].xform; } else { // convert string into XML document var newDoc = text2xml(xmlString); this.prepareSvg(newDoc); // import new svg document into our document var svg; // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode() if (svgdoc.adoptNode) { svg = svgdoc.adoptNode(newDoc.documentElement); } else { svg = svgdoc.importNode(newDoc.documentElement, true); } uniquifyElems(svg); var innerw = convertToNum('width', svg.getAttribute('width')), innerh = convertToNum('height', svg.getAttribute('height')), innervb = svg.getAttribute('viewBox'), // if no explicit viewbox, create one out of the width and height vb = innervb ? innervb.split(' ') : [0, 0, innerw, innerh]; for (j = 0; j < 4; ++j) { vb[j] = Number(vb[j]); } // TODO: properly handle preserveAspectRatio var // canvasw = +svgcontent.getAttribute('width'), canvash = Number(svgcontent.getAttribute('height')); // imported content should be 1/3 of the canvas on its largest dimension if (innerh > innerw) { ts = 'scale(' + canvash / 3 / vb[3] + ')'; } else { ts = 'scale(' + canvash / 3 / vb[2] + ')'; } // Hack to make recalculateDimensions understand how to scale ts = 'translate(0) ' + ts + ' translate(0)'; symbol = svgdoc.createElementNS(NS.SVG, 'symbol'); var defs = findDefs(); if (isGecko()) { // Move all gradients into root for Firefox, workaround for this bug: // https://bugzilla.mozilla.org/show_bug.cgi?id=353575 // TODO: Make this properly undo-able. $$b(svg).find('linearGradient, radialGradient, pattern').appendTo(defs); } while (svg.firstChild) { var first = svg.firstChild; symbol.append(first); } var attrs = svg.attributes; var _iterator2 = _createForOfIteratorHelper(attrs), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var attr = _step2.value; // Ok for `NamedNodeMap` symbol.setAttribute(attr.nodeName, attr.value); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } symbol.id = getNextId(); // Store data importIds[uid] = { symbol: symbol, xform: ts }; findDefs().append(symbol); batchCmd.addSubCommand(new InsertElementCommand$1(symbol)); } useEl = svgdoc.createElementNS(NS.SVG, 'use'); useEl.id = getNextId(); setHref(useEl, '#' + symbol.id); (currentGroup || getCurrentDrawing().getCurrentLayer()).append(useEl); batchCmd.addSubCommand(new InsertElementCommand$1(useEl)); clearSelection(); useEl.setAttribute('transform', ts); recalculateDimensions(useEl); $$b(useEl).data('symbol', symbol).data('ref', symbol); addToSelection([useEl]); // TODO: Find way to add this in a recalculateDimensions-parsable way // if (vb[0] !== 0 || vb[1] !== 0) { // ts = 'translate(' + (-vb[0]) + ',' + (-vb[1]) + ') ' + ts; // } addCommandToHistory(batchCmd); call('changed', [svgcontent]); } catch (e) { console.log(e); // eslint-disable-line no-console return null; } // we want to return the element so we can automatically select it return useEl; }; // Could deprecate, but besides external uses, their usage makes clear that // canvas is a dependency for all of these var dr = { identifyLayers: identifyLayers, createLayer: createLayer, cloneLayer: cloneLayer, deleteCurrentLayer: deleteCurrentLayer, setCurrentLayer: setCurrentLayer, renameCurrentLayer: renameCurrentLayer, setCurrentLayerPosition: setCurrentLayerPosition, setLayerVisibility: setLayerVisibility, moveSelectedToLayer: moveSelectedToLayer, mergeLayer: mergeLayer, mergeAllLayers: mergeAllLayers, leaveContext: leaveContext, setContext: setContext }; Object.entries(dr).forEach(function (_ref7) { var _ref8 = _slicedToArray(_ref7, 2), prop = _ref8[0], propVal = _ref8[1]; canvas[prop] = propVal; }); init$3( /** * @implements {module:draw.DrawCanvasInit} */ { pathActions: pathActions$1, getCurrentGroup: function getCurrentGroup() { return currentGroup; }, setCurrentGroup: function setCurrentGroup(cg) { currentGroup = cg; }, getSelectedElements: getSelectedElements, getSVGContent: getSVGContent, undoMgr: undoMgr, elData: elData, getCurrentDrawing: getCurrentDrawing, clearSelection: clearSelection, call: call, addCommandToHistory: addCommandToHistory, /** * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ changeSVGContent: function changeSVGContent() { call('changed', [svgcontent]); } }); /** * Group: Document functions. */ /** * Clears the current document. This is not an undoable action. * @function module:svgcanvas.SvgCanvas#clear * @fires module:svgcanvas.SvgCanvas#event:cleared * @returns {void} */ this.clear = function () { pathActions$1.clear(); clearSelection(); // clear the svgcontent node canvas.clearSvgContentElement(); // create new document canvas.current_drawing_ = new Drawing(svgcontent); // create empty first layer canvas.createLayer('Layer 1'); // clear the undo stack canvas.undoMgr.resetUndoStack(); // reset the selector manager selectorManager.initGroup(); // reset the rubber band box rubberBox = selectorManager.getRubberBandBox(); call('cleared'); }; // Alias function this.linkControlPoints = pathActions$1.linkControlPoints; /** * @function module:svgcanvas.SvgCanvas#getContentElem * @returns {Element} The content DOM element */ this.getContentElem = function () { return svgcontent; }; /** * @function module:svgcanvas.SvgCanvas#getRootElem * @returns {SVGSVGElement} The root DOM element */ this.getRootElem = function () { return svgroot; }; /** * @typedef {PlainObject} DimensionsAndZoom * @property {Float} w Width * @property {Float} h Height * @property {Float} zoom Zoom */ /** * @function module:svgcanvas.SvgCanvas#getResolution * @returns {DimensionsAndZoom} The current dimensions and zoom level in an object */ var getResolution = this.getResolution = function () { // const vb = svgcontent.getAttribute('viewBox').split(' '); // return {w:vb[2], h:vb[3], zoom: currentZoom}; var w = svgcontent.getAttribute('width') / currentZoom; var h = svgcontent.getAttribute('height') / currentZoom; return { w: w, h: h, zoom: currentZoom }; }; /** * @function module:svgcanvas.SvgCanvas#getSnapToGrid * @returns {boolean} The current snap to grid setting */ this.getSnapToGrid = function () { return curConfig.gridSnapping; }; /** * @function module:svgcanvas.SvgCanvas#getVersion * @returns {string} A string which describes the revision number of SvgCanvas. */ this.getVersion = function () { return 'svgcanvas.js ($Rev$)'; }; /** * Update interface strings with given values. * @function module:svgcanvas.SvgCanvas#setUiStrings * @param {module:path.uiStrings} strs - Object with strings (see the [locales API]{@link module:locale.LocaleStrings} and the [tutorial]{@tutorial LocaleDocs}) * @returns {void} */ this.setUiStrings = function (strs) { Object.assign(uiStrings, strs.notification); $$b = jQueryPluginDBox($$b, strs.common); setUiStrings(strs); }; /** * Update configuration options with given values. * @function module:svgcanvas.SvgCanvas#setConfig * @param {module:SVGEditor.Config} opts - Object with options * @returns {void} */ this.setConfig = function (opts) { Object.assign(curConfig, opts); }; /** * @function module:svgcanvas.SvgCanvas#getTitle * @param {Element} [elem] * @returns {string|void} the current group/SVG's title contents or * `undefined` if no element is passed nd there are no selected elements. */ this.getTitle = function (elem) { elem = elem || selectedElements[0]; if (!elem) { return undefined; } elem = $$b(elem).data('gsvg') || $$b(elem).data('symbol') || elem; var childs = elem.childNodes; var _iterator3 = _createForOfIteratorHelper(childs), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var child = _step3.value; if (child.nodeName === 'title') { return child.textContent; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return ''; }; /** * Sets the group/SVG's title content. * @function module:svgcanvas.SvgCanvas#setGroupTitle * @param {string} val * @todo Combine this with `setDocumentTitle` * @returns {void} */ this.setGroupTitle = function (val) { var elem = selectedElements[0]; elem = $$b(elem).data('gsvg') || elem; var ts = $$b(elem).children('title'); var batchCmd = new BatchCommand$1('Set Label'); var title; if (!val.length) { // Remove title element var tsNextSibling = ts.nextSibling; batchCmd.addSubCommand(new RemoveElementCommand$1(ts[0], tsNextSibling, elem)); ts.remove(); } else if (ts.length) { // Change title contents title = ts[0]; batchCmd.addSubCommand(new ChangeElementCommand$1(title, { '#text': title.textContent })); title.textContent = val; } else { // Add title element title = svgdoc.createElementNS(NS.SVG, 'title'); title.textContent = val; $$b(elem).prepend(title); batchCmd.addSubCommand(new InsertElementCommand$1(title)); } addCommandToHistory(batchCmd); }; /** * @function module:svgcanvas.SvgCanvas#getDocumentTitle * @returns {string|void} The current document title or an empty string if not found */ var getDocumentTitle = this.getDocumentTitle = function () { return canvas.getTitle(svgcontent); }; /** * Adds/updates a title element for the document with the given name. * This is an undoable action. * @function module:svgcanvas.SvgCanvas#setDocumentTitle * @param {string} newTitle - String with the new title * @returns {void} */ this.setDocumentTitle = function (newTitle) { var childs = svgcontent.childNodes; var docTitle = false, oldTitle = ''; var batchCmd = new BatchCommand$1('Change Image Title'); var _iterator4 = _createForOfIteratorHelper(childs), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var child = _step4.value; if (child.nodeName === 'title') { docTitle = child; oldTitle = docTitle.textContent; break; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } if (!docTitle) { docTitle = svgdoc.createElementNS(NS.SVG, 'title'); svgcontent.insertBefore(docTitle, svgcontent.firstChild); // svgcontent.firstChild.before(docTitle); // Ok to replace above with this? } if (newTitle.length) { docTitle.textContent = newTitle; } else { // No title given, so element is not necessary docTitle.remove(); } batchCmd.addSubCommand(new ChangeElementCommand$1(docTitle, { '#text': oldTitle })); addCommandToHistory(batchCmd); }; /** * Returns the editor's namespace URL, optionally adding it to the root element. * @function module:svgcanvas.SvgCanvas#getEditorNS * @param {boolean} [add] - Indicates whether or not to add the namespace value * @returns {string} The editor's namespace URL */ this.getEditorNS = function (add) { if (add) { svgcontent.setAttribute('xmlns:se', NS.SE); } return NS.SE; }; /** * Changes the document's dimensions to the given size. * @function module:svgcanvas.SvgCanvas#setResolution * @param {Float|"fit"} x - Number with the width of the new dimensions in user units. * Can also be the string "fit" to indicate "fit to content". * @param {Float} y - Number with the height of the new dimensions in user units. * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {boolean} Indicates if resolution change was successful. * It will fail on "fit to content" option with no content to fit to. */ this.setResolution = function (x, y) { var res = getResolution(); var w = res.w, h = res.h; var batchCmd; if (x === 'fit') { // Get bounding box var bbox = getStrokedBBoxDefaultVisible(); if (bbox) { batchCmd = new BatchCommand$1('Fit Canvas to Content'); var visEls = getVisibleElements(); addToSelection(visEls); var dx = [], dy = []; $$b.each(visEls, function (i, item) { dx.push(bbox.x * -1); dy.push(bbox.y * -1); }); var cmd = canvas.moveSelectedElements(dx, dy, true); batchCmd.addSubCommand(cmd); clearSelection(); x = Math.round(bbox.width); y = Math.round(bbox.height); } else { return false; } } if (x !== w || y !== h) { if (!batchCmd) { batchCmd = new BatchCommand$1('Change Image Dimensions'); } x = convertToNum('width', x); y = convertToNum('height', y); svgcontent.setAttribute('width', x); svgcontent.setAttribute('height', y); this.contentW = x; this.contentH = y; batchCmd.addSubCommand(new ChangeElementCommand$1(svgcontent, { width: w, height: h })); svgcontent.setAttribute('viewBox', [0, 0, x / currentZoom, y / currentZoom].join(' ')); batchCmd.addSubCommand(new ChangeElementCommand$1(svgcontent, { viewBox: ['0 0', w, h].join(' ') })); addCommandToHistory(batchCmd); call('changed', [svgcontent]); } return true; }; /** * @typedef {module:jQueryAttr.Attributes} module:svgcanvas.ElementPositionInCanvas * @property {Float} x * @property {Float} y */ /** * @function module:svgcanvas.SvgCanvas#getOffset * @returns {module:svgcanvas.ElementPositionInCanvas} An object with `x`, `y` values indicating the svgcontent element's * position in the editor's canvas. */ this.getOffset = function () { return $$b(svgcontent).attr(['x', 'y']); }; /** * @typedef {PlainObject} module:svgcanvas.ZoomAndBBox * @property {Float} zoom * @property {module:utilities.BBoxObject} bbox */ /** * Sets the zoom level on the canvas-side based on the given value. * @function module:svgcanvas.SvgCanvas#setBBoxZoom * @param {"selection"|"canvas"|"content"|"layer"|module:SVGEditor.BBoxObjectWithFactor} val - Bounding box object to zoom to or string indicating zoom option. Note: the object value type is defined in `svg-editor.js` * @param {Integer} editorW - The editor's workarea box's width * @param {Integer} editorH - The editor's workarea box's height * @returns {module:svgcanvas.ZoomAndBBox|void} */ this.setBBoxZoom = function (val, editorW, editorH) { var spacer = 0.85; var bb; var calcZoom = function calcZoom(bb) { // eslint-disable-line no-shadow if (!bb) { return false; } var wZoom = Math.round(editorW / bb.width * 100 * spacer) / 100; var hZoom = Math.round(editorH / bb.height * 100 * spacer) / 100; var zoom = Math.min(wZoom, hZoom); canvas.setZoom(zoom); return { zoom: zoom, bbox: bb }; }; if (_typeof(val) === 'object') { bb = val; if (bb.width === 0 || bb.height === 0) { var newzoom = bb.zoom ? bb.zoom : currentZoom * bb.factor; canvas.setZoom(newzoom); return { zoom: currentZoom, bbox: bb }; } return calcZoom(bb); } switch (val) { case 'selection': { if (!selectedElements[0]) { return undefined; } var selectedElems = $$b.map(selectedElements, function (n) { if (n) { return n; } return undefined; }); bb = getStrokedBBoxDefaultVisible(selectedElems); break; } case 'canvas': { var res = getResolution(); spacer = 0.95; bb = { width: res.w, height: res.h, x: 0, y: 0 }; break; } case 'content': bb = getStrokedBBoxDefaultVisible(); break; case 'layer': bb = getStrokedBBoxDefaultVisible(getVisibleElements(getCurrentDrawing().getCurrentLayer())); break; default: return undefined; } return calcZoom(bb); }; /** * The zoom level has changed. Supplies the new zoom level as a number (not percentage). * @event module:svgcanvas.SvgCanvas#event:ext_zoomChanged * @type {Float} */ /** * The bottom panel was updated. * @event module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate * @type {PlainObject} * @property {boolean} nofill Indicates fill is disabled * @property {boolean} nostroke Indicates stroke is disabled */ /** * The element selection has changed (elements were added/removed from selection). * @event module:svgcanvas.SvgCanvas#event:ext_selectedChanged * @type {PlainObject} * @property {Element[]} elems Array of the newly selected elements * @property {Element|null} selectedElement The single selected element * @property {boolean} multiselected Indicates whether one or more elements were selected */ /** * Called when part of element is in process of changing, generally on * mousemove actions like rotate, move, etc. * @event module:svgcanvas.SvgCanvas#event:ext_elementTransition * @type {PlainObject} * @property {Element[]} elems Array of transitioning elements */ /** * One or more elements were changed. * @event module:svgcanvas.SvgCanvas#event:ext_elementChanged * @type {PlainObject} * @property {Element[]} elems Array of the affected elements */ /** * Invoked as soon as the locale is ready. * @event module:svgcanvas.SvgCanvas#event:ext_langReady * @type {PlainObject} * @property {string} lang The two-letter language code * @property {module:SVGEditor.uiStrings} uiStrings * @property {module:SVGEditor~ImportLocale} importLocale */ /** * The language was changed. Two-letter code of the new language. * @event module:svgcanvas.SvgCanvas#event:ext_langChanged * @type {string} */ /** * Means for an extension to add locale data. The two-letter language code. * @event module:svgcanvas.SvgCanvas#event:ext_addLangData * @type {PlainObject} * @property {string} lang * @property {module:SVGEditor~ImportLocale} importLocale */ /** * Called when new image is created. * @event module:svgcanvas.SvgCanvas#event:ext_onNewDocument * @type {void} */ /** * Called when sidepanel is resized or toggled. * @event module:svgcanvas.SvgCanvas#event:ext_workareaResized * @type {void} */ /** * Called upon addition of the extension, or, if svgicons are set, * after the icons are ready when extension SVG icons have loaded. * @event module:svgcanvas.SvgCanvas#event:ext_callback * @type {void} */ /** * Sets the zoom to the given level. * @function module:svgcanvas.SvgCanvas#setZoom * @param {Float} zoomLevel - Float indicating the zoom level to change to * @fires module:svgcanvas.SvgCanvas#event:ext_zoomChanged * @returns {void} */ this.setZoom = function (zoomLevel) { var res = getResolution(); svgcontent.setAttribute('viewBox', '0 0 ' + res.w / zoomLevel + ' ' + res.h / zoomLevel); currentZoom = zoomLevel; $$b.each(selectedElements, function (i, elem) { if (!elem) { return; } selectorManager.requestSelector(elem).resize(); }); pathActions$1.zoomChange(); runExtensions('zoomChanged', /** @type {module:svgcanvas.SvgCanvas#event:ext_zoomChanged} */ zoomLevel); }; /** * @function module:svgcanvas.SvgCanvas#getMode * @returns {string} The current editor mode string */ this.getMode = function () { return currentMode; }; /** * Sets the editor's mode to the given string. * @function module:svgcanvas.SvgCanvas#setMode * @param {string} name - String with the new mode to change to * @returns {void} */ this.setMode = function (name) { pathActions$1.clear(true); textActions.clear(); curProperties = selectedElements[0] && selectedElements[0].nodeName === 'text' ? curText : curShape; currentMode = name; }; /** * Group: Element Styling. */ /** * @typedef {PlainObject} module:svgcanvas.PaintOptions * @property {"solidColor"} type */ /** * @function module:svgcanvas.SvgCanvas#getColor * @param {string} type * @returns {string|module:svgcanvas.PaintOptions|Float|module:jGraduate~Paint} The current fill/stroke option */ this.getColor = function (type) { return curProperties[type]; }; /** * Change the current stroke/fill color/gradient value. * @function module:svgcanvas.SvgCanvas#setColor * @param {string} type - String indicating fill or stroke * @param {string} val - The value to set the stroke attribute to * @param {boolean} preventUndo - Boolean indicating whether or not this should be an undoable option * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.setColor = function (type, val, preventUndo) { curShape[type] = val; curProperties[type + '_paint'] = { type: 'solidColor' }; var elems = []; /** * * @param {Element} e * @returns {void} */ function addNonG(e) { if (e.nodeName !== 'g') { elems.push(e); } } var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; if (elem) { if (elem.tagName === 'g') { walkTree(elem, addNonG); } else if (type === 'fill') { if (elem.tagName !== 'polyline' && elem.tagName !== 'line') { elems.push(elem); } } else { elems.push(elem); } } } if (elems.length > 0) { if (!preventUndo) { changeSelectedAttribute(type, val, elems); call('changed', elems); } else { changeSelectedAttributeNoUndo(type, val, elems); } } }; /** * Apply the current gradient to selected element's fill or stroke. * @function module:svgcanvas.SvgCanvas#setGradient * @param {"fill"|"stroke"} type - String indicating "fill" or "stroke" to apply to an element * @returns {void} */ var setGradient = this.setGradient = function (type) { if (!curProperties[type + '_paint'] || curProperties[type + '_paint'].type === 'solidColor') { return; } var grad = canvas[type + 'Grad']; // find out if there is a duplicate gradient already in the defs var duplicateGrad = findDuplicateGradient(grad); var defs = findDefs(); // no duplicate found, so import gradient into defs if (!duplicateGrad) { // const origGrad = grad; grad = defs.appendChild(svgdoc.importNode(grad, true)); // get next id and set it on the grad grad.id = getNextId(); } else { // use existing gradient grad = duplicateGrad; } canvas.setColor(type, 'url(#' + grad.id + ')'); }; /** * Check if exact gradient already exists. * @function module:svgcanvas~findDuplicateGradient * @param {SVGGradientElement} grad - The gradient DOM element to compare to others * @returns {SVGGradientElement} The existing gradient if found, `null` if not */ var findDuplicateGradient = function findDuplicateGradient(grad) { var defs = findDefs(); var existingGrads = $$b(defs).find('linearGradient, radialGradient'); var i = existingGrads.length; var radAttrs = ['r', 'cx', 'cy', 'fx', 'fy']; while (i--) { var og = existingGrads[i]; if (grad.tagName === 'linearGradient') { if (grad.getAttribute('x1') !== og.getAttribute('x1') || grad.getAttribute('y1') !== og.getAttribute('y1') || grad.getAttribute('x2') !== og.getAttribute('x2') || grad.getAttribute('y2') !== og.getAttribute('y2')) { continue; } } else { var _ret = function () { var gradAttrs = $$b(grad).attr(radAttrs); var ogAttrs = $$b(og).attr(radAttrs); var diff = false; $$b.each(radAttrs, function (j, attr) { if (gradAttrs[attr] !== ogAttrs[attr]) { diff = true; } }); if (diff) { return "continue"; } }(); if (_ret === "continue") continue; } // else could be a duplicate, iterate through stops var stops = grad.getElementsByTagNameNS(NS.SVG, 'stop'); var ostops = og.getElementsByTagNameNS(NS.SVG, 'stop'); if (stops.length !== ostops.length) { continue; } var j = stops.length; while (j--) { var stop = stops[j]; var ostop = ostops[j]; if (stop.getAttribute('offset') !== ostop.getAttribute('offset') || stop.getAttribute('stop-opacity') !== ostop.getAttribute('stop-opacity') || stop.getAttribute('stop-color') !== ostop.getAttribute('stop-color')) { break; } } if (j === -1) { return og; } } // for each gradient in defs return null; }; /** * Set a color/gradient to a fill/stroke. * @function module:svgcanvas.SvgCanvas#setPaint * @param {"fill"|"stroke"} type - String with "fill" or "stroke" * @param {module:jGraduate.jGraduatePaintOptions} paint - The jGraduate paint object to apply * @returns {void} */ this.setPaint = function (type, paint) { // make a copy var p = new $$b.jGraduate.Paint(paint); this.setPaintOpacity(type, p.alpha / 100, true); // now set the current paint object curProperties[type + '_paint'] = p; switch (p.type) { case 'solidColor': this.setColor(type, p.solidColor !== 'none' ? '#' + p.solidColor : 'none'); break; case 'linearGradient': case 'radialGradient': canvas[type + 'Grad'] = p[p.type]; setGradient(type); break; } }; /** * @function module:svgcanvas.SvgCanvas#setStrokePaint * @param {module:jGraduate~Paint} paint * @returns {void} */ this.setStrokePaint = function (paint) { this.setPaint('stroke', paint); }; /** * @function module:svgcanvas.SvgCanvas#setFillPaint * @param {module:jGraduate~Paint} paint * @returns {void} */ this.setFillPaint = function (paint) { this.setPaint('fill', paint); }; /** * @function module:svgcanvas.SvgCanvas#getStrokeWidth * @returns {Float|string} The current stroke-width value */ this.getStrokeWidth = function () { return curProperties.stroke_width; }; /** * Sets the stroke width for the current selected elements. * When attempting to set a line's width to 0, this changes it to 1 instead. * @function module:svgcanvas.SvgCanvas#setStrokeWidth * @param {Float} val - A Float indicating the new stroke width value * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.setStrokeWidth = function (val) { if (val === 0 && ['line', 'path'].includes(currentMode)) { canvas.setStrokeWidth(1); return; } curProperties.stroke_width = val; var elems = []; /** * * @param {Element} e * @returns {void} */ function addNonG(e) { if (e.nodeName !== 'g') { elems.push(e); } } var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; if (elem) { if (elem.tagName === 'g') { walkTree(elem, addNonG); } else { elems.push(elem); } } } if (elems.length > 0) { changeSelectedAttribute('stroke-width', val, elems); call('changed', selectedElements); } }; /** * Set the given stroke-related attribute the given value for selected elements. * @function module:svgcanvas.SvgCanvas#setStrokeAttr * @param {string} attr - String with the attribute name * @param {string|Float} val - String or number with the attribute value * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.setStrokeAttr = function (attr, val) { curShape[attr.replace('-', '_')] = val; var elems = []; var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; if (elem) { if (elem.tagName === 'g') { walkTree(elem, function (e) { if (e.nodeName !== 'g') { elems.push(e); } }); } else { elems.push(elem); } } } if (elems.length > 0) { changeSelectedAttribute(attr, val, elems); call('changed', selectedElements); } }; /** * @typedef {PlainObject} module:svgcanvas.StyleOptions * @property {string} fill * @property {Float} fill_opacity * @property {string} stroke * @property {Float} stroke_width * @property {string} stroke_dasharray * @property {string} stroke_linejoin * @property {string} stroke_linecap * @property {Float} stroke_opacity * @property {Float} opacity */ /** * @function module:svgcanvas.SvgCanvas#getStyle * @returns {module:svgcanvas.StyleOptions} current style options */ this.getStyle = function () { return curShape; }; /** * @function module:svgcanvas.SvgCanvas#getOpacity * @returns {Float} the current opacity */ this.getOpacity = getOpacity; /** * Sets the given opacity on the current selected elements. * @function module:svgcanvas.SvgCanvas#setOpacity * @param {string} val * @returns {void} */ this.setOpacity = function (val) { curShape.opacity = val; changeSelectedAttribute('opacity', val); }; /** * @function module:svgcanvas.SvgCanvas#getFillOpacity * @returns {Float} the current fill opacity */ this.getFillOpacity = function () { return curShape.fill_opacity; }; /** * @function module:svgcanvas.SvgCanvas#getStrokeOpacity * @returns {string} the current stroke opacity */ this.getStrokeOpacity = function () { return curShape.stroke_opacity; }; /** * Sets the current fill/stroke opacity. * @function module:svgcanvas.SvgCanvas#setPaintOpacity * @param {string} type - String with "fill" or "stroke" * @param {Float} val - Float with the new opacity value * @param {boolean} preventUndo - Indicates whether or not this should be an undoable action * @returns {void} */ this.setPaintOpacity = function (type, val, preventUndo) { curShape[type + '_opacity'] = val; if (!preventUndo) { changeSelectedAttribute(type + '-opacity', val); } else { changeSelectedAttributeNoUndo(type + '-opacity', val); } }; /** * Gets the current fill/stroke opacity. * @function module:svgcanvas.SvgCanvas#getPaintOpacity * @param {"fill"|"stroke"} type - String with "fill" or "stroke" * @returns {Float} Fill/stroke opacity */ this.getPaintOpacity = function (type) { return type === 'fill' ? this.getFillOpacity() : this.getStrokeOpacity(); }; /** * Gets the `stdDeviation` blur value of the given element. * @function module:svgcanvas.SvgCanvas#getBlur * @param {Element} elem - The element to check the blur value for * @returns {string} stdDeviation blur attribute value */ this.getBlur = function (elem) { var val = 0; // const elem = selectedElements[0]; if (elem) { var filterUrl = elem.getAttribute('filter'); if (filterUrl) { var blur = getElem(elem.id + '_blur'); if (blur) { val = blur.firstChild.getAttribute('stdDeviation'); } } } return val; }; (function () { var curCommand = null; var filter = null; var filterHidden = false; /** * Sets the `stdDeviation` blur value on the selected element without being undoable. * @function module:svgcanvas.SvgCanvas#setBlurNoUndo * @param {Float} val - The new `stdDeviation` value * @returns {void} */ canvas.setBlurNoUndo = function (val) { if (!filter) { canvas.setBlur(val); return; } if (val === 0) { // Don't change the StdDev, as that will hide the element. // Instead, just remove the value for "filter" changeSelectedAttributeNoUndo('filter', ''); filterHidden = true; } else { var elem = selectedElements[0]; if (filterHidden) { changeSelectedAttributeNoUndo('filter', 'url(#' + elem.id + '_blur)'); } if (isWebkit()) { // console.log('e', elem); // eslint-disable-line no-console elem.removeAttribute('filter'); elem.setAttribute('filter', 'url(#' + elem.id + '_blur)'); } changeSelectedAttributeNoUndo('stdDeviation', val, [filter.firstChild]); canvas.setBlurOffsets(filter, val); } }; /** * * @returns {void} */ function finishChange() { var bCmd = canvas.undoMgr.finishUndoableChange(); curCommand.addSubCommand(bCmd); addCommandToHistory(curCommand); curCommand = null; filter = null; } /** * Sets the `x`, `y`, `width`, `height` values of the filter element in order to * make the blur not be clipped. Removes them if not neeeded. * @function module:svgcanvas.SvgCanvas#setBlurOffsets * @param {Element} filterElem - The filter DOM element to update * @param {Float} stdDev - The standard deviation value on which to base the offset size * @returns {void} */ canvas.setBlurOffsets = function (filterElem, stdDev) { if (stdDev > 3) { // TODO: Create algorithm here where size is based on expected blur assignAttributes(filterElem, { x: '-50%', y: '-50%', width: '200%', height: '200%' }); // Removing these attributes hides text in Chrome (see Issue 579) } else if (!isWebkit()) { filterElem.removeAttribute('x'); filterElem.removeAttribute('y'); filterElem.removeAttribute('width'); filterElem.removeAttribute('height'); } }; /** * Adds/updates the blur filter to the selected element. * @function module:svgcanvas.SvgCanvas#setBlur * @param {Float} val - Float with the new `stdDeviation` blur value * @param {boolean} complete - Whether or not the action should be completed (to add to the undo manager) * @returns {void} */ canvas.setBlur = function (val, complete) { if (curCommand) { finishChange(); return; } // Looks for associated blur, creates one if not found var elem = selectedElements[0]; var elemId = elem.id; filter = getElem(elemId + '_blur'); val -= 0; var batchCmd = new BatchCommand$1(); // Blur found! if (filter) { if (val === 0) { filter = null; } } else { // Not found, so create var newblur = addSVGElementFromJson({ element: 'feGaussianBlur', attr: { "in": 'SourceGraphic', stdDeviation: val } }); filter = addSVGElementFromJson({ element: 'filter', attr: { id: elemId + '_blur' } }); filter.append(newblur); findDefs().append(filter); batchCmd.addSubCommand(new InsertElementCommand$1(filter)); } var changes = { filter: elem.getAttribute('filter') }; if (val === 0) { elem.removeAttribute('filter'); batchCmd.addSubCommand(new ChangeElementCommand$1(elem, changes)); return; } changeSelectedAttribute('filter', 'url(#' + elemId + '_blur)'); batchCmd.addSubCommand(new ChangeElementCommand$1(elem, changes)); canvas.setBlurOffsets(filter, val); curCommand = batchCmd; canvas.undoMgr.beginUndoableChange('stdDeviation', [filter ? filter.firstChild : null]); if (complete) { canvas.setBlurNoUndo(val); finishChange(); } }; })(); /** * Check whether selected element is bold or not. * @function module:svgcanvas.SvgCanvas#getBold * @returns {boolean} Indicates whether or not element is bold */ this.getBold = function () { // should only have one element selected var selected = selectedElements[0]; if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { return selected.getAttribute('font-weight') === 'bold'; } return false; }; /** * Make the selected element bold or normal. * @function module:svgcanvas.SvgCanvas#setBold * @param {boolean} b - Indicates bold (`true`) or normal (`false`) * @returns {void} */ this.setBold = function (b) { var selected = selectedElements[0]; if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { changeSelectedAttribute('font-weight', b ? 'bold' : 'normal'); } if (!selectedElements[0].textContent) { textActions.setCursor(); } }; /** * Check whether selected element is in italics or not. * @function module:svgcanvas.SvgCanvas#getItalic * @returns {boolean} Indicates whether or not element is italic */ this.getItalic = function () { var selected = selectedElements[0]; if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { return selected.getAttribute('font-style') === 'italic'; } return false; }; /** * Make the selected element italic or normal. * @function module:svgcanvas.SvgCanvas#setItalic * @param {boolean} i - Indicates italic (`true`) or normal (`false`) * @returns {void} */ this.setItalic = function (i) { var selected = selectedElements[0]; if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { changeSelectedAttribute('font-style', i ? 'italic' : 'normal'); } if (!selectedElements[0].textContent) { textActions.setCursor(); } }; /** * @function module:svgcanvas.SvgCanvas#getFontFamily * @returns {string} The current font family */ this.getFontFamily = function () { return curText.font_family; }; /** * Set the new font family. * @function module:svgcanvas.SvgCanvas#setFontFamily * @param {string} val - String with the new font family * @returns {void} */ this.setFontFamily = function (val) { curText.font_family = val; changeSelectedAttribute('font-family', val); if (selectedElements[0] && !selectedElements[0].textContent) { textActions.setCursor(); } }; /** * Set the new font color. * @function module:svgcanvas.SvgCanvas#setFontColor * @param {string} val - String with the new font color * @returns {void} */ this.setFontColor = function (val) { curText.fill = val; changeSelectedAttribute('fill', val); }; /** * @function module:svgcanvas.SvgCanvas#getFontColor * @returns {string} The current font color */ this.getFontColor = function () { return curText.fill; }; /** * @function module:svgcanvas.SvgCanvas#getFontSize * @returns {Float} The current font size */ this.getFontSize = function () { return curText.font_size; }; /** * Applies the given font size to the selected element. * @function module:svgcanvas.SvgCanvas#setFontSize * @param {Float} val - Float with the new font size * @returns {void} */ this.setFontSize = function (val) { curText.font_size = val; changeSelectedAttribute('font-size', val); if (!selectedElements[0].textContent) { textActions.setCursor(); } }; /** * @function module:svgcanvas.SvgCanvas#getText * @returns {string} The current text (`textContent`) of the selected element */ this.getText = function () { var selected = selectedElements[0]; if (isNullish(selected)) { return ''; } return selected.textContent; }; /** * Updates the text element with the given string. * @function module:svgcanvas.SvgCanvas#setTextContent * @param {string} val - String with the new text * @returns {void} */ this.setTextContent = function (val) { changeSelectedAttribute('#text', val); textActions.init(val); textActions.setCursor(); }; /** * Sets the new image URL for the selected image element. Updates its size if * a new URL is given. * @function module:svgcanvas.SvgCanvas#setImageURL * @param {string} val - String with the image URL/path * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.setImageURL = function (val) { var elem = selectedElements[0]; if (!elem) { return; } var attrs = $$b(elem).attr(['width', 'height']); var setsize = !attrs.width || !attrs.height; var curHref = getHref(elem); // Do nothing if no URL change or size change if (curHref === val && !setsize) { return; } var batchCmd = new BatchCommand$1('Change Image URL'); setHref(elem, val); batchCmd.addSubCommand(new ChangeElementCommand$1(elem, { '#href': curHref })); $$b(new Image()).load(function () { var changes = $$b(elem).attr(['width', 'height']); $$b(elem).attr({ width: this.width, height: this.height }); selectorManager.requestSelector(elem).resize(); batchCmd.addSubCommand(new ChangeElementCommand$1(elem, changes)); addCommandToHistory(batchCmd); call('changed', [elem]); }).attr('src', val); }; /** * Sets the new link URL for the selected anchor element. * @function module:svgcanvas.SvgCanvas#setLinkURL * @param {string} val - String with the link URL/path * @returns {void} */ this.setLinkURL = function (val) { var elem = selectedElements[0]; if (!elem) { return; } if (elem.tagName !== 'a') { // See if parent is an anchor var parentsA = $$b(elem).parents('a'); if (parentsA.length) { elem = parentsA[0]; } else { return; } } var curHref = getHref(elem); if (curHref === val) { return; } var batchCmd = new BatchCommand$1('Change Link URL'); setHref(elem, val); batchCmd.addSubCommand(new ChangeElementCommand$1(elem, { '#href': curHref })); addCommandToHistory(batchCmd); }; /** * Sets the `rx` and `ry` values to the selected `rect` element * to change its corner radius. * @function module:svgcanvas.SvgCanvas#setRectRadius * @param {string|Float} val - The new radius * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.setRectRadius = function (val) { var selected = selectedElements[0]; if (!isNullish(selected) && selected.tagName === 'rect') { var r = selected.getAttribute('rx'); if (r !== String(val)) { selected.setAttribute('rx', val); selected.setAttribute('ry', val); addCommandToHistory(new ChangeElementCommand$1(selected, { rx: r, ry: r }, 'Radius')); call('changed', [selected]); } } }; /** * Wraps the selected element(s) in an anchor element or converts group to one. * @function module:svgcanvas.SvgCanvas#makeHyperlink * @param {string} url * @returns {void} */ this.makeHyperlink = function (url) { canvas.groupSelectedElements('a', url); // TODO: If element is a single "g", convert to "a" // if (selectedElements.length > 1 && selectedElements[1]) { }; /** * @function module:svgcanvas.SvgCanvas#removeHyperlink * @returns {void} */ this.removeHyperlink = function () { canvas.ungroupSelectedElement(); }; /** * Group: Element manipulation. */ /** * Sets the new segment type to the selected segment(s). * @function module:svgcanvas.SvgCanvas#setSegType * @param {Integer} newType - New segment type. See {@link https://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg} for list * @returns {void} */ this.setSegType = function (newType) { pathActions$1.setSegType(newType); }; /** * Convert selected element to a path, or get the BBox of an element-as-path. * @function module:svgcanvas.SvgCanvas#convertToPath * @todo (codedread): Remove the getBBox argument and split this function into two. * @param {Element} elem - The DOM element to be converted * @param {boolean} getBBox - Boolean on whether or not to only return the path's BBox * @returns {void|DOMRect|false|SVGPathElement|null} If the getBBox flag is true, the resulting path's bounding box object. * Otherwise the resulting path element is returned. */ this.convertToPath = function (elem, getBBox) { if (isNullish(elem)) { var elems = selectedElements; $$b.each(elems, function (i, el) { if (el) { canvas.convertToPath(el); } }); return undefined; } if (getBBox) { return getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions$1); } // TODO: Why is this applying attributes from curShape, then inside utilities.convertToPath it's pulling addition attributes from elem? // TODO: If convertToPath is called with one elem, curShape and elem are probably the same; but calling with multiple is a bug or cool feature. var attrs = { fill: curShape.fill, 'fill-opacity': curShape.fill_opacity, stroke: curShape.stroke, 'stroke-width': curShape.stroke_width, 'stroke-dasharray': curShape.stroke_dasharray, 'stroke-linejoin': curShape.stroke_linejoin, 'stroke-linecap': curShape.stroke_linecap, 'stroke-opacity': curShape.stroke_opacity, opacity: curShape.opacity, visibility: 'hidden' }; return convertToPath(elem, attrs, addSVGElementFromJson, pathActions$1, clearSelection, addToSelection, hstry, addCommandToHistory); }; /** * This function makes the changes to the elements. It does not add the change * to the history stack. * @param {string} attr - Attribute name * @param {string|Float} newValue - String or number with the new attribute value * @param {Element[]} elems - The DOM elements to apply the change to * @returns {void} */ var changeSelectedAttributeNoUndo = function changeSelectedAttributeNoUndo(attr, newValue, elems) { if (currentMode === 'pathedit') { // Editing node pathActions$1.moveNode(attr, newValue); } elems = elems || selectedElements; var i = elems.length; var noXYElems = ['g', 'polyline', 'path']; // const goodGAttrs = ['transform', 'opacity', 'filter']; var _loop = function _loop() { var elem = elems[i]; if (isNullish(elem)) { return "continue"; } // Set x,y vals on elements that don't have them if ((attr === 'x' || attr === 'y') && noXYElems.includes(elem.tagName)) { var bbox = getStrokedBBoxDefaultVisible([elem]); var diffX = attr === 'x' ? newValue - bbox.x : 0; var diffY = attr === 'y' ? newValue - bbox.y : 0; canvas.moveSelectedElements(diffX * currentZoom, diffY * currentZoom, true); return "continue"; } // only allow the transform/opacity/filter attribute to change on <g> elements, slightly hacky // TODO: Missing statement body // if (elem.tagName === 'g' && goodGAttrs.includes(attr)) {} var oldval = attr === '#text' ? elem.textContent : elem.getAttribute(attr); if (isNullish(oldval)) { oldval = ''; } if (oldval !== String(newValue)) { if (attr === '#text') { // const oldW = utilsGetBBox(elem).width; elem.textContent = newValue; // FF bug occurs on on rotated elements if (/rotate/.test(elem.getAttribute('transform'))) { elem = ffClone(elem); } // Hoped to solve the issue of moving text with text-anchor="start", // but this doesn't actually fix it. Hopefully on the right track, though. -Fyrd // const box = getBBox(elem), left = box.x, top = box.y, {width, height} = box, // dx = width - oldW, dy = 0; // const angle = getRotationAngle(elem, true); // if (angle) { // const r = Math.sqrt(dx * dx + dy * dy); // const theta = Math.atan2(dy, dx) - angle; // dx = r * Math.cos(theta); // dy = r * Math.sin(theta); // // elem.setAttribute('x', elem.getAttribute('x') - dx); // elem.setAttribute('y', elem.getAttribute('y') - dy); // } } else if (attr === '#href') { setHref(elem, newValue); } else { elem.setAttribute(attr, newValue); } // Go into "select" mode for text changes // NOTE: Important that this happens AFTER elem.setAttribute() or else attributes like // font-size can get reset to their old value, ultimately by svgEditor.updateContextPanel(), // after calling textActions.toSelectMode() below if (currentMode === 'textedit' && attr !== '#text' && elem.textContent.length) { textActions.toSelectMode(elem); } // if (i === 0) { // selectedBBoxes[0] = utilsGetBBox(elem); // } // Use the Firefox ffClone hack for text elements with gradients or // where other text attributes are changed. if (isGecko() && elem.nodeName === 'text' && /rotate/.test(elem.getAttribute('transform'))) { if (String(newValue).startsWith('url') || ['font-size', 'font-family', 'x', 'y'].includes(attr) && elem.textContent) { elem = ffClone(elem); } } // Timeout needed for Opera & Firefox // codedread: it is now possible for this function to be called with elements // that are not in the selectedElements array, we need to only request a // selector if the element is in that array if (selectedElements.includes(elem)) { setTimeout(function () { // Due to element replacement, this element may no longer // be part of the DOM if (!elem.parentNode) { return; } selectorManager.requestSelector(elem).resize(); }, 0); } // if this element was rotated, and we changed the position of this element // we need to update the rotational transform attribute var angle = getRotationAngle(elem); if (angle !== 0 && attr !== 'transform') { var tlist = getTransformList(elem); var n = tlist.numberOfItems; while (n--) { var xform = tlist.getItem(n); if (xform.type === 4) { // remove old rotate tlist.removeItem(n); var box = getBBox(elem); var center = transformPoint(box.x + box.width / 2, box.y + box.height / 2, transformListToTransform(tlist).matrix); var cx = center.x, cy = center.y; var newrot = svgroot.createSVGTransform(); newrot.setRotate(angle, cx, cy); tlist.insertItemBefore(newrot, n); break; } } } } // if oldValue != newValue }; while (i--) { var _ret2 = _loop(); if (_ret2 === "continue") continue; } // for each elem }; /** * Change the given/selected element and add the original value to the history stack. * If you want to change all `selectedElements`, ignore the `elems` argument. * If you want to change only a subset of `selectedElements`, then send the * subset to this function in the `elems` argument. * @function module:svgcanvas.SvgCanvas#changeSelectedAttribute * @param {string} attr - String with the attribute name * @param {string|Float} val - String or number with the new attribute value * @param {Element[]} elems - The DOM elements to apply the change to * @returns {void} */ var changeSelectedAttribute = this.changeSelectedAttribute = function (attr, val, elems) { elems = elems || selectedElements; canvas.undoMgr.beginUndoableChange(attr, elems); // const i = elems.length; changeSelectedAttributeNoUndo(attr, val, elems); var batchCmd = canvas.undoMgr.finishUndoableChange(); if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } }; /** * Removes all selected elements from the DOM and adds the change to the * history stack. * @function module:svgcanvas.SvgCanvas#deleteSelectedElements * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.deleteSelectedElements = function () { var batchCmd = new BatchCommand$1('Delete Elements'); var len = selectedElements.length; var selectedCopy = []; // selectedElements is being deleted for (var i = 0; i < len; ++i) { var selected = selectedElements[i]; if (isNullish(selected)) { break; } var parent = selected.parentNode; var t = selected; // this will unselect the element and remove the selectedOutline selectorManager.releaseSelector(t); // Remove the path if present. removePath_(t.id); // Get the parent if it's a single-child anchor if (parent.tagName === 'a' && parent.childNodes.length === 1) { t = parent; parent = parent.parentNode; } var _t = t, nextSibling = _t.nextSibling; t.remove(); var elem = t; selectedCopy.push(selected); // for the copy batchCmd.addSubCommand(new RemoveElementCommand$1(elem, nextSibling, parent)); } selectedElements = []; if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } call('changed', selectedCopy); clearSelection(); }; /** * Removes all selected elements from the DOM and adds the change to the * history stack. Remembers removed elements on the clipboard. * @function module:svgcanvas.SvgCanvas#cutSelectedElements * @returns {void} */ this.cutSelectedElements = function () { canvas.copySelectedElements(); canvas.deleteSelectedElements(); }; var CLIPBOARD_ID = 'svgedit_clipboard'; /** * Flash the clipboard data momentarily on localStorage so all tabs can see. * @returns {void} */ function flashStorage() { var data = sessionStorage.getItem(CLIPBOARD_ID); localStorage.setItem(CLIPBOARD_ID, data); setTimeout(function () { localStorage.removeItem(CLIPBOARD_ID); }, 1); } /** * Transfers sessionStorage from one tab to another. * @param {!Event} ev Storage event. * @returns {void} */ function storageChange(ev) { if (!ev.newValue) return; // This is a call from removeItem. if (ev.key === CLIPBOARD_ID + '_startup') { // Another tab asked for our sessionStorage. localStorage.removeItem(CLIPBOARD_ID + '_startup'); flashStorage(); } else if (ev.key === CLIPBOARD_ID) { // Another tab sent data. sessionStorage.setItem(CLIPBOARD_ID, ev.newValue); } } // Listen for changes to localStorage. window.addEventListener('storage', storageChange, false); // Ask other tabs for sessionStorage (this is ONLY to trigger event). localStorage.setItem(CLIPBOARD_ID + '_startup', Math.random()); /** * Remembers the current selected elements on the clipboard. * @function module:svgcanvas.SvgCanvas#copySelectedElements * @returns {void} */ this.copySelectedElements = function () { var data = JSON.stringify(selectedElements.map(function (x) { return getJsonFromSvgElement(x); })); // Use sessionStorage for the clipboard data. sessionStorage.setItem(CLIPBOARD_ID, data); flashStorage(); var menu = $$b('#cmenu_canvas'); // Context menu might not exist (it is provided by editor.js). if (menu.enableContextMenuItems) { menu.enableContextMenuItems('#paste,#paste_in_place'); } }; /** * @function module:svgcanvas.SvgCanvas#pasteElements * @param {"in_place"|"point"|void} type * @param {Integer|void} x Expected if type is "point" * @param {Integer|void} y Expected if type is "point" * @fires module:svgcanvas.SvgCanvas#event:changed * @fires module:svgcanvas.SvgCanvas#event:ext_IDsUpdated * @returns {void} */ this.pasteElements = function (type, x, y) { var clipb = JSON.parse(sessionStorage.getItem(CLIPBOARD_ID)); if (!clipb) return; var len = clipb.length; if (!len) return; var pasted = []; var batchCmd = new BatchCommand$1('Paste elements'); // const drawing = getCurrentDrawing(); /** * @typedef {PlainObject<string, string>} module:svgcanvas.ChangedIDs */ /** * @type {module:svgcanvas.ChangedIDs} */ var changedIDs = {}; // Recursively replace IDs and record the changes /** * * @param {module:svgcanvas.SVGAsJSON} elem * @returns {void} */ function checkIDs(elem) { if (elem.attr && elem.attr.id) { changedIDs[elem.attr.id] = getNextId(); elem.attr.id = changedIDs[elem.attr.id]; } if (elem.children) elem.children.forEach(function (child) { return checkIDs(child); }); } clipb.forEach(function (elem) { return checkIDs(elem); }); // Give extensions like the connector extension a chance to reflect new IDs and remove invalid elements /** * Triggered when `pasteElements` is called from a paste action (context menu or key). * @event module:svgcanvas.SvgCanvas#event:ext_IDsUpdated * @type {PlainObject} * @property {module:svgcanvas.SVGAsJSON[]} elems * @property {module:svgcanvas.ChangedIDs} changes Maps past ID (on attribute) to current ID */ runExtensions('IDsUpdated', /** @type {module:svgcanvas.SvgCanvas#event:ext_IDsUpdated} */ { elems: clipb, changes: changedIDs }, true).forEach(function (extChanges) { if (!extChanges || !('remove' in extChanges)) return; extChanges.remove.forEach(function (removeID) { clipb = clipb.filter(function (clipBoardItem) { return clipBoardItem.attr.id !== removeID; }); }); }); // Move elements to lastClickPoint while (len--) { var elem = clipb[len]; if (!elem) { continue; } var copy = addSVGElementFromJson(elem); pasted.push(copy); batchCmd.addSubCommand(new InsertElementCommand$1(copy)); restoreRefElems(copy); } selectOnly(pasted); if (type !== 'in_place') { var ctrX, ctrY; if (!type) { ctrX = lastClickPoint.x; ctrY = lastClickPoint.y; } else if (type === 'point') { ctrX = x; ctrY = y; } var bbox = getStrokedBBoxDefaultVisible(pasted); var cx = ctrX - (bbox.x + bbox.width / 2), cy = ctrY - (bbox.y + bbox.height / 2), dx = [], dy = []; $$b.each(pasted, function (i, item) { dx.push(cx); dy.push(cy); }); var cmd = canvas.moveSelectedElements(dx, dy, false); if (cmd) batchCmd.addSubCommand(cmd); } addCommandToHistory(batchCmd); call('changed', pasted); }; /** * Wraps all the selected elements in a group (`g`) element. * @function module:svgcanvas.SvgCanvas#groupSelectedElements * @param {"a"|"g"} [type="g"] - type of element to group into, defaults to `<g>` * @param {string} [urlArg] * @returns {void} */ this.groupSelectedElements = function (type, urlArg) { if (!type) { type = 'g'; } var cmdStr = ''; var url; switch (type) { case 'a': { cmdStr = 'Make hyperlink'; url = urlArg || ''; break; } default: { type = 'g'; cmdStr = 'Group Elements'; break; } } var batchCmd = new BatchCommand$1(cmdStr); // create and insert the group element var g = addSVGElementFromJson({ element: type, attr: { id: getNextId() } }); if (type === 'a') { setHref(g, url); } batchCmd.addSubCommand(new InsertElementCommand$1(g)); // now move all children into the group var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; if (isNullish(elem)) { continue; } if (elem.parentNode.tagName === 'a' && elem.parentNode.childNodes.length === 1) { elem = elem.parentNode; } var oldNextSibling = elem.nextSibling; var oldParent = elem.parentNode; g.append(elem); batchCmd.addSubCommand(new MoveElementCommand$1(elem, oldNextSibling, oldParent)); } if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } // update selection selectOnly([g], true); }; /** * Pushes all appropriate parent group properties down to its children, then * removes them from the group. * @function module:svgcanvas.SvgCanvas#pushGroupProperties * @param {SVGAElement|SVGGElement} g * @param {boolean} undoable * @returns {BatchCommand|void} */ var pushGroupProperties = this.pushGroupProperties = function (g, undoable) { var children = g.childNodes; var len = children.length; var xform = g.getAttribute('transform'); var glist = getTransformList(g); var m = transformListToTransform(glist).matrix; var batchCmd = new BatchCommand$1('Push group properties'); // TODO: get all fill/stroke properties from the group that we are about to destroy // "fill", "fill-opacity", "fill-rule", "stroke", "stroke-dasharray", "stroke-dashoffset", // "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", // "stroke-width" // and then for each child, if they do not have the attribute (or the value is 'inherit') // then set the child's attribute var gangle = getRotationAngle(g); var gattrs = $$b(g).attr(['filter', 'opacity']); var gfilter, gblur, changes; var drawing = getCurrentDrawing(); for (var i = 0; i < len; i++) { var elem = children[i]; if (elem.nodeType !== 1) { continue; } if (gattrs.opacity !== null && gattrs.opacity !== 1) { // const c_opac = elem.getAttribute('opacity') || 1; var newOpac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100) / 100; changeSelectedAttribute('opacity', newOpac, [elem]); } if (gattrs.filter) { var cblur = this.getBlur(elem); var origCblur = cblur; if (!gblur) { gblur = this.getBlur(g); } if (cblur) { // Is this formula correct? cblur = Number(gblur) + Number(cblur); } else if (cblur === 0) { cblur = gblur; } // If child has no current filter, get group's filter or clone it. if (!origCblur) { // Set group's filter to use first child's ID if (!gfilter) { gfilter = getRefElem(gattrs.filter); } else { // Clone the group's filter gfilter = drawing.copyElem(gfilter); findDefs().append(gfilter); } } else { gfilter = getRefElem(elem.getAttribute('filter')); } // Change this in future for different filters var suffix = gfilter.firstChild.tagName === 'feGaussianBlur' ? 'blur' : 'filter'; gfilter.id = elem.id + '_' + suffix; changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]); // Update blur value if (cblur) { changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]); canvas.setBlurOffsets(gfilter, cblur); } } var chtlist = getTransformList(elem); // Don't process gradient transforms if (elem.tagName.includes('Gradient')) { chtlist = null; } // Hopefully not a problem to add this. Necessary for elements like <desc/> if (!chtlist) { continue; } // Apparently <defs> can get get a transformlist, but we don't want it to have one! if (elem.tagName === 'defs') { continue; } if (glist.numberOfItems) { // TODO: if the group's transform is just a rotate, we can always transfer the // rotate() down to the children (collapsing consecutive rotates and factoring // out any translates) if (gangle && glist.numberOfItems === 1) { // [Rg] [Rc] [Mc] // we want [Tr] [Rc2] [Mc] where: // - [Rc2] is at the child's current center but has the // sum of the group and child's rotation angles // - [Tr] is the equivalent translation that this child // undergoes if the group wasn't there // [Tr] = [Rg] [Rc] [Rc2_inv] // get group's rotation matrix (Rg) var rgm = glist.getItem(0).matrix; // get child's rotation matrix (Rc) var rcm = svgroot.createSVGMatrix(); var cangle = getRotationAngle(elem); if (cangle) { rcm = chtlist.getItem(0).matrix; } // get child's old center of rotation var cbox = getBBox(elem); var ceqm = transformListToTransform(chtlist).matrix; var coldc = transformPoint(cbox.x + cbox.width / 2, cbox.y + cbox.height / 2, ceqm); // sum group and child's angles var sangle = gangle + cangle; // get child's rotation at the old center (Rc2_inv) var r2 = svgroot.createSVGTransform(); r2.setRotate(sangle, coldc.x, coldc.y); // calculate equivalent translate var trm = matrixMultiply(rgm, rcm, r2.matrix.inverse()); // set up tlist if (cangle) { chtlist.removeItem(0); } if (sangle) { if (chtlist.numberOfItems) { chtlist.insertItemBefore(r2, 0); } else { chtlist.appendItem(r2); } } if (trm.e || trm.f) { var tr = svgroot.createSVGTransform(); tr.setTranslate(trm.e, trm.f); if (chtlist.numberOfItems) { chtlist.insertItemBefore(tr, 0); } else { chtlist.appendItem(tr); } } } else { // more complicated than just a rotate // transfer the group's transform down to each child and then // call recalculateDimensions() var oldxform = elem.getAttribute('transform'); changes = {}; changes.transform = oldxform || ''; var newxform = svgroot.createSVGTransform(); // [ gm ] [ chm ] = [ chm ] [ gm' ] // [ gm' ] = [ chmInv ] [ gm ] [ chm ] var chm = transformListToTransform(chtlist).matrix, chmInv = chm.inverse(); var gm = matrixMultiply(chmInv, m, chm); newxform.setMatrix(gm); chtlist.appendItem(newxform); } var cmd = recalculateDimensions(elem); if (cmd) { batchCmd.addSubCommand(cmd); } } } // remove transform and make it undo-able if (xform) { changes = {}; changes.transform = xform; g.setAttribute('transform', ''); g.removeAttribute('transform'); batchCmd.addSubCommand(new ChangeElementCommand$1(g, changes)); } if (undoable && !batchCmd.isEmpty()) { return batchCmd; } return undefined; }; /** * Unwraps all the elements in a selected group (`g`) element. This requires * significant recalculations to apply group's transforms, etc. to its children. * @function module:svgcanvas.SvgCanvas#ungroupSelectedElement * @returns {void} */ this.ungroupSelectedElement = function () { var g = selectedElements[0]; if (!g) { return; } if ($$b(g).data('gsvg') || $$b(g).data('symbol')) { // Is svg, so actually convert to group convertToGroup(g); return; } if (g.tagName === 'use') { // Somehow doesn't have data set, so retrieve var symbol = getElem(getHref(g).substr(1)); $$b(g).data('symbol', symbol).data('ref', symbol); convertToGroup(g); return; } var parentsA = $$b(g).parents('a'); if (parentsA.length) { g = parentsA[0]; } // Look for parent "a" if (g.tagName === 'g' || g.tagName === 'a') { var batchCmd = new BatchCommand$1('Ungroup Elements'); var cmd = pushGroupProperties(g, true); if (cmd) { batchCmd.addSubCommand(cmd); } var parent = g.parentNode; var anchor = g.nextSibling; var children = new Array(g.childNodes.length); var i = 0; while (g.firstChild) { var elem = g.firstChild; var oldNextSibling = elem.nextSibling; var oldParent = elem.parentNode; // Remove child title elements if (elem.tagName === 'title') { var nextSibling = elem.nextSibling; batchCmd.addSubCommand(new RemoveElementCommand$1(elem, nextSibling, oldParent)); elem.remove(); continue; } if (anchor) { anchor.before(elem); } else { g.after(elem); } children[i++] = elem; batchCmd.addSubCommand(new MoveElementCommand$1(elem, oldNextSibling, oldParent)); } // remove the group from the selection clearSelection(); // delete the group element (but make undo-able) var gNextSibling = g.nextSibling; g.remove(); batchCmd.addSubCommand(new RemoveElementCommand$1(g, gNextSibling, parent)); if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } // update selection addToSelection(children); } }; /** * Repositions the selected element to the bottom in the DOM to appear on top of * other elements. * @function module:svgcanvas.SvgCanvas#moveToTopSelectedElement * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.moveToTopSelectedElement = function () { var _selectedElements = selectedElements, _selectedElements2 = _slicedToArray(_selectedElements, 1), selected = _selectedElements2[0]; if (!isNullish(selected)) { var t = selected; var oldParent = t.parentNode; var oldNextSibling = t.nextSibling; t = t.parentNode.appendChild(t); // If the element actually moved position, add the command and fire the changed // event handler. if (oldNextSibling !== t.nextSibling) { addCommandToHistory(new MoveElementCommand$1(t, oldNextSibling, oldParent, 'top')); call('changed', [t]); } } }; /** * Repositions the selected element to the top in the DOM to appear under * other elements. * @function module:svgcanvas.SvgCanvas#moveToBottomSelectedElement * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.moveToBottomSelectedElement = function () { var _selectedElements3 = selectedElements, _selectedElements4 = _slicedToArray(_selectedElements3, 1), selected = _selectedElements4[0]; if (!isNullish(selected)) { var t = selected; var oldParent = t.parentNode; var oldNextSibling = t.nextSibling; var firstChild = t.parentNode.firstChild; if (firstChild.tagName === 'title') { firstChild = firstChild.nextSibling; } // This can probably be removed, as the defs should not ever apppear // inside a layer group if (firstChild.tagName === 'defs') { firstChild = firstChild.nextSibling; } t = t.parentNode.insertBefore(t, firstChild); // If the element actually moved position, add the command and fire the changed // event handler. if (oldNextSibling !== t.nextSibling) { addCommandToHistory(new MoveElementCommand$1(t, oldNextSibling, oldParent, 'bottom')); call('changed', [t]); } } }; /** * Moves the select element up or down the stack, based on the visibly * intersecting elements. * @function module:svgcanvas.SvgCanvas#moveUpDownSelected * @param {"Up"|"Down"} dir - String that's either 'Up' or 'Down' * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {void} */ this.moveUpDownSelected = function (dir) { var selected = selectedElements[0]; if (!selected) { return; } curBBoxes = []; var closest, foundCur; // jQuery sorts this list var list = $$b(getIntersectionList(getStrokedBBoxDefaultVisible([selected]))).toArray(); if (dir === 'Down') { list.reverse(); } $$b.each(list, function () { if (!foundCur) { if (this === selected) { foundCur = true; } return true; } closest = this; return false; }); if (!closest) { return; } var t = selected; var oldParent = t.parentNode; var oldNextSibling = t.nextSibling; $$b(closest)[dir === 'Down' ? 'before' : 'after'](t); // If the element actually moved position, add the command and fire the changed // event handler. if (oldNextSibling !== t.nextSibling) { addCommandToHistory(new MoveElementCommand$1(t, oldNextSibling, oldParent, 'Move ' + dir)); call('changed', [t]); } }; /** * Moves selected elements on the X/Y axis. * @function module:svgcanvas.SvgCanvas#moveSelectedElements * @param {Float} dx - Float with the distance to move on the x-axis * @param {Float} dy - Float with the distance to move on the y-axis * @param {boolean} undoable - Boolean indicating whether or not the action should be undoable * @fires module:svgcanvas.SvgCanvas#event:changed * @returns {BatchCommand|void} Batch command for the move */ this.moveSelectedElements = function (dx, dy, undoable) { // if undoable is not sent, default to true // if single values, scale them to the zoom if (dx.constructor !== Array) { dx /= currentZoom; dy /= currentZoom; } undoable = undoable || true; var batchCmd = new BatchCommand$1('position'); var i = selectedElements.length; while (i--) { var selected = selectedElements[i]; if (!isNullish(selected)) { // if (i === 0) { // selectedBBoxes[0] = utilsGetBBox(selected); // } // const b = {}; // for (const j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j]; // selectedBBoxes[i] = b; var xform = svgroot.createSVGTransform(); var tlist = getTransformList(selected); // dx and dy could be arrays if (dx.constructor === Array) { // if (i === 0) { // selectedBBoxes[0].x += dx[0]; // selectedBBoxes[0].y += dy[0]; // } xform.setTranslate(dx[i], dy[i]); } else { // if (i === 0) { // selectedBBoxes[0].x += dx; // selectedBBoxes[0].y += dy; // } xform.setTranslate(dx, dy); } if (tlist.numberOfItems) { tlist.insertItemBefore(xform, 0); } else { tlist.appendItem(xform); } var cmd = recalculateDimensions(selected); if (cmd) { batchCmd.addSubCommand(cmd); } selectorManager.requestSelector(selected).resize(); } } if (!batchCmd.isEmpty()) { if (undoable) { addCommandToHistory(batchCmd); } call('changed', selectedElements); return batchCmd; } return undefined; }; /** * Create deep DOM copies (clones) of all selected elements and move them slightly * from their originals. * @function module:svgcanvas.SvgCanvas#cloneSelectedElements * @param {Float} x Float with the distance to move on the x-axis * @param {Float} y Float with the distance to move on the y-axis * @returns {void} */ this.cloneSelectedElements = function (x, y) { var i, elem; var batchCmd = new BatchCommand$1('Clone Elements'); // find all the elements selected (stop at first null) var len = selectedElements.length; /** * Sorts an array numerically and ascending. * @param {Element} a * @param {Element} b * @returns {Integer} */ function sortfunction(a, b) { return $$b(b).index() - $$b(a).index(); } selectedElements.sort(sortfunction); for (i = 0; i < len; ++i) { elem = selectedElements[i]; if (isNullish(elem)) { break; } } // use slice to quickly get the subset of elements we need var copiedElements = selectedElements.slice(0, i); this.clearSelection(true); // note that we loop in the reverse way because of the way elements are added // to the selectedElements array (top-first) var drawing = getCurrentDrawing(); i = copiedElements.length; while (i--) { // clone each element and replace it within copiedElements elem = copiedElements[i] = drawing.copyElem(copiedElements[i]); (currentGroup || drawing.getCurrentLayer()).append(elem); batchCmd.addSubCommand(new InsertElementCommand$1(elem)); } if (!batchCmd.isEmpty()) { addToSelection(copiedElements.reverse()); // Need to reverse for correct selection-adding this.moveSelectedElements(x, y, false); addCommandToHistory(batchCmd); } }; /** * Aligns selected elements. * @function module:svgcanvas.SvgCanvas#alignSelectedElements * @param {string} type - String with single character indicating the alignment type * @param {"selected"|"largest"|"smallest"|"page"} relativeTo * @returns {void} */ this.alignSelectedElements = function (type, relativeTo) { var bboxes = []; // angles = []; var len = selectedElements.length; if (!len) { return; } var minx = Number.MAX_VALUE, maxx = Number.MIN_VALUE, miny = Number.MAX_VALUE, maxy = Number.MIN_VALUE; var curwidth = Number.MIN_VALUE, curheight = Number.MIN_VALUE; for (var i = 0; i < len; ++i) { if (isNullish(selectedElements[i])) { break; } var elem = selectedElements[i]; bboxes[i] = getStrokedBBoxDefaultVisible([elem]); // now bbox is axis-aligned and handles rotation switch (relativeTo) { case 'smallest': if ((type === 'l' || type === 'c' || type === 'r') && (curwidth === Number.MIN_VALUE || curwidth > bboxes[i].width) || (type === 't' || type === 'm' || type === 'b') && (curheight === Number.MIN_VALUE || curheight > bboxes[i].height)) { minx = bboxes[i].x; miny = bboxes[i].y; maxx = bboxes[i].x + bboxes[i].width; maxy = bboxes[i].y + bboxes[i].height; curwidth = bboxes[i].width; curheight = bboxes[i].height; } break; case 'largest': if ((type === 'l' || type === 'c' || type === 'r') && (curwidth === Number.MIN_VALUE || curwidth < bboxes[i].width) || (type === 't' || type === 'm' || type === 'b') && (curheight === Number.MIN_VALUE || curheight < bboxes[i].height)) { minx = bboxes[i].x; miny = bboxes[i].y; maxx = bboxes[i].x + bboxes[i].width; maxy = bboxes[i].y + bboxes[i].height; curwidth = bboxes[i].width; curheight = bboxes[i].height; } break; default: // 'selected' if (bboxes[i].x < minx) { minx = bboxes[i].x; } if (bboxes[i].y < miny) { miny = bboxes[i].y; } if (bboxes[i].x + bboxes[i].width > maxx) { maxx = bboxes[i].x + bboxes[i].width; } if (bboxes[i].y + bboxes[i].height > maxy) { maxy = bboxes[i].y + bboxes[i].height; } break; } } // loop for each element to find the bbox and adjust min/max if (relativeTo === 'page') { minx = 0; miny = 0; maxx = canvas.contentW; maxy = canvas.contentH; } var dx = new Array(len); var dy = new Array(len); for (var _i6 = 0; _i6 < len; ++_i6) { if (isNullish(selectedElements[_i6])) { break; } // const elem = selectedElements[i]; var bbox = bboxes[_i6]; dx[_i6] = 0; dy[_i6] = 0; switch (type) { case 'l': // left (horizontal) dx[_i6] = minx - bbox.x; break; case 'c': // center (horizontal) dx[_i6] = (minx + maxx) / 2 - (bbox.x + bbox.width / 2); break; case 'r': // right (horizontal) dx[_i6] = maxx - (bbox.x + bbox.width); break; case 't': // top (vertical) dy[_i6] = miny - bbox.y; break; case 'm': // middle (vertical) dy[_i6] = (miny + maxy) / 2 - (bbox.y + bbox.height / 2); break; case 'b': // bottom (vertical) dy[_i6] = maxy - (bbox.y + bbox.height); break; } } this.moveSelectedElements(dx, dy); }; /** * Group: Additional editor tools. */ /** * @name module:svgcanvas.SvgCanvas#contentW * @type {Float} */ this.contentW = getResolution().w; /** * @name module:svgcanvas.SvgCanvas#contentH * @type {Float} */ this.contentH = getResolution().h; /** * @typedef {PlainObject} module:svgcanvas.CanvasInfo * @property {Float} x - The canvas' new x coordinate * @property {Float} y - The canvas' new y coordinate * @property {string} oldX - The canvas' old x coordinate * @property {string} oldY - The canvas' old y coordinate * @property {Float} d_x - The x position difference * @property {Float} d_y - The y position difference */ /** * Updates the editor canvas width/height/position after a zoom has occurred. * @function module:svgcanvas.SvgCanvas#updateCanvas * @param {Float} w - Float with the new width * @param {Float} h - Float with the new height * @fires module:svgcanvas.SvgCanvas#event:ext_canvasUpdated * @returns {module:svgcanvas.CanvasInfo} */ this.updateCanvas = function (w, h) { svgroot.setAttribute('width', w); svgroot.setAttribute('height', h); var bg = $$b('#canvasBackground')[0]; var oldX = svgcontent.getAttribute('x'); var oldY = svgcontent.getAttribute('y'); var x = (w - this.contentW * currentZoom) / 2; var y = (h - this.contentH * currentZoom) / 2; assignAttributes(svgcontent, { width: this.contentW * currentZoom, height: this.contentH * currentZoom, x: x, y: y, viewBox: '0 0 ' + this.contentW + ' ' + this.contentH }); assignAttributes(bg, { width: svgcontent.getAttribute('width'), height: svgcontent.getAttribute('height'), x: x, y: y }); var bgImg = getElem('background_image'); if (bgImg) { assignAttributes(bgImg, { width: '100%', height: '100%' }); } selectorManager.selectorParentGroup.setAttribute('transform', 'translate(' + x + ',' + y + ')'); /** * Invoked upon updates to the canvas. * @event module:svgcanvas.SvgCanvas#event:ext_canvasUpdated * @type {PlainObject} * @property {Integer} new_x * @property {Integer} new_y * @property {string} old_x (Of Integer) * @property {string} old_y (Of Integer) * @property {Integer} d_x * @property {Integer} d_y */ runExtensions('canvasUpdated', /** * @type {module:svgcanvas.SvgCanvas#event:ext_canvasUpdated} */ { new_x: x, new_y: y, old_x: oldX, old_y: oldY, d_x: x - oldX, d_y: y - oldY }); return { x: x, y: y, old_x: oldX, old_y: oldY, d_x: x - oldX, d_y: y - oldY }; }; /** * Set the background of the editor (NOT the actual document). * @function module:svgcanvas.SvgCanvas#setBackground * @param {string} color - String with fill color to apply * @param {string} url - URL or path to image to use * @returns {void} */ this.setBackground = function (color, url) { var bg = getElem('canvasBackground'); var border = $$b(bg).find('rect')[0]; var bgImg = getElem('background_image'); var bgPattern = getElem('background_pattern'); border.setAttribute('fill', color === 'chessboard' ? '#fff' : color); if (color === 'chessboard') { if (!bgPattern) { bgPattern = svgdoc.createElementNS(NS.SVG, 'foreignObject'); assignAttributes(bgPattern, { id: 'background_pattern', width: '100%', height: '100%', preserveAspectRatio: 'xMinYMin', style: 'pointer-events:none' }); var div = document.createElement('div'); assignAttributes(div, { style: 'pointer-events:none;width:100%;height:100%;' + 'background-image:url(data:image/gif;base64,' + 'R0lGODlhEAAQAIAAAP///9bW1iH5BAAAAAAALAAAAAAQABAAAAIfjG+' + 'gq4jM3IFLJgpswNly/XkcBpIiVaInlLJr9FZWAQA7);' }); bgPattern.appendChild(div); bg.append(bgPattern); } } else if (bgPattern) { bgPattern.remove(); } if (url) { if (!bgImg) { bgImg = svgdoc.createElementNS(NS.SVG, 'image'); assignAttributes(bgImg, { id: 'background_image', width: '100%', height: '100%', preserveAspectRatio: 'xMinYMin', style: 'pointer-events:none' }); } setHref(bgImg, url); bg.append(bgImg); } else if (bgImg) { bgImg.remove(); } }; /** * Select the next/previous element within the current layer. * @function module:svgcanvas.SvgCanvas#cycleElement * @param {boolean} next - true = next and false = previous element * @fires module:svgcanvas.SvgCanvas#event:selected * @returns {void} */ this.cycleElement = function (next) { var num; var curElem = selectedElements[0]; var elem = false; var allElems = getVisibleElements(currentGroup || getCurrentDrawing().getCurrentLayer()); if (!allElems.length) { return; } if (isNullish(curElem)) { num = next ? allElems.length - 1 : 0; elem = allElems[num]; } else { var i = allElems.length; while (i--) { if (allElems[i] === curElem) { num = next ? i - 1 : i + 1; if (num >= allElems.length) { num = 0; } else if (num < 0) { num = allElems.length - 1; } elem = allElems[num]; break; } } } selectOnly([elem], true); call('selected', selectedElements); }; this.clear(); /** * @interface module:svgcanvas.PrivateMethods * @type {PlainObject} * @property {module:svgcanvas~addCommandToHistory} addCommandToHistory * @property {module:history.HistoryCommand} BatchCommand * @property {module:history.HistoryCommand} ChangeElementCommand * @property {module:utilities.decode64} decode64 * @property {module:utilities.dropXMLInternalSubset} dropXMLInternalSubset * @property {module:utilities.encode64} encode64 * @property {module:svgcanvas~ffClone} ffClone * @property {module:svgcanvas~findDuplicateGradient} findDuplicateGradient * @property {module:utilities.getPathBBox} getPathBBox * @property {module:units.getTypeMap} getTypeMap * @property {module:draw.identifyLayers} identifyLayers * @property {module:history.HistoryCommand} InsertElementCommand * @property {module:browser.isChrome} isChrome * @property {module:math.isIdentity} isIdentity * @property {module:browser.isIE} isIE * @property {module:svgcanvas~logMatrix} logMatrix * @property {module:history.HistoryCommand} MoveElementCommand * @property {module:namespaces.NS} NS * @property {module:utilities.preventClickDefault} preventClickDefault * @property {module:history.HistoryCommand} RemoveElementCommand * @property {module:SVGTransformList.SVGEditTransformList} SVGEditTransformList * @property {module:utilities.text2xml} text2xml * @property {module:math.transformBox} transformBox * @property {module:math.transformPoint} transformPoint * @property {module:utilities.walkTree} walkTree */ /** * @deprecated getPrivateMethods * Since all methods are/should be public somehow, this function should be removed; * we might require `import` in place of this in the future once ES6 Modules * widespread * Being able to access private methods publicly seems wrong somehow, * but currently appears to be the best way to allow testing and provide * access to them to plugins. * @function module:svgcanvas.SvgCanvas#getPrivateMethods * @returns {module:svgcanvas.PrivateMethods} */ this.getPrivateMethods = function () { var obj = { addCommandToHistory: addCommandToHistory, BatchCommand: BatchCommand$1, ChangeElementCommand: ChangeElementCommand$1, decode64: decode64, dropXMLInternalSubset: dropXMLInternalSubset, encode64: encode64, ffClone: ffClone, findDefs: findDefs, findDuplicateGradient: findDuplicateGradient, getElem: getElem, getPathBBox: getPathBBox, getTypeMap: getTypeMap, getUrlFromAttr: getUrlFromAttr, identifyLayers: identifyLayers, InsertElementCommand: InsertElementCommand$1, isChrome: isChrome, isIdentity: isIdentity, isIE: isIE, logMatrix: logMatrix, MoveElementCommand: MoveElementCommand$1, NS: NS, preventClickDefault: preventClickDefault, RemoveElementCommand: RemoveElementCommand$1, SVGEditTransformList: SVGTransformList, text2xml: text2xml, transformBox: transformBox, transformPoint: transformPoint, walkTree: walkTree }; return obj; }; } // End constructor ; // End class // Todo: Update: https://github.com/jeresig/jquery.hotkeys /* * jQuery Hotkeys Plugin * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * * http://github.com/jeresig/jquery.hotkeys * * Based upon the plugin by Tzury Bar Yochay: * http://github.com/tzuryby/hotkeys * * Original idea by: * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/ */ // We *do* want to allow the escape key within textareas (and possibly tab too), so add the condition `n.which !== 27` function jQueryPluginJSHotkeys (b) { b.hotkeys = { version: "0.8", specialKeys: { 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 224: "meta", 219: "[", 221: "]" }, shiftNums: { "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": '"', ",": "<", ".": ">", "/": "?", "\\": "|" } }; function a(d) { if (typeof d.data !== "string") { return; } var c = d.handler, e = d.data.toLowerCase().split(" "); d.handler = function (n) { if (this !== n.target && n.which !== 27 && (/textarea|select/i.test(n.target.nodeName) || n.target.type === "text")) { return; } var h = n.type !== "keypress" && b.hotkeys.specialKeys[n.which], o = String.fromCharCode(n.which).toLowerCase(), m = "", g = {}; if (n.altKey && h !== "alt") { m += "alt+"; } if (n.ctrlKey && h !== "ctrl") { m += "ctrl+"; } if (n.metaKey && !n.ctrlKey && h !== "meta") { m += "meta+"; } if (n.shiftKey && h !== "shift") { m += "shift+"; } if (h) { g[m + h] = true; } else { g[m + o] = true; g[m + b.hotkeys.shiftNums[o]] = true; if (m === "shift+") { g[b.hotkeys.shiftNums[o]] = true; } } for (var j = 0, f = e.length; j < f; j++) { if (g[e[j]]) { return c.apply(this, arguments); } } }; } b.each(["keydown", "keyup", "keypress"], function () { b.event.special[this] = { add: a }; }); return b; } /** * @file SVG Icon Loader 2.0 * * jQuery Plugin for loading SVG icons from a single file * * Adds {@link external:jQuery.svgIcons}, {@link external:jQuery.getSvgIcon}, {@link external:jQuery.resizeSvgIcons} * * How to use: 1. Create the SVG master file that includes all icons: The master SVG icon-containing file is an SVG file that contains `<g>` elements. Each `<g>` element should contain the markup of an SVG icon. The `<g>` element has an ID that should correspond with the ID of the HTML element used on the page that should contain or optionally be replaced by the icon. Additionally, one empty element should be added at the end with id "svg_eof". 2. Optionally create fallback raster images for each SVG icon. 3. Include the jQuery and the SVG Icon Loader scripts on your page. 4. Run `$.svgIcons()` when the document is ready. See its signature 5. To access an icon at a later point without using the callback, use this: `$.getSvgIcon(id (string), uniqueClone (boolean))`; This will return the icon (as jQuery object) with a given ID. 6. To resize icons at a later point without using the callback, use this: `$.resizeSvgIcons(resizeOptions)` (use the same way as the "resize" parameter) * * @module jQuerySVGIcons * @license MIT * @copyright (c) 2009 Alexis Deveria * {@link http://a.deveria.com} * @example $(function () { $.svgIcons('my_icon_set.svg'); // The SVG file that contains all icons // No options have been set, so all icons will automatically be inserted // into HTML elements that match the same IDs. }); * @example $(function () { // The SVG file that contains all icons $.svgIcons('my_icon_set.svg', { callback (icons) { // Custom callback function that sets click // events for each icon $.each(icons, function (id, icon) { icon.click(function () { alert('You clicked on the icon with id ' + id); }); }); } }); }); * @example $(function () { // The SVGZ file that contains all icons $.svgIcons('my_icon_set.svgz', { w: 32, // All icons will be 32px wide h: 32, // All icons will be 32px high fallback_path: 'icons/', // All fallback files can be found here fallback: { '#open_icon': 'open.png', // The "open.png" will be appended to the // HTML element with ID "open_icon" '#close_icon': 'close.png', '#save_icon': 'save.png' }, placement: {'.open_icon': 'open'}, // The "open" icon will be added // to all elements with class "open_icon" resize: { '#save_icon .svg_icon': 64 // The "save" icon will be resized to 64 x 64px }, callback (icons) { // Sets background color for "close" icon icons.close.css('background', 'red'); }, svgz: true // Indicates that an SVGZ file is being used }); }); */ var isOpera$1 = Boolean(window.opera); var fixIDs = function fixIDs(svgEl, svgNum, force) { var defs = svgEl.find('defs'); if (!defs.length) return svgEl; var idElems; if (isOpera$1) { idElems = defs.find('*').filter(function () { return Boolean(this.id); }); } else { idElems = defs.find('[id]'); } var allElems = svgEl[0].getElementsByTagName('*'), len = allElems.length; idElems.each(function (i) { var id = this.id; /* const noDupes = ($(svgdoc).find('#' + id).length <= 1); if (isOpera) noDupes = false; // Opera didn't clone svgEl, so not reliable if(!force && noDupes) return; */ var newId = 'x' + id + svgNum + i; this.id = newId; var oldVal = 'url(#' + id + ')'; var newVal = 'url(#' + newId + ')'; // Selector method, possibly faster but fails in Opera / jQuery 1.4.3 // svgEl.find('[fill="url(#' + id + ')"]').each(function() { // this.setAttribute('fill', 'url(#' + newId + ')'); // }).end().find('[stroke="url(#' + id + ')"]').each(function() { // this.setAttribute('stroke', 'url(#' + newId + ')'); // }).end().find('use').each(function() { // if(this.getAttribute('xlink:href') == '#' + id) { // this.setAttributeNS(xlinkns,'href','#' + newId); // } // }).end().find('[filter="url(#' + id + ')"]').each(function() { // this.setAttribute('filter', 'url(#' + newId + ')'); // }); for (i = 0; i < len; i++) { var elem = allElems[i]; if (elem.getAttribute('fill') === oldVal) { elem.setAttribute('fill', newVal); } if (elem.getAttribute('stroke') === oldVal) { elem.setAttribute('stroke', newVal); } if (elem.getAttribute('filter') === oldVal) { elem.setAttribute('filter', newVal); } } }); return svgEl; }; /** * @callback module:jQuerySVGIcons.SVGIconsLoadedCallback * @param {PlainObject<string, external:jQuery>} svgIcons IDs keyed to jQuery objects of images * @returns {void} */ /** * @function module:jQuerySVGIcons.jQuerySVGIcons * @param {external:jQuery} $ Its keys include all icon IDs and the values, the icon as a jQuery object * @returns {external:jQuery} The enhanced jQuery object */ function jQueryPluginSVGIcons($) { var svgIcons = {}; /** * Map of raster images with each key being the SVG icon ID * to replace, and the value the image file name. * @typedef {PlainObject<string, string>} external:jQuery.svgIcons.Fallback */ /** * Map of raster images with each key being the SVG icon ID * whose `alt` will be set, and the value being the `alt` text. * @typedef {PlainObject<string, string>} external:jQuery.svgIcons.Alts */ /** * @function external:jQuery.svgIcons * @param {string} file The location of a local SVG or SVGz file * @param {PlainObject} [opts] * @param {Float} [opts.w] The icon widths * @param {Float} [opts.h] The icon heights * @param {external:jQuery.svgIcons.Fallback} [opts.fallback] * @param {string} [opts.fallback_path] The path to use for all images * listed under "fallback" * @param {boolean} [opts.replace] If set to `true`, HTML elements will * be replaced by, rather than include the SVG icon. * @param {PlainObject<string, string>} [opts.placement] Map with selectors * for keys and SVG icon ids as values. This provides a custom method of * adding icons. * @param {PlainObject<string, module:jQuerySVGIcons.Size>} [opts.resize] Map * with selectors for keys and numbers as values. This allows an easy way to * resize specific icons. * @param {module:jQuerySVGIcons.SVGIconsLoadedCallback} [opts.callback] A * function to call when all icons have been loaded. * @param {boolean} [opts.id_match=true] Automatically attempt to match * SVG icon ids with corresponding HTML id * @param {boolean} [opts.no_img] Prevent attempting to convert the icon * into an `<img>` element (may be faster, help for browser consistency) * @param {boolean} [opts.svgz] Indicate that the file is an SVGZ file, and * thus not to parse as XML. SVGZ files add compression benefits, but * getting data from them fails in Firefox 2 and older. * @param {jQuery.svgIcons.Alts} [opts.alts] Map of images with each key * being the SVG icon ID whose `alt` will be set, and the value being * the `alt` text * @param {string} [opts.testIconAlt="icon"] Alt text for the injected test image. * In case wish to ensure have one for accessibility * @returns {void} */ $.svgIcons = function (file) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var svgns = 'http://www.w3.org/2000/svg', xlinkns = 'http://www.w3.org/1999/xlink', iconW = opts.w || 24, iconH = opts.h || 24; var elems, svgdoc, testImg, iconsMade = false, dataLoaded = false, loadAttempts = 0; var // ua = navigator.userAgent, // isSafari = (ua.includes('Safari/') && !ua.includes('Chrome/')), dataPre = 'data:image/svg+xml;charset=utf-8;base64,'; var dataEl; if (opts.svgz) { dataEl = $('<object data="' + file + '" type=image/svg+xml>').appendTo('body').hide(); try { svgdoc = dataEl[0].contentDocument; dataEl.load(getIcons); getIcons(0, true); // Opera will not run "load" event if file is already cached } catch (err1) { useFallback(); } } else { var parser = new DOMParser(); $.ajax({ url: file, dataType: 'string', success: function success(data) { if (!data) { $(useFallback); return; } svgdoc = parser.parseFromString(data, 'text/xml'); $(function () { getIcons('ajax'); }); }, error: function error(err) { // TODO: Fix Opera widget icon bug if (window.opera) { $(function () { useFallback(); }); } else if (err.responseText) { svgdoc = parser.parseFromString(err.responseText, 'text/xml'); if (!svgdoc.childNodes.length) { $(useFallback); } $(function () { getIcons('ajax'); }); } else { $(useFallback); } } }); } /** * * @param {"ajax"|0|void} evt * @param {boolean} [noWait] * @returns {void} */ function getIcons(evt, noWait) { if (evt !== 'ajax') { if (dataLoaded) return; // Webkit sometimes says svgdoc is undefined, other times // it fails to load all nodes. Thus we must make sure the "eof" // element is loaded. svgdoc = dataEl[0].contentDocument; // Needed again for Webkit var isReady = svgdoc && svgdoc.getElementById('svg_eof'); if (!isReady && !(noWait && isReady)) { loadAttempts++; if (loadAttempts < 50) { setTimeout(getIcons, 20); } else { useFallback(); dataLoaded = true; } return; } dataLoaded = true; } elems = $(svgdoc.firstChild).children(); // .getElementsByTagName('foreignContent'); if (!opts.no_img) { var testSrc = dataPre + 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zd' + 'mciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D'; testImg = $(new Image()).attr({ src: testSrc, width: 0, height: 0, alt: opts.testIconAlt || 'icon' }).appendTo('body').load(function () { // Safari 4 crashes, Opera and Chrome don't makeIcons(true); }).error(function () { makeIcons(); }); } else { setTimeout(function () { if (!iconsMade) makeIcons(); }, 500); } } /** * * @param {external:jQuery} target * @param {external:jQuery} icon A wrapped `defs` or Image * @param {string} id SVG icon ID * @param {boolean} setID Whether to set the ID attribute (with `id`) * @returns {void} */ function setIcon(target, icon, id, setID) { if (isOpera$1) icon.css('visibility', 'hidden'); if (opts.replace) { if (setID) icon.attr('id', id); var cl = target.attr('class'); if (cl) icon.attr('class', 'svg_icon ' + cl); if (!target.alt) { var alt = 'icon'; if (opts.alts) { alt = opts.alts[id] || alt; } icon.attr('alt', alt); } target.replaceWith(icon); } else { target.append(icon); } if (isOpera$1) { setTimeout(function () { icon.removeAttr('style'); }, 1); } } var holder; /** * @param {external:jQuery} icon A wrapped `defs` or Image * @param {string} id SVG icon ID * @returns {void} */ function addIcon(icon, id) { if (opts.id_match === undefined || opts.id_match !== false) { setIcon(holder, icon, id, true); } svgIcons[id] = icon; } /** * * @param {boolean} [toImage] * @param {external:jQuery.svgIcons.Fallback} [fallback=false] * @returns {void} */ function makeIcons() { var toImage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (iconsMade) return; if (opts.no_img) toImage = false; var tempHolder; if (toImage) { tempHolder = $(document.createElement('div')); tempHolder.hide().appendTo('body'); } if (fallback) { var path = opts.fallback_path || ''; $.each(fallback, function (id, imgsrc) { holder = $('#' + id); var alt = 'icon'; if (opts.alts) { alt = opts.alts[id] || alt; } var icon = $(new Image()).attr({ "class": 'svg_icon', src: path + imgsrc, width: iconW, height: iconH, alt: alt }); addIcon(icon, id); }); } else { var len = elems.length; for (var i = 0; i < len; i++) { var elem = elems[i]; var id = elem.id; if (id === 'svg_eof') break; holder = $('#' + id); var svgroot = document.createElementNS(svgns, 'svg'); // Per https://www.w3.org/TR/xml-names11/#defaulting, the namespace for // attributes should have no value. svgroot.setAttribute('viewBox', [0, 0, iconW, iconH].join(' ')); var svg = elem.getElementsByTagNameNS(svgns, 'svg')[0]; // Make flexible by converting width/height to viewBox var w = svg.getAttribute('width'); var h = svg.getAttribute('height'); svg.removeAttribute('width'); svg.removeAttribute('height'); var vb = svg.getAttribute('viewBox'); if (!vb) { svg.setAttribute('viewBox', [0, 0, w, h].join(' ')); } // Not using jQuery to be a bit faster svgroot.setAttribute('xmlns', svgns); svgroot.setAttribute('width', iconW); svgroot.setAttribute('height', iconH); svgroot.setAttribute('xmlns:xlink', xlinkns); svgroot.setAttribute('class', 'svg_icon'); // Without cloning, Firefox will make another GET request. // With cloning, causes issue in Opera/Win/Non-EN if (!isOpera$1) svg = svg.cloneNode(true); svgroot.append(svg); var icon = void 0; if (toImage) { tempHolder.empty().append(svgroot); var str = dataPre + encode64(unescape(encodeURIComponent(new XMLSerializer().serializeToString(svgroot)))); var alt = 'icon'; if (opts.alts) { alt = opts.alts[id] || alt; } icon = $(new Image()).attr({ "class": 'svg_icon', src: str, alt: alt }); } else { icon = fixIDs($(svgroot), i); } addIcon(icon, id); } } if (opts.placement) { $.each(opts.placement, function (sel, id) { if (!svgIcons[id]) return; $(sel).each(function (i) { var copy = svgIcons[id].clone(); if (i > 0 && !toImage) copy = fixIDs(copy, i); setIcon($(this), copy, id); }); }); } if (!fallback) { if (toImage) tempHolder.remove(); if (dataEl) dataEl.remove(); if (testImg) testImg.remove(); } if (opts.resize) $.resizeSvgIcons(opts.resize); iconsMade = true; if (opts.callback) opts.callback(svgIcons); } /** * @returns {void} */ function useFallback() { if (file.includes('.svgz')) { var regFile = file.replace('.svgz', '.svg'); if (window.console) { console.log('.svgz failed, trying with .svg'); // eslint-disable-line no-console } $.svgIcons(regFile, opts); } else if (opts.fallback) { makeIcons(false, opts.fallback); } } }; /** * @function external:jQuery.getSvgIcon * @param {string} id * @param {boolean} uniqueClone Whether to clone * @returns {external:jQuery} The icon (optionally cloned) */ $.getSvgIcon = function (id, uniqueClone) { var icon = svgIcons[id]; if (uniqueClone && icon) { icon = fixIDs(icon, 0).clone(true); } return icon; }; /** * @typedef {GenericArray} module:jQuerySVGIcons.Dimensions * @property {Integer} length 2 * @property {Float} 0 Width * @property {Float} 1 Height */ /** * If a Float is used, it will represent width and height. Arrays contain * the width and height. * @typedef {module:jQuerySVGIcons.Dimensions|Float} module:jQuerySVGIcons.Size */ /** * @function external:jQuery.resizeSvgIcons * @param {PlainObject<string, module:jQuerySVGIcons.Size>} obj Object with * selectors as keys. The values are sizes. * @returns {void} */ $.resizeSvgIcons = function (obj) { // FF2 and older don't detect .svg_icon, so we change it detect svg elems instead var changeSel = !$('.svg_icon:first').length; $.each(obj, function (sel, size) { var arr = Array.isArray(size); var w = arr ? size[0] : size, h = arr ? size[1] : size; if (changeSel) { sel = sel.replace(/\.svg_icon/g, 'svg'); } $(sel).each(function () { this.setAttribute('width', w); this.setAttribute('height', h); if (window.opera && window.widget) { this.parentNode.style.width = w + 'px'; this.parentNode.style.height = h + 'px'; } }); }); }; return $; } /** * @file jGraduate 0.4 * * jQuery Plugin for a gradient picker * * @module jGraduate * @copyright 2010 Jeff Schiller {@link http://blog.codedread.com/}, 2010 Alexis Deveria {@link http://a.deveria.com/} * * @license Apache-2.0 * @example * // The Paint object is described below. * $.jGraduate.Paint(); // constructs a 'none' color * @example $.jGraduate.Paint({copy: o}); // creates a copy of the paint o * @example $.jGraduate.Paint({hex: '#rrggbb'}); // creates a solid color paint with hex = "#rrggbb" * @example $.jGraduate.Paint({linearGradient: o, a: 50}); // creates a linear gradient paint with opacity=0.5 * @example $.jGraduate.Paint({radialGradient: o, a: 7}); // creates a radial gradient paint with opacity=0.07 * @example $.jGraduate.Paint({hex: '#rrggbb', linearGradient: o}); // throws an exception? */ /* eslint-disable jsdoc/require-property */ /** * The jQuery namespace. * @external jQuery */ /** * The jQuery plugin namespace. * @namespace {PlainObject} fn * @memberof external:jQuery * @see {@link http://learn.jquery.com/plugins/|jQuery Plugins} */ /* eslint-enable jsdoc/require-property */ var ns = { svg: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink' }; if (!window.console) { window.console = { log: function log(str) { /* */ }, dir: function dir(str) { /* */ } }; } /** * Adds {@link external:jQuery.jGraduate.Paint}, * {@link external:jQuery.fn.jGraduateDefaults}, * {@link external:jQuery.fn.jGraduate}. * @function module:jGraduate.jGraduate * @param {external:jQuery} $ The jQuery instance to wrap * @returns {external:jQuery} */ function jQueryPluginJGraduate($) { /** * @typedef {PlainObject} module:jGraduate.jGraduatePaintOptions * @property {Float} [alpha] * @property {module:jGraduate~Paint} [copy] Copy paint object * @property {SVGLinearGradientElement} [linearGradient] * @property {SVGRadialGradientElement} [radialGradient] * @property {string} [solidColor] */ /** * @memberof module:jGraduate~ */ var Paint = /** * @param {module:jGraduate.jGraduatePaintOptions} [opt] */ function Paint(opt) { _classCallCheck(this, Paint); var options = opt || {}; this.alpha = isNaN(options.alpha) ? 100 : options.alpha; // copy paint object if (options.copy) { /** * @name module:jGraduate~Paint#type * @type {"none"|"solidColor"|"linearGradient"|"radialGradient"} */ this.type = options.copy.type; /** * Represents opacity (0-100). * @name module:jGraduate~Paint#alpha * @type {Float} */ this.alpha = options.copy.alpha; /** * Represents #RRGGBB hex of color. * @name module:jGraduate~Paint#solidColor * @type {string} */ this.solidColor = null; /** * @name module:jGraduate~Paint#linearGradient * @type {SVGLinearGradientElement} */ this.linearGradient = null; /** * @name module:jGraduate~Paint#radialGradient * @type {SVGRadialGradientElement} */ this.radialGradient = null; switch (this.type) { case 'none': break; case 'solidColor': this.solidColor = options.copy.solidColor; break; case 'linearGradient': this.linearGradient = options.copy.linearGradient.cloneNode(true); break; case 'radialGradient': this.radialGradient = options.copy.radialGradient.cloneNode(true); break; } // create linear gradient paint } else if (options.linearGradient) { this.type = 'linearGradient'; this.solidColor = null; this.radialGradient = null; this.linearGradient = options.linearGradient.cloneNode(true); // create linear gradient paint } else if (options.radialGradient) { this.type = 'radialGradient'; this.solidColor = null; this.linearGradient = null; this.radialGradient = options.radialGradient.cloneNode(true); // create solid color paint } else if (options.solidColor) { this.type = 'solidColor'; this.solidColor = options.solidColor; // create empty paint } else { this.type = 'none'; this.solidColor = null; this.linearGradient = null; this.radialGradient = null; } }; /* eslint-disable jsdoc/require-property */ /** * @namespace {PlainObject} jGraduate * @memberof external:jQuery */ $.jGraduate = /** @lends external:jQuery.jGraduate */ { /* eslint-enable jsdoc/require-property */ /** * @class external:jQuery.jGraduate.Paint * @see module:jGraduate~Paint */ Paint: Paint }; // JSDoc doesn't show this as belonging to our `module:jGraduate.Options` type, // so we use `@see` /** * @namespace {module:jGraduate.Options} jGraduateDefaults * @memberof external:jQuery.fn */ $.fn.jGraduateDefaults = /** @lends external:jQuery.fn.jGraduateDefaults */ { /** * Creates an object with a 'none' color. * @type {external:jQuery.jGraduate.Paint} * @see module:jGraduate.Options */ paint: new $.jGraduate.Paint(), /** * @namespace */ window: { /** * @type {string} * @see module:jGraduate.Options */ pickerTitle: 'Drag markers to pick a paint' }, /** * @namespace */ images: { /** * @type {string} * @see module:jGraduate.Options */ clientPath: 'images/' }, /** * @type {string} * @see module:jGraduate.Options */ newstop: 'inverse' // same, inverse, black, white }; var isGecko = navigator.userAgent.includes('Gecko/'); /** * @typedef {PlainObject<string, string>} module:jGraduate.Attrs */ /** * @param {SVGElement} elem * @param {module:jGraduate.Attrs} attrs * @returns {void} */ function setAttrs(elem, attrs) { if (isGecko) { Object.entries(attrs).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), aname = _ref2[0], val = _ref2[1]; elem.setAttribute(aname, val); }); } else { Object.entries(attrs).forEach(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), aname = _ref4[0], val = _ref4[1]; var prop = elem[aname]; if (prop && prop.constructor === 'SVGLength') { prop.baseVal.value = val; } else { elem.setAttribute(aname, val); } }); } } /** * @param {string} name * @param {module:jGraduate.Attrs} attrs * @param {Element} newparent * @returns {SVGElement} */ function mkElem(name, attrs, newparent) { var elem = document.createElementNS(ns.svg, name); setAttrs(elem, attrs); if (newparent) { newparent.append(elem); } return elem; } /** * @typedef {PlainObject} module:jGraduate.ColorOpac Object may have one or both values * @property {string} [color] #Hex color * @property {Float} [opac] 0-1 */ /** * @typedef {PlainObject} module:jGraduate.Options * @property {module:jGraduate~Paint} [paint] A Paint object object describing the paint to display initially; defaults to a new instance without options (defaults to opaque white) * @property {external:Window} [window] * @property {string} [window.pickerTitle='Drag markers to pick a paint'] * @property {PlainObject} [images] * @property {string} [images.clientPath='images/'] * @property {"same"|"inverse"|"black"|"white"|module:jGraduate.ColorOpac} [newstop="inverse"] */ /** * @callback external:jQuery.fn.jGraduate.OkCallback * @param {external:jQuery.jGraduate.Paint} paint * @returns {void} */ /** * @callback external:jQuery.fn.jGraduate.CancelCallback * @returns {void} */ /** * @function external:jQuery.fn.jGraduate * @param {module:jGraduate.Options} [options] * @param {external:jQuery.fn.jGraduate.OkCallback} [okCallback] Called with a Paint object when Ok is pressed * @param {external:jQuery.fn.jGraduate.CancelCallback} [cancelCallback] Called with no arguments when Cancel is pressed * @returns {external:jQuery} */ $.fn.jGraduate = function (options, okCallback, cancelCallback) { return this.each(function () { var $this = $(this), $settings = $.extend(true, {}, $.fn.jGraduateDefaults, options || {}), id = $this.attr('id'), idref = '#' + $this.attr('id') + ' '; if (!idref) { /* await */ $.alert('Container element must have an id attribute to maintain unique id strings for sub-elements.'); return; } var okClicked = function okClicked() { switch ($this.paint.type) { case 'radialGradient': $this.paint.linearGradient = null; break; case 'linearGradient': $this.paint.radialGradient = null; break; case 'solidColor': $this.paint.radialGradient = $this.paint.linearGradient = null; break; } typeof $this.okCallback === 'function' && $this.okCallback($this.paint); $this.hide(); }; var cancelClicked = function cancelClicked() { typeof $this.cancelCallback === 'function' && $this.cancelCallback(); $this.hide(); }; $.extend(true, $this, // public properties, methods, and callbacks { // make a copy of the incoming paint paint: new $.jGraduate.Paint({ copy: $settings.paint }), okCallback: typeof okCallback === 'function' ? okCallback : null, cancelCallback: typeof cancelCallback === 'function' ? cancelCallback : null }); var // pos = $this.position(), color = null; var $win = $(window); if ($this.paint.type === 'none') { $this.paint = new $.jGraduate.Paint({ solidColor: 'ffffff' }); } $this.addClass('jGraduate_Picker'); /* eslint-disable max-len */ $this.html('<ul class="jGraduate_tabs">' + '<li class="jGraduate_tab_color jGraduate_tab_current" data-type="col">Solid Color</li>' + '<li class="jGraduate_tab_lingrad" data-type="lg">Linear Gradient</li>' + '<li class="jGraduate_tab_radgrad" data-type="rg">Radial Gradient</li>' + '</ul>' + '<div class="jGraduate_colPick"></div>' + '<div class="jGraduate_gradPick"></div>' + '<div class="jGraduate_LightBox"></div>' + '<div id="' + id + '_jGraduate_stopPicker" class="jGraduate_stopPicker"></div>'); var colPicker = $(idref + '> .jGraduate_colPick'); var gradPicker = $(idref + '> .jGraduate_gradPick'); gradPicker.html('<div id="' + id + '_jGraduate_Swatch" class="jGraduate_Swatch">' + '<h2 class="jGraduate_Title">' + $settings.window.pickerTitle + '</h2>' + '<div id="' + id + '_jGraduate_GradContainer" class="jGraduate_GradContainer"></div>' + '<div id="' + id + '_jGraduate_StopSlider" class="jGraduate_StopSlider"></div>' + '</div>' + '<div class="jGraduate_Form jGraduate_Points jGraduate_lg_field">' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">Begin Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_x1" size="3" title="Enter starting x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_y1" size="3" title="Enter starting y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">End Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_x2" size="3" title="Enter ending x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_y2" size="3" title="Enter ending y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '</div>' + '<div class="jGraduate_Form jGraduate_Points jGraduate_rg_field">' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">Center Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_cx" size="3" title="Enter x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_cy" size="3" title="Enter y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">Focal Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>Match center: <input type="checkbox" checked="checked" id="' + id + '_jGraduate_match_ctr"/></label><br/>' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_fx" size="3" title="Enter x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_fy" size="3" title="Enter y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '</div>' + '<div class="jGraduate_StopSection jGraduate_SpreadMethod">' + '<label class="jGraduate_Form_Heading">Spread method</label>' + '<div class="jGraduate_Form_Section">' + '<select class="jGraduate_spreadMethod">' + '<option value=pad selected>Pad</option>' + '<option value=reflect>Reflect</option>' + '<option value=repeat>Repeat</option>' + '</select>' + '</div>' + '</div>' + '<div class="jGraduate_Form">' + '<div class="jGraduate_Slider jGraduate_RadiusField jGraduate_rg_field">' + '<label class="prelabel">Radius:</label>' + '<div id="' + id + '_jGraduate_Radius" class="jGraduate_SliderBar jGraduate_Radius" title="Click to set radius">' + '<img id="' + id + '_jGraduate_RadiusArrows" class="jGraduate_RadiusArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_RadiusInput" size="3" value="100"/>%</label>' + '</div>' + '<div class="jGraduate_Slider jGraduate_EllipField jGraduate_rg_field">' + '<label class="prelabel">Ellip:</label>' + '<div id="' + id + '_jGraduate_Ellip" class="jGraduate_SliderBar jGraduate_Ellip" title="Click to set Ellip">' + '<img id="' + id + '_jGraduate_EllipArrows" class="jGraduate_EllipArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_EllipInput" size="3" value="0"/>%</label>' + '</div>' + '<div class="jGraduate_Slider jGraduate_AngleField jGraduate_rg_field">' + '<label class="prelabel">Angle:</label>' + '<div id="' + id + '_jGraduate_Angle" class="jGraduate_SliderBar jGraduate_Angle" title="Click to set Angle">' + '<img id="' + id + '_jGraduate_AngleArrows" class="jGraduate_AngleArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_AngleInput" size="3" value="0"/>deg</label>' + '</div>' + '<div class="jGraduate_Slider jGraduate_OpacField">' + '<label class="prelabel">Opac:</label>' + '<div id="' + id + '_jGraduate_Opac" class="jGraduate_SliderBar jGraduate_Opac" title="Click to set Opac">' + '<img id="' + id + '_jGraduate_OpacArrows" class="jGraduate_OpacArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_OpacInput" size="3" value="100"/>%</label>' + '</div>' + '</div>' + '<div class="jGraduate_OkCancel">' + '<input type="button" id="' + id + '_jGraduate_Ok" class="jGraduate_Ok" value="OK"/>' + '<input type="button" id="' + id + '_jGraduate_Cancel" class="jGraduate_Cancel" value="Cancel"/>' + '</div>'); /* eslint-enable max-len */ // -------------- // Set up all the SVG elements (the gradient, stops and rectangle) var MAX = 256, MARGINX = 0, MARGINY = 0, // STOP_RADIUS = 15 / 2, SIZEX = MAX - 2 * MARGINX, SIZEY = MAX - 2 * MARGINY; var attrInput = {}; var SLIDERW = 145; $('.jGraduate_SliderBar').width(SLIDERW); var container = $('#' + id + '_jGraduate_GradContainer')[0]; var svg = mkElem('svg', { id: id + '_jgraduate_svg', width: MAX, height: MAX, xmlns: ns.svg }, container); // This wasn't working as designed // let curType; // curType = curType || $this.paint.type; // if we are sent a gradient, import it var curType = $this.paint.type; var grad = $this.paint[curType]; var curGradient = grad; var gradalpha = $this.paint.alpha; var isSolid = curType === 'solidColor'; // Make any missing gradients switch (curType) { case 'solidColor': // fall through case 'linearGradient': if (!isSolid) { curGradient.id = id + '_lg_jgraduate_grad'; grad = curGradient = svg.appendChild(curGradient); // .cloneNode(true)); } mkElem('radialGradient', { id: id + '_rg_jgraduate_grad' }, svg); if (curType === 'linearGradient') { break; } // fall through case 'radialGradient': if (!isSolid) { curGradient.id = id + '_rg_jgraduate_grad'; grad = curGradient = svg.appendChild(curGradient); // .cloneNode(true)); } mkElem('linearGradient', { id: id + '_lg_jgraduate_grad' }, svg); } var stopGroup; // eslint-disable-line prefer-const if (isSolid) { grad = curGradient = $('#' + id + '_lg_jgraduate_grad')[0]; color = $this.paint[curType]; mkStop(0, '#' + color, 1); var type = _typeof($settings.newstop); if (type === 'string') { switch ($settings.newstop) { case 'same': mkStop(1, '#' + color, 1); break; case 'inverse': { // Invert current color for second stop var inverted = ''; for (var i = 0; i < 6; i += 2) { // const ch = color.substr(i, 2); var inv = (255 - Number.parseInt(color.substr(i, 2), 16)).toString(16); if (inv.length < 2) inv = 0 + inv; inverted += inv; } mkStop(1, '#' + inverted, 1); break; } case 'white': mkStop(1, '#ffffff', 1); break; case 'black': mkStop(1, '#000000', 1); break; } } else if (type === 'object') { var opac = 'opac' in $settings.newstop ? $settings.newstop.opac : 1; mkStop(1, $settings.newstop.color || '#' + color, opac); } } var x1 = Number.parseFloat(grad.getAttribute('x1') || 0.0), y1 = Number.parseFloat(grad.getAttribute('y1') || 0.0), x2 = Number.parseFloat(grad.getAttribute('x2') || 1.0), y2 = Number.parseFloat(grad.getAttribute('y2') || 0.0); var cx = Number.parseFloat(grad.getAttribute('cx') || 0.5), cy = Number.parseFloat(grad.getAttribute('cy') || 0.5), fx = Number.parseFloat(grad.getAttribute('fx') || cx), fy = Number.parseFloat(grad.getAttribute('fy') || cy); var previewRect = mkElem('rect', { id: id + '_jgraduate_rect', x: MARGINX, y: MARGINY, width: SIZEX, height: SIZEY, fill: 'url(#' + id + '_jgraduate_grad)', 'fill-opacity': gradalpha / 100 }, svg); // stop visuals created here var beginCoord = $('<div/>').attr({ "class": 'grad_coord jGraduate_lg_field', title: 'Begin Stop' }).text(1).css({ top: y1 * MAX, left: x1 * MAX }).data('coord', 'start').appendTo(container); var endCoord = beginCoord.clone().text(2).css({ top: y2 * MAX, left: x2 * MAX }).attr('title', 'End stop').data('coord', 'end').appendTo(container); var centerCoord = $('<div/>').attr({ "class": 'grad_coord jGraduate_rg_field', title: 'Center stop' }).text('C').css({ top: cy * MAX, left: cx * MAX }).data('coord', 'center').appendTo(container); var focusCoord = centerCoord.clone().text('F').css({ top: fy * MAX, left: fx * MAX, display: 'none' }).attr('title', 'Focus point').data('coord', 'focus').appendTo(container); focusCoord[0].id = id + '_jGraduate_focusCoord'; // const coords = $(idref + ' .grad_coord'); // $(container).hover(function () { // coords.animate({ // opacity: 1 // }, 500); // }, function () { // coords.animate({ // opacity: .2 // }, 500); // }); var showFocus; $.each(['x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'fx', 'fy'], function (i, attr) { var isRadial = isNaN(attr[1]); var attrval = curGradient.getAttribute(attr); if (!attrval) { // Set defaults if (isRadial) { // For radial points attrval = '0.5'; } else { // Only x2 is 1 attrval = attr === 'x2' ? '1.0' : '0.0'; } } attrInput[attr] = $('#' + id + '_jGraduate_' + attr).val(attrval).change(function () { // TODO: Support values < 0 and > 1 (zoomable preview?) if (isNaN(Number.parseFloat(this.value)) || this.value < 0) { this.value = 0.0; } else if (this.value > 1) { this.value = 1.0; } if (!(attr[0] === 'f' && !showFocus)) { if (isRadial && curType === 'radialGradient' || !isRadial && curType === 'linearGradient') { curGradient.setAttribute(attr, this.value); } } var $elem = isRadial ? attr[0] === 'c' ? centerCoord : focusCoord : attr[1] === '1' ? beginCoord : endCoord; var cssName = attr.includes('x') ? 'left' : 'top'; $elem.css(cssName, this.value * MAX); }).change(); }); /** * * @param {Float} n * @param {Float|string} colr * @param {Float} opac * @param {boolean} [sel] * @param {SVGStopElement} [stopElem] * @returns {SVGStopElement} */ function mkStop(n, colr, opac, sel, stopElem) { var stop = stopElem || mkElem('stop', { 'stop-color': colr, 'stop-opacity': opac, offset: n }, curGradient); if (stopElem) { colr = stopElem.getAttribute('stop-color'); opac = stopElem.getAttribute('stop-opacity'); n = stopElem.getAttribute('offset'); } else { curGradient.append(stop); } if (opac === null) opac = 1; var pickerD = 'M-6.2,0.9c3.6-4,6.7-4.3,6.7-12.4c-0.2,7.9,' + '3.1,8.8,6.5,12.4c3.5,3.8,2.9,9.6,0,12.3c-3.1,2.8-10.4,' + '2.7-13.2,0C-9.6,9.9-9.4,4.4-6.2,0.9z'; var pathbg = mkElem('path', { d: pickerD, fill: 'url(#jGraduate_trans)', transform: 'translate(' + (10 + n * MAX) + ', 26)' }, stopGroup); var path = mkElem('path', { d: pickerD, fill: colr, 'fill-opacity': opac, transform: 'translate(' + (10 + n * MAX) + ', 26)', stroke: '#000', 'stroke-width': 1.5 }, stopGroup); $(path).mousedown(function (e) { selectStop(this); drag = curStop; $win.mousemove(dragColor).mouseup(remDrags); stopOffset = stopMakerDiv.offset(); e.preventDefault(); return false; }).data('stop', stop).data('bg', pathbg).dblclick(function () { $('div.jGraduate_LightBox').show(); var colorhandle = this; var stopOpacity = Number(stop.getAttribute('stop-opacity')) || 1; var stopColor = stop.getAttribute('stop-color') || 1; var thisAlpha = (Number.parseFloat(stopOpacity) * 255).toString(16); while (thisAlpha.length < 2) { thisAlpha = '0' + thisAlpha; } colr = stopColor.substr(1) + thisAlpha; $('#' + id + '_jGraduate_stopPicker').css({ left: 100, bottom: 15 }).jPicker({ window: { title: 'Pick the start color and opacity for the gradient' }, images: { clientPath: $settings.images.clientPath }, color: { active: colr, alphaSupport: true } }, function (clr, arg2) { stopColor = clr.val('hex') ? '#' + clr.val('hex') : 'none'; stopOpacity = clr.val('a') !== null ? clr.val('a') / 256 : 1; colorhandle.setAttribute('fill', stopColor); colorhandle.setAttribute('fill-opacity', stopOpacity); stop.setAttribute('stop-color', stopColor); stop.setAttribute('stop-opacity', stopOpacity); $('div.jGraduate_LightBox').hide(); $('#' + id + '_jGraduate_stopPicker').hide(); }, null, function () { $('div.jGraduate_LightBox').hide(); $('#' + id + '_jGraduate_stopPicker').hide(); }); }); $(curGradient).find('stop').each(function () { var curS = $(this); if (Number(this.getAttribute('offset')) > n) { if (!colr) { var newcolor = this.getAttribute('stop-color'); var newopac = this.getAttribute('stop-opacity'); stop.setAttribute('stop-color', newcolor); path.setAttribute('fill', newcolor); stop.setAttribute('stop-opacity', newopac === null ? 1 : newopac); path.setAttribute('fill-opacity', newopac === null ? 1 : newopac); } curS.before(stop); return false; } return true; }); if (sel) selectStop(path); return stop; } /** * * @returns {void} */ function remStop() { delStop.setAttribute('display', 'none'); var path = $(curStop); var stop = path.data('stop'); var bg = path.data('bg'); $([curStop, stop, bg]).remove(); } var stopMakerDiv = $('#' + id + '_jGraduate_StopSlider'); var stops, curStop, drag; var delStop = mkElem('path', { d: 'm9.75,-6l-19.5,19.5m0,-19.5l19.5,19.5', fill: 'none', stroke: '#D00', 'stroke-width': 5, display: 'none' }, undefined); // stopMakerSVG); /** * @param {Element} item * @returns {void} */ function selectStop(item) { if (curStop) curStop.setAttribute('stroke', '#000'); item.setAttribute('stroke', 'blue'); curStop = item; // stops = $('stop'); // opac_select.val(curStop.attr('fill-opacity') || 1); // root.append(delStop); } var stopOffset; /** * * @returns {void} */ function remDrags() { $win.unbind('mousemove', dragColor); if (delStop.getAttribute('display') !== 'none') { remStop(); } drag = null; } var scaleX = 1, scaleY = 1, angle = 0; var cX = cx; var cY = cy; /** * * @returns {void} */ function xform() { var rot = angle ? 'rotate(' + angle + ',' + cX + ',' + cY + ') ' : ''; if (scaleX === 1 && scaleY === 1) { curGradient.removeAttribute('gradientTransform'); // $('#ang').addClass('dis'); } else { var x = -cX * (scaleX - 1); var y = -cY * (scaleY - 1); curGradient.setAttribute('gradientTransform', rot + 'translate(' + x + ',' + y + ') scale(' + scaleX + ',' + scaleY + ')'); // $('#ang').removeClass('dis'); } } /** * @param {Event} evt * @returns {void} */ function dragColor(evt) { var x = evt.pageX - stopOffset.left; var y = evt.pageY - stopOffset.top; x = x < 10 ? 10 : x > MAX + 10 ? MAX + 10 : x; var xfStr = 'translate(' + x + ', 26)'; if (y < -60 || y > 130) { delStop.setAttribute('display', 'block'); delStop.setAttribute('transform', xfStr); } else { delStop.setAttribute('display', 'none'); } drag.setAttribute('transform', xfStr); $.data(drag, 'bg').setAttribute('transform', xfStr); var stop = $.data(drag, 'stop'); var sX = (x - 10) / MAX; stop.setAttribute('offset', sX); var last = 0; $(curGradient).find('stop').each(function (i) { var cur = this.getAttribute('offset'); var t = $(this); if (cur < last) { t.prev().before(t); stops = $(curGradient).find('stop'); } last = cur; }); } var stopMakerSVG = mkElem('svg', { width: '100%', height: 45 }, stopMakerDiv[0]); var transPattern = mkElem('pattern', { width: 16, height: 16, patternUnits: 'userSpaceOnUse', id: 'jGraduate_trans' }, stopMakerSVG); var transImg = mkElem('image', { width: 16, height: 16 }, transPattern); var bgImage = $settings.images.clientPath + 'map-opacity.png'; transImg.setAttributeNS(ns.xlink, 'xlink:href', bgImage); $(stopMakerSVG).click(function (evt) { stopOffset = stopMakerDiv.offset(); var target = evt.target; if (target.tagName === 'path') return; var x = evt.pageX - stopOffset.left - 8; x = x < 10 ? 10 : x > MAX + 10 ? MAX + 10 : x; mkStop(x / MAX, 0, 0, true); evt.stopPropagation(); }); $(stopMakerSVG).mouseover(function () { stopMakerSVG.append(delStop); }); stopGroup = mkElem('g', {}, stopMakerSVG); mkElem('line', { x1: 10, y1: 15, x2: MAX + 10, y2: 15, 'stroke-width': 2, stroke: '#000' }, stopMakerSVG); var spreadMethodOpt = gradPicker.find('.jGraduate_spreadMethod').change(function () { curGradient.setAttribute('spreadMethod', $(this).val()); }); // handle dragging the stop around the swatch var draggingCoord = null; var onCoordDrag = function onCoordDrag(evt) { var x = evt.pageX - offset.left; var y = evt.pageY - offset.top; // clamp stop to the swatch x = x < 0 ? 0 : x > MAX ? MAX : x; y = y < 0 ? 0 : y > MAX ? MAX : y; draggingCoord.css('left', x).css('top', y); // calculate stop offset var fracx = x / SIZEX; var fracy = y / SIZEY; var type = draggingCoord.data('coord'); var grd = curGradient; switch (type) { case 'start': attrInput.x1.val(fracx); attrInput.y1.val(fracy); grd.setAttribute('x1', fracx); grd.setAttribute('y1', fracy); break; case 'end': attrInput.x2.val(fracx); attrInput.y2.val(fracy); grd.setAttribute('x2', fracx); grd.setAttribute('y2', fracy); break; case 'center': attrInput.cx.val(fracx); attrInput.cy.val(fracy); grd.setAttribute('cx', fracx); grd.setAttribute('cy', fracy); cX = fracx; cY = fracy; xform(); break; case 'focus': attrInput.fx.val(fracx); attrInput.fy.val(fracy); grd.setAttribute('fx', fracx); grd.setAttribute('fy', fracy); xform(); } evt.preventDefault(); }; var onCoordUp = function onCoordUp() { draggingCoord = null; $win.unbind('mousemove', onCoordDrag).unbind('mouseup', onCoordUp); }; // Linear gradient // (function () { stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); var numstops = stops.length; // if there are not at least two stops, then if (numstops < 2) { while (numstops < 2) { curGradient.append(document.createElementNS(ns.svg, 'stop')); ++numstops; } stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); } for (var _i = 0; _i < numstops; _i++) { mkStop(0, 0, 0, 0, stops[_i]); } spreadMethodOpt.val(curGradient.getAttribute('spreadMethod') || 'pad'); var offset; // No match, so show focus point showFocus = false; previewRect.setAttribute('fill-opacity', gradalpha / 100); $('#' + id + ' div.grad_coord').mousedown(function (evt) { evt.preventDefault(); draggingCoord = $(this); // const sPos = draggingCoord.offset(); offset = draggingCoord.parent().offset(); $win.mousemove(onCoordDrag).mouseup(onCoordUp); }); // bind GUI elements $('#' + id + '_jGraduate_Ok').bind('click', function () { $this.paint.type = curType; $this.paint[curType] = curGradient.cloneNode(true); $this.paint.solidColor = null; okClicked(); }); $('#' + id + '_jGraduate_Cancel').bind('click', function (paint) { cancelClicked(); }); if (curType === 'radialGradient') { if (showFocus) { focusCoord.show(); } else { focusCoord.hide(); attrInput.fx.val(''); attrInput.fy.val(''); } } $('#' + id + '_jGraduate_match_ctr')[0].checked = !showFocus; var lastfx, lastfy; $('#' + id + '_jGraduate_match_ctr').change(function () { showFocus = !this.checked; focusCoord.toggle(showFocus); attrInput.fx.val(''); attrInput.fy.val(''); var grd = curGradient; if (!showFocus) { lastfx = grd.getAttribute('fx'); lastfy = grd.getAttribute('fy'); grd.removeAttribute('fx'); grd.removeAttribute('fy'); } else { var fX = lastfx || 0.5; var fY = lastfy || 0.5; grd.setAttribute('fx', fX); grd.setAttribute('fy', fY); attrInput.fx.val(fX); attrInput.fy.val(fY); } }); stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); numstops = stops.length; // if there are not at least two stops, then if (numstops < 2) { while (numstops < 2) { curGradient.append(document.createElementNS(ns.svg, 'stop')); ++numstops; } stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); } var slider; var setSlider = function setSlider(e) { var _slider = slider, left = _slider.offset.left; var div = slider.parent; var x = e.pageX - left - Number.parseInt(div.css('border-left-width')); if (x > SLIDERW) x = SLIDERW; if (x <= 0) x = 0; var posx = x - 5; x /= SLIDERW; switch (slider.type) { case 'radius': x = Math.pow(x * 2, 2.5); if (x > 0.98 && x < 1.02) x = 1; if (x <= 0.01) x = 0.01; curGradient.setAttribute('r', x); break; case 'opacity': $this.paint.alpha = Number.parseInt(x * 100); previewRect.setAttribute('fill-opacity', x); break; case 'ellip': scaleX = 1; scaleY = 1; if (x < 0.5) { x /= 0.5; // 0.001 scaleX = x <= 0 ? 0.01 : x; } else if (x > 0.5) { x /= 0.5; // 2 x = 2 - x; scaleY = x <= 0 ? 0.01 : x; } xform(); x -= 1; if (scaleY === x + 1) { x = Math.abs(x); } break; case 'angle': x -= 0.5; angle = x *= 180; xform(); x /= 100; break; } slider.elem.css({ 'margin-left': posx }); x = Math.round(x * 100); slider.input.val(x); }; var ellipVal = 0, angleVal = 0; if (curType === 'radialGradient') { var tlist = curGradient.gradientTransform.baseVal; if (tlist.numberOfItems === 2) { var t = tlist.getItem(0); var s = tlist.getItem(1); if (t.type === 2 && s.type === 3) { var m = s.matrix; if (m.a !== 1) { ellipVal = Math.round(-(1 - m.a) * 100); } else if (m.d !== 1) { ellipVal = Math.round((1 - m.d) * 100); } } } else if (tlist.numberOfItems === 3) { // Assume [R][T][S] var r = tlist.getItem(0); var _t = tlist.getItem(1); var _s = tlist.getItem(2); if (r.type === 4 && _t.type === 2 && _s.type === 3) { angleVal = Math.round(r.angle); var _m = _s.matrix; if (_m.a !== 1) { ellipVal = Math.round(-(1 - _m.a) * 100); } else if (_m.d !== 1) { ellipVal = Math.round((1 - _m.d) * 100); } } } } var sliders = { radius: { handle: '#' + id + '_jGraduate_RadiusArrows', input: '#' + id + '_jGraduate_RadiusInput', val: (curGradient.getAttribute('r') || 0.5) * 100 }, opacity: { handle: '#' + id + '_jGraduate_OpacArrows', input: '#' + id + '_jGraduate_OpacInput', val: $this.paint.alpha || 100 }, ellip: { handle: '#' + id + '_jGraduate_EllipArrows', input: '#' + id + '_jGraduate_EllipInput', val: ellipVal }, angle: { handle: '#' + id + '_jGraduate_AngleArrows', input: '#' + id + '_jGraduate_AngleInput', val: angleVal } }; $.each(sliders, function (type, data) { var handle = $(data.handle); handle.mousedown(function (evt) { var parent = handle.parent(); slider = { type: type, elem: handle, input: $(data.input), parent: parent, offset: parent.offset() }; $win.mousemove(dragSlider).mouseup(stopSlider); evt.preventDefault(); }); $(data.input).val(data.val).change(function () { var isRad = curType === 'radialGradient'; var val = Number(this.value); var xpos = 0; switch (type) { case 'radius': if (isRad) curGradient.setAttribute('r', val / 100); xpos = Math.pow(val / 100, 1 / 2.5) / 2 * SLIDERW; break; case 'opacity': $this.paint.alpha = val; previewRect.setAttribute('fill-opacity', val / 100); xpos = val * (SLIDERW / 100); break; case 'ellip': scaleX = scaleY = 1; if (val === 0) { xpos = SLIDERW * 0.5; break; } if (val > 99.5) val = 99.5; if (val > 0) { scaleY = 1 - val / 100; } else { scaleX = -(val / 100) - 1; } xpos = SLIDERW * ((val + 100) / 2) / 100; if (isRad) xform(); break; case 'angle': angle = val; xpos = angle / 180; xpos += 0.5; xpos *= SLIDERW; if (isRad) xform(); } if (xpos > SLIDERW) { xpos = SLIDERW; } else if (xpos < 0) { xpos = 0; } handle.css({ 'margin-left': xpos - 5 }); }).change(); }); var dragSlider = function dragSlider(evt) { setSlider(evt); evt.preventDefault(); }; var stopSlider = function stopSlider(evt) { $win.unbind('mousemove', dragSlider).unbind('mouseup', stopSlider); slider = null; }; // -------------- var thisAlpha = ($this.paint.alpha * 255 / 100).toString(16); while (thisAlpha.length < 2) { thisAlpha = '0' + thisAlpha; } thisAlpha = thisAlpha.split('.')[0]; color = $this.paint.solidColor === 'none' ? '' : $this.paint.solidColor + thisAlpha; if (!isSolid) { color = stops[0].getAttribute('stop-color'); } // This should be done somewhere else, probably $.extend($.fn.jPicker.defaults.window, { alphaSupport: true, effects: { type: 'show', speed: 0 } }); colPicker.jPicker({ window: { title: $settings.window.pickerTitle }, images: { clientPath: $settings.images.clientPath }, color: { active: color, alphaSupport: true } }, function (clr) { $this.paint.type = 'solidColor'; $this.paint.alpha = clr.val('ahex') ? Math.round(clr.val('a') / 255 * 100) : 100; $this.paint.solidColor = clr.val('hex') ? clr.val('hex') : 'none'; $this.paint.radialGradient = null; okClicked(); }, null, function () { cancelClicked(); }); var tabs = $(idref + ' .jGraduate_tabs li'); tabs.click(function () { tabs.removeClass('jGraduate_tab_current'); $(this).addClass('jGraduate_tab_current'); $(idref + ' > div').hide(); var type = $(this).attr('data-type'); /* const container = */ $(idref + ' .jGraduate_gradPick').show(); if (type === 'rg' || type === 'lg') { // Show/hide appropriate fields $('.jGraduate_' + type + '_field').show(); $('.jGraduate_' + (type === 'lg' ? 'rg' : 'lg') + '_field').hide(); $('#' + id + '_jgraduate_rect')[0].setAttribute('fill', 'url(#' + id + '_' + type + '_jgraduate_grad)'); // Copy stops curType = type === 'lg' ? 'linearGradient' : 'radialGradient'; $('#' + id + '_jGraduate_OpacInput').val($this.paint.alpha).change(); var newGrad = $('#' + id + '_' + type + '_jgraduate_grad')[0]; if (curGradient !== newGrad) { var curStops = $(curGradient).find('stop'); $(newGrad).empty().append(curStops); curGradient = newGrad; var sm = spreadMethodOpt.val(); curGradient.setAttribute('spreadMethod', sm); } showFocus = type === 'rg' && curGradient.getAttribute('fx') !== null && !(cx === fx && cy === fy); $('#' + id + '_jGraduate_focusCoord').toggle(showFocus); if (showFocus) { $('#' + id + '_jGraduate_match_ctr')[0].checked = false; } } else { $(idref + ' .jGraduate_gradPick').hide(); $(idref + ' .jGraduate_colPick').show(); } }); $(idref + ' > div').hide(); tabs.removeClass('jGraduate_tab_current'); var tab; switch ($this.paint.type) { case 'linearGradient': tab = $(idref + ' .jGraduate_tab_lingrad'); break; case 'radialGradient': tab = $(idref + ' .jGraduate_tab_radgrad'); break; default: tab = $(idref + ' .jGraduate_tab_color'); break; } $this.show(); // jPicker will try to show after a 0ms timeout, so need to fire this after that setTimeout(function () { tab.addClass('jGraduate_tab_current').click(); }, 10); }); }; return $; } /** * SpinButton control. * * Adds bells and whistles to any ordinary textbox to * make it look and feel like a SpinButton Control. * * Supplies {@link external:jQuery.fn.SpinButton}). * * Originally written by George Adamson, Software Unity (george.jquery@softwareunity.com) August 2006: * - Added min/max options. * - Added step size option. * - Added bigStep (page up/down) option. * * Modifications made by Mark Gibson, (mgibson@designlinks.net) September 2006: * - Converted to jQuery plugin. * - Allow limited or unlimited min/max values. * - Allow custom class names, and add class to input element. * - Removed global vars. * - Reset (to original or through config) when invalid value entered. * - Repeat whilst holding mouse button down (with initial pause, like keyboard repeat). * - Support mouse wheel in Firefox. * - Fix double click in IE. * - Refactored some code and renamed some vars. * * Modifications by Jeff Schiller, June 2009: * - provide callback function for when the value changes based on the following * {@link https://www.mail-archive.com/jquery-en@googlegroups.com/msg36070.html}. * * Modifications by Jeff Schiller, July 2009: * - improve styling for widget in Opera. * - consistent key-repeat handling cross-browser. * * Modifications by Alexis Deveria, October 2009: * - provide "stepfunc" callback option to allow custom function to run when changing a value. * - Made adjustValue(0) only run on certain keyup events, not all. * * Tested in IE6, Opera9, Firefox 1.5. * * | Version | Date | Author | Notes | * |---------|------|--------|-------| * | v1.0 | 11 Aug 2006 | George Adamson | First release | * | v1.1 | Aug 2006 | George Adamson | Minor enhancements | * | v1.2 | 27 Sep 2006 | Mark Gibson | Major enhancements | * | v1.3a | 28 Sep 2006 | George Adamson | Minor enhancements | * | v1.4 | 18 Jun 2009 | Jeff Schiller | Added callback function | * | v1.5 | 06 Jul 2009 | Jeff Schiller | Fixes for Opera. | * | v1.6 | 13 Oct 2009 | Alexis Deveria | Added stepfunc function | * | v1.7 | 21 Oct 2009 | Alexis Deveria | Minor fixes.<br />Fast-repeat for keys and live updating as you type. | * | v1.8 | 12 Jan 2010 | Benjamin Thomas | Fixes for mouseout behavior.<br />Added smallStep | * | v1.9 | 20 May 2018 | Brett Zamir | Avoid SVGEdit dependency via `stateObj` config;<br />convert to ES6 module | * . * * @module jQuerySpinButton * @example // Create group of settings to initialise spinbutton(s). (Optional) const myOptions = { min: 0, // Set lower limit. max: 100, // Set upper limit. step: 1, // Set increment size. smallStep: 0.5, // Set shift-click increment size. stateObj: {tool_scale: 1}, // Object to allow passing in live-updating scale spinClass: mySpinBtnClass, // CSS class to style the spinbutton. (Class also specifies url of the up/down button image.) upClass: mySpinUpClass, // CSS class for style when mouse over up button. downClass: mySpinDnClass // CSS class for style when mouse over down button. }; $(function () { // Initialise INPUT element(s) as SpinButtons: (passing options if desired) $('#myInputElement').SpinButton(myOptions); }); */ /** * @function module:jQuerySpinButton.jQuerySpinButton * @param {external:jQuery} $ The jQuery object to which to add the plug-in * @returns {external:jQuery} */ function jQueryPluginSpinButton($) { /** * @callback module:jQuerySpinButton.StepCallback * @param {external:jQuery} thisArg Value of `this` * @param {Float} i Value to adjust * @returns {Float} */ /** * @callback module:jQuerySpinButton.ValueCallback * @param {external:jQuery.fn.SpinButton} thisArg Spin Button; check its `value` to see how it was changed. * @returns {void} */ /** * @typedef {PlainObject} module:jQuerySpinButton.SpinButtonConfig * @property {Float} min Set lower limit * @property {Float} max Set upper limit. * @property {Float} step Set increment size. * @property {module:jQuerySpinButton.StepCallback} stepfunc Custom function to run when changing a value; called with `this` of object and the value to adjust and returns a float. * @property {module:jQuerySpinButton.ValueCallback} callback Called after value adjusted (with `this` of object) * @property {Float} smallStep Set shift-click increment size. * @property {PlainObject} stateObj Object to allow passing in live-updating scale * @property {Float} stateObj.tool_scale * @property {string} spinClass CSS class to style the spinbutton. (Class also specifies url of the up/down button image.) * @property {string} upClass CSS class for style when mouse over up button. * @property {string} downClass CSS class for style when mouse over down button. * @property {Float} page Value to be adjusted on page up/page down * @property {Float} reset Reset value when invalid value entered * @property {Float} delay Millisecond delay * @property {Float} interval Millisecond interval */ /** * @function external:jQuery.fn.SpinButton * @param {module:jQuerySpinButton.SpinButtonConfig} cfg * @returns {external:jQuery} */ $.fn.SpinButton = function (cfg) { cfg = cfg || {}; /** * * @param {Element} el * @param {"offsetLeft"|"offsetTop"} prop * @returns {Integer} */ function coord(el, prop) { var b = document.body; var c = el[prop]; while ((el = el.offsetParent) && el !== b) { if (!$.browser.msie || el.currentStyle.position !== 'relative') { c += el[prop]; } } return c; } return this.each(function () { this.repeating = false; // Apply specified options or defaults: // (Ought to refactor this some day to use $.extend() instead) this.spinCfg = { // min: cfg.min ? Number(cfg.min) : null, // max: cfg.max ? Number(cfg.max) : null, min: !isNaN(Number.parseFloat(cfg.min)) ? Number(cfg.min) : null, // Fixes bug with min:0 max: !isNaN(Number.parseFloat(cfg.max)) ? Number(cfg.max) : null, step: cfg.step ? Number(cfg.step) : 1, stepfunc: cfg.stepfunc || false, page: cfg.page ? Number(cfg.page) : 10, upClass: cfg.upClass || 'up', downClass: cfg.downClass || 'down', reset: cfg.reset || this.value, delay: cfg.delay ? Number(cfg.delay) : 500, interval: cfg.interval ? Number(cfg.interval) : 100, _btn_width: 20, _direction: null, _delay: null, _repeat: null, callback: cfg.callback || null }; // if a smallStep isn't supplied, use half the regular step this.spinCfg.smallStep = cfg.smallStep || this.spinCfg.step / 2; this.adjustValue = function (i) { var v; if (isNaN(this.value)) { v = this.spinCfg.reset; } else if (typeof this.spinCfg.stepfunc === 'function') { v = this.spinCfg.stepfunc(this, i); } else { // weirdest JavaScript bug ever: 5.1 + 0.1 = 5.199999999 v = Number((Number(this.value) + Number(i)).toFixed(5)); } if (this.spinCfg.min !== null) { v = Math.max(v, this.spinCfg.min); } if (this.spinCfg.max !== null) { v = Math.min(v, this.spinCfg.max); } this.value = v; if (typeof this.spinCfg.callback === 'function') { this.spinCfg.callback(this); } }; $(this).addClass(cfg.spinClass || 'spin-button').mousemove(function (e) { // Determine which button mouse is over, or not (spin direction): var x = e.pageX || e.x; var y = e.pageY || e.y; var el = e.target; var scale = cfg.stateObj.tool_scale || 1; var height = $(el).height() / 2; var direction = x > coord(el, 'offsetLeft') + el.offsetWidth * scale - this.spinCfg._btn_width ? y < coord(el, 'offsetTop') + height * scale ? 1 : -1 : 0; if (direction !== this.spinCfg._direction) { // Style up/down buttons: switch (direction) { case 1: // Up arrow: $(this).removeClass(this.spinCfg.downClass).addClass(this.spinCfg.upClass); break; case -1: // Down arrow: $(this).removeClass(this.spinCfg.upClass).addClass(this.spinCfg.downClass); break; default: // Mouse is elsewhere in the textbox $(this).removeClass(this.spinCfg.upClass).removeClass(this.spinCfg.downClass); } // Set spin direction: this.spinCfg._direction = direction; } }).mouseout(function () { // Reset up/down buttons to their normal appearance when mouse moves away: $(this).removeClass(this.spinCfg.upClass).removeClass(this.spinCfg.downClass); this.spinCfg._direction = null; window.clearInterval(this.spinCfg._repeat); window.clearTimeout(this.spinCfg._delay); }).mousedown(function (e) { var _this = this; if (e.button === 0 && this.spinCfg._direction !== 0) { // Respond to click on one of the buttons: var stepSize = e.shiftKey ? this.spinCfg.smallStep : this.spinCfg.step; var adjust = function adjust() { _this.adjustValue(_this.spinCfg._direction * stepSize); }; adjust(); // Initial delay before repeating adjustment this.spinCfg._delay = window.setTimeout(function () { adjust(); // Repeat adjust at regular intervals _this.spinCfg._repeat = window.setInterval(adjust, _this.spinCfg.interval); }, this.spinCfg.delay); } }).mouseup(function (e) { // Cancel repeating adjustment window.clearInterval(this.spinCfg._repeat); window.clearTimeout(this.spinCfg._delay); }).dblclick(function (e) { if ($.browser.msie) { this.adjustValue(this.spinCfg._direction * this.spinCfg.step); } }).keydown(function (e) { // Respond to up/down arrow keys. switch (e.keyCode) { case 38: this.adjustValue(this.spinCfg.step); break; // Up case 40: this.adjustValue(-this.spinCfg.step); break; // Down case 33: this.adjustValue(this.spinCfg.page); break; // PageUp case 34: this.adjustValue(-this.spinCfg.page); break; // PageDown } }) /* http://unixpapa.com/js/key.html describes the current state-of-affairs for key repeat events: - Safari 3.1 changed their model so that keydown is reliably repeated going forward - Firefox and Opera still only repeat the keypress event, not the keydown */ .keypress(function (e) { if (this.repeating) { // Respond to up/down arrow keys. switch (e.keyCode) { case 38: this.adjustValue(this.spinCfg.step); break; // Up case 40: this.adjustValue(-this.spinCfg.step); break; // Down case 33: this.adjustValue(this.spinCfg.page); break; // PageUp case 34: this.adjustValue(-this.spinCfg.page); break; // PageDown } // we always ignore the first keypress event (use the keydown instead) } else { this.repeating = true; } }) // clear the 'repeating' flag .keyup(function (e) { this.repeating = false; switch (e.keyCode) { case 38: // Up case 40: // Down case 33: // PageUp case 34: // PageDown case 13: this.adjustValue(0); break; // Enter/Return } }).bind('mousewheel', function (e) { // Respond to mouse wheel in IE. (It returns up/dn motion in multiples of 120) if (e.wheelDelta >= 120) { this.adjustValue(this.spinCfg.step); } else if (e.wheelDelta <= -120) { this.adjustValue(-this.spinCfg.step); } e.preventDefault(); }).change(function (e) { this.adjustValue(0); }); if (this.addEventListener) { // Respond to mouse wheel in Firefox this.addEventListener('DOMMouseScroll', function (e) { if (e.detail > 0) { this.adjustValue(-this.spinCfg.step); } else if (e.detail < 0) { this.adjustValue(this.spinCfg.step); } e.preventDefault(); }); } }); }; return $; } /** * @callback module:jQueryContextMenu.jQueryContextMenuListener * @param {string} href The `href` value after the first character (for bypassing an initial `#`) * @param {external:jQuery} srcElement The wrapped jQuery srcElement * @param {{x: Float, y: Float, docX: Float, docY: Float}} coords * @returns {void} */ /** * @typedef {PlainObject} module:jQueryContextMenu.jQueryContextMenuConfig * @property {string} menu * @property {Float} inSpeed * @property {Float} outSpeed * @property {boolean} allowLeft */ /** * Adds {@link external:jQuery.fn.contextMenu}, * {@link external:jQuery.fn.disableContextMenuItems}, * {@link external:jQuery.fn.enableContextMenuItems}, * {@link external:jQuery.fn.disableContextMenu}, * {@link external:jQuery.fn.enableContextMenu}, * {@link external:jQuery.fn.destroyContextMenu}. * @function module:jQueryContextMenu.jQueryContextMenu * @param {external:jQuery} $ The jQuery object to wrap (with `contextMenu`, `disableContextMenuItems`, `enableContextMenuItems`, `disableContextMenu`, `enableContextMenu`, `destroyContextMenu`) * @returns {external:jQuery} */ function jQueryContextMenu($) { var win = $(window); var doc = $(document); $.extend($.fn, { /** * @memberof external:jQuery.fn * @param {module:jQueryContextMenu.jQueryContextMenuConfig} o * @param {module:jQueryContextMenu.jQueryContextMenuListener} listener * @returns {external:jQuery} */ contextMenu: function contextMenu(o, listener) { // Defaults if (o.menu === undefined) return false; if (o.inSpeed === undefined) o.inSpeed = 150; if (o.outSpeed === undefined) o.outSpeed = 75; // 0 needs to be -1 for expected results (no fade) if (o.inSpeed === 0) o.inSpeed = -1; if (o.outSpeed === 0) o.outSpeed = -1; // Loop each context menu $(this).each(function () { var el = $(this); var offset = $(el).offset(); var menu = $('#' + o.menu); // Add contextMenu class menu.addClass('contextMenu'); // Simulate a true right click $(this).bind('mousedown', function (evt) { $(this).mouseup(function (e) { var srcElement = $(this); srcElement.unbind('mouseup'); if (!(evt.button === 2 || o.allowLeft || evt.ctrlKey && isMac())) { return undefined; } e.stopPropagation(); // Hide context menus that may be showing $('.contextMenu').hide(); // Get this context menu if (el.hasClass('disabled')) return false; // Detect mouse position var x = e.pageX, y = e.pageY; var xOff = win.width() - menu.width(), yOff = win.height() - menu.height(); if (x > xOff - 15) x = xOff - 15; if (y > yOff - 30) y = yOff - 30; // 30 is needed to prevent scrollbars in FF // Show the menu doc.unbind('click'); menu.css({ top: y, left: x }).fadeIn(o.inSpeed); // Hover events menu.find('A').mouseover(function () { menu.find('LI.hover').removeClass('hover'); $(this).parent().addClass('hover'); }).mouseout(function () { menu.find('LI.hover').removeClass('hover'); }); // Keyboard doc.keypress(function (ev) { switch (ev.keyCode) { case 38: // up if (!menu.find('LI.hover').length) { menu.find('LI:last').addClass('hover'); } else { menu.find('LI.hover').removeClass('hover').prevAll('LI:not(.disabled)').eq(0).addClass('hover'); if (!menu.find('LI.hover').length) menu.find('LI:last').addClass('hover'); } break; case 40: // down if (!menu.find('LI.hover').length) { menu.find('LI:first').addClass('hover'); } else { menu.find('LI.hover').removeClass('hover').nextAll('LI:not(.disabled)').eq(0).addClass('hover'); if (!menu.find('LI.hover').length) menu.find('LI:first').addClass('hover'); } break; case 13: // enter menu.find('LI.hover A').trigger('click'); break; case 27: // esc doc.trigger('click'); break; } }); // When items are selected menu.find('A').unbind('mouseup'); menu.find('LI:not(.disabled) A').mouseup(function () { doc.unbind('click').unbind('keypress'); $('.contextMenu').hide(); if (listener) { listener($(this).attr('href').substr(1), $(srcElement), { x: x - offset.left, y: y - offset.top, docX: x, docY: y }); } return false; }); // Hide bindings setTimeout(function () { // Delay for Mozilla doc.click(function () { doc.unbind('click').unbind('keypress'); menu.fadeOut(o.outSpeed); return false; }); }, 0); return undefined; }); }); // Disable text selection if ($.browser.mozilla) { $('#' + o.menu).each(function () { $(this).css({ MozUserSelect: 'none' }); }); } else if ($.browser.msie) { $('#' + o.menu).each(function () { $(this).bind('selectstart.disableTextSelect', function () { return false; }); }); } else { $('#' + o.menu).each(function () { $(this).bind('mousedown.disableTextSelect', function () { return false; }); }); } // Disable browser context menu (requires both selectors to work in IE/Safari + FF/Chrome) $(el).add($('UL.contextMenu')).bind('contextmenu', function () { return false; }); }); return $(this); }, /** * Disable context menu items on the fly. * @memberof external:jQuery.fn * @param {void|string} o Comma-separated * @returns {external:jQuery} */ disableContextMenuItems: function disableContextMenuItems(o) { if (o === undefined) { // Disable all $(this).find('LI').addClass('disabled'); return $(this); } $(this).each(function () { if (o !== undefined) { var d = o.split(','); var _iterator = _createForOfIteratorHelper(d), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var href = _step.value; $(this).find('A[href="' + href + '"]').parent().addClass('disabled'); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } }); return $(this); }, /** * Enable context menu items on the fly. * @memberof external:jQuery.fn * @param {void|string} o Comma-separated * @returns {external:jQuery} */ enableContextMenuItems: function enableContextMenuItems(o) { if (o === undefined) { // Enable all $(this).find('LI.disabled').removeClass('disabled'); return $(this); } $(this).each(function () { if (o !== undefined) { var d = o.split(','); var _iterator2 = _createForOfIteratorHelper(d), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var href = _step2.value; $(this).find('A[href="' + href + '"]').parent().removeClass('disabled'); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } }); return $(this); }, /** * Disable context menu(s). * @memberof external:jQuery.fn * @returns {external:jQuery} */ disableContextMenu: function disableContextMenu() { $(this).each(function () { $(this).addClass('disabled'); }); return $(this); }, /** * Enable context menu(s). * @memberof external:jQuery.fn * @returns {external:jQuery} */ enableContextMenu: function enableContextMenu() { $(this).each(function () { $(this).removeClass('disabled'); }); return $(this); }, /** * Destroy context menu(s). * @memberof external:jQuery.fn * @returns {external:jQuery} */ destroyContextMenu: function destroyContextMenu() { // Destroy specified context menus $(this).each(function () { // Disable action $(this).unbind('mousedown').unbind('mouseup'); }); return $(this); } }); return $; } /* eslint-disable no-bitwise, max-len */ /** * @file jPicker (Adapted from version 1.1.6) * * jQuery Plugin for Photoshop style color picker * * @module jPicker * @copyright (c) 2010 Christopher T. Tillman * Digital Magic Productions, Inc. ({@link http://www.digitalmagicpro.com/}) * FREE to use, alter, copy, sell, and especially ENHANCE * @license MIT * * Painstakingly ported from John Dyers' excellent work on his own color picker based on the Prototype framework. * * John Dyers' website: {@link http://johndyer.name} * Color Picker page: {@link http://johndyer.name/photoshop-like-javascript-color-picker/} */ /** * @external Math */ /** * @memberof external:Math * @param {Float} value * @param {Float} precision * @returns {Float} */ function toFixedNumeric(value, precision) { if (precision === undefined) precision = 0; return Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision); } /** * Whether a value is `null` or `undefined`. * @param {any} val * @returns {boolean} */ var isNullish$2 = function isNullish(val) { return val === null || val === undefined; }; /** * @function module:jPicker.jPicker * @param {external:jQuery} $ The jQuery object, {@link external:jQuery.fn.$.fn.jPicker}, {@link external:jQuery.fn.$.fn.jPicker.defaults}) * @returns {external:jQuery} */ var jPicker = function jPicker($) { /** * @typedef {PlainObject} module:jPicker.SliderOptions * @property {external:jQuery|PlainObject} arrow * @property {string} arrow.image Not in use? * @property {Float} arrow.width * @property {Float} arrow.height * @property {PlainObject} map * @property {Float} map.width * @property {Float} map.height */ /** * Encapsulate slider functionality for the ColorMap and ColorBar - * could be useful to use a jQuery UI draggable for this with certain extensions. * @memberof module:jPicker */ var Slider = /** * @param {external:jQuery} bar * @param {module:jPicker.SliderOptions} options */ function Slider(bar, options) { _classCallCheck(this, Slider); var that = this; /** * Fire events on the supplied `context` * @param {module:jPicker.JPickerInit} context * @returns {void} */ function fireChangeEvents(context) { changeEvents.forEach(function (changeEvent) { changeEvent.call(that, that, context); }); } /** * Bind the mousedown to the bar not the arrow for quick snapping to the clicked location. * @param {external:jQuery.Event} e * @returns {void} */ function mouseDown(e) { var off = bar.offset(); offset = { l: off.left | 0, t: off.top | 0 }; clearTimeout(timeout); // using setTimeout for visual updates - once the style is updated the browser will re-render internally allowing the next Javascript to run timeout = setTimeout(function () { setValuesFromMousePosition.call(that, e); }, 0); // Bind mousemove and mouseup event to the document so it responds when dragged of of the bar - we will unbind these when on mouseup to save processing $(document).bind('mousemove', mouseMove).bind('mouseup', mouseUp); e.preventDefault(); // don't try to select anything or drag the image to the desktop } /** * Set the values as the mouse moves. * @param {external:jQuery.Event} e * @returns {false} */ function mouseMove(e) { clearTimeout(timeout); timeout = setTimeout(function () { setValuesFromMousePosition.call(that, e); }, 0); e.stopPropagation(); e.preventDefault(); return false; } /** * Unbind the document events - they aren't needed when not dragging. * @param {external:jQuery.Event} e * @returns {false} */ function mouseUp(e) { $(document).unbind('mouseup', mouseUp).unbind('mousemove', mouseMove); e.stopPropagation(); e.preventDefault(); return false; } /** * Calculate mouse position and set value within the current range. * @param {Event} e * @returns {void} */ function setValuesFromMousePosition(e) { var barW = bar.w, // local copies for YUI compressor barH = bar.h; var locX = e.pageX - offset.l, locY = e.pageY - offset.t; // keep the arrow within the bounds of the bar if (locX < 0) locX = 0;else if (locX > barW) locX = barW; if (locY < 0) locY = 0;else if (locY > barH) locY = barH; val.call(that, 'xy', { x: locX / barW * rangeX + minX, y: locY / barH * rangeY + minY }); } /** * * @returns {void} */ function draw() { var barW = bar.w, barH = bar.h, arrowW = arrow.w, arrowH = arrow.h; var arrowOffsetX = 0, arrowOffsetY = 0; setTimeout(function () { if (rangeX > 0) { // range is greater than zero // constrain to bounds if (x === maxX) arrowOffsetX = barW;else arrowOffsetX = x / rangeX * barW | 0; } if (rangeY > 0) { // range is greater than zero // constrain to bounds if (y === maxY) arrowOffsetY = barH;else arrowOffsetY = y / rangeY * barH | 0; } // if arrow width is greater than bar width, center arrow and prevent horizontal dragging if (arrowW >= barW) arrowOffsetX = (barW >> 1) - (arrowW >> 1); // number >> 1 - superfast bitwise divide by two and truncate (move bits over one bit discarding lowest) else arrowOffsetX -= arrowW >> 1; // if arrow height is greater than bar height, center arrow and prevent vertical dragging if (arrowH >= barH) arrowOffsetY = (barH >> 1) - (arrowH >> 1);else arrowOffsetY -= arrowH >> 1; // set the arrow position based on these offsets arrow.css({ left: arrowOffsetX + 'px', top: arrowOffsetY + 'px' }); }); } /** * Get or set a value. * @param {?("xy"|"x"|"y")} name * @param {module:math.XYObject} value * @param {module:jPicker.Slider} context * @returns {module:math.XYObject|Float|void} */ function val(name, value, context) { var set = value !== undefined; if (!set) { if (isNullish$2(name)) name = 'xy'; switch (name.toLowerCase()) { case 'x': return x; case 'y': return y; case 'xy': default: return { x: x, y: y }; } } if (!isNullish$2(context) && context === that) return undefined; var changed = false; var newX, newY; if (isNullish$2(name)) name = 'xy'; switch (name.toLowerCase()) { case 'x': newX = value && (value.x && value.x | 0 || value | 0) || 0; break; case 'y': newY = value && (value.y && value.y | 0 || value | 0) || 0; break; case 'xy': default: newX = value && value.x && value.x | 0 || 0; newY = value && value.y && value.y | 0 || 0; break; } if (!isNullish$2(newX)) { if (newX < minX) newX = minX;else if (newX > maxX) newX = maxX; if (x !== newX) { x = newX; changed = true; } } if (!isNullish$2(newY)) { if (newY < minY) newY = minY;else if (newY > maxY) newY = maxY; if (y !== newY) { y = newY; changed = true; } } changed && fireChangeEvents.call(that, context || that); return undefined; } /** * @typedef {PlainObject} module:jPicker.MinMaxRangeX * @property {Float} minX * @property {Float} maxX * @property {Float} rangeX */ /** * @typedef {PlainObject} module:jPicker.MinMaxRangeY * @property {Float} minY * @property {Float} maxY * @property {Float} rangeY */ /** * @typedef {module:jPicker.MinMaxRangeY|module:jPicker.MinMaxRangeX} module:jPicker.MinMaxRangeXY */ /** * * @param {"minx"|"maxx"|"rangex"|"miny"|"maxy"|"rangey"|"all"} name * @param {module:jPicker.MinMaxRangeXY} value * @returns {module:jPicker.MinMaxRangeXY|module:jPicker.MinMaxRangeX|module:jPicker.MinMaxRangeY|void} */ function range(name, value) { var set = value !== undefined; if (!set) { if (isNullish$2(name)) name = 'all'; switch (name.toLowerCase()) { case 'minx': return minX; case 'maxx': return maxX; case 'rangex': return { minX: minX, maxX: maxX, rangeX: rangeX }; case 'miny': return minY; case 'maxy': return maxY; case 'rangey': return { minY: minY, maxY: maxY, rangeY: rangeY }; case 'all': default: return { minX: minX, maxX: maxX, rangeX: rangeX, minY: minY, maxY: maxY, rangeY: rangeY }; } } var // changed = false, newMinX, newMaxX, newMinY, newMaxY; if (isNullish$2(name)) name = 'all'; switch (name.toLowerCase()) { case 'minx': newMinX = value && (value.minX && value.minX | 0 || value | 0) || 0; break; case 'maxx': newMaxX = value && (value.maxX && value.maxX | 0 || value | 0) || 0; break; case 'rangex': newMinX = value && value.minX && value.minX | 0 || 0; newMaxX = value && value.maxX && value.maxX | 0 || 0; break; case 'miny': newMinY = value && (value.minY && value.minY | 0 || value | 0) || 0; break; case 'maxy': newMaxY = value && (value.maxY && value.maxY | 0 || value | 0) || 0; break; case 'rangey': newMinY = value && value.minY && value.minY | 0 || 0; newMaxY = value && value.maxY && value.maxY | 0 || 0; break; case 'all': default: newMinX = value && value.minX && value.minX | 0 || 0; newMaxX = value && value.maxX && value.maxX | 0 || 0; newMinY = value && value.minY && value.minY | 0 || 0; newMaxY = value && value.maxY && value.maxY | 0 || 0; break; } if (!isNullish$2(newMinX) && minX !== newMinX) { minX = newMinX; rangeX = maxX - minX; } if (!isNullish$2(newMaxX) && maxX !== newMaxX) { maxX = newMaxX; rangeX = maxX - minX; } if (!isNullish$2(newMinY) && minY !== newMinY) { minY = newMinY; rangeY = maxY - minY; } if (!isNullish$2(newMaxY) && maxY !== newMaxY) { maxY = newMaxY; rangeY = maxY - minY; } return undefined; } /** * @param {GenericCallback} callback * @returns {void} */ function bind(callback) { // eslint-disable-line promise/prefer-await-to-callbacks if (typeof callback === 'function') changeEvents.push(callback); } /** * @param {GenericCallback} callback * @returns {void} */ function unbind(callback) { // eslint-disable-line promise/prefer-await-to-callbacks if (typeof callback !== 'function') return; var i; while (i = changeEvents.includes(callback)) { changeEvents.splice(i, 1); } } /** * * @returns {void} */ function destroy() { // unbind all possible events and null objects $(document).unbind('mouseup', mouseUp).unbind('mousemove', mouseMove); bar.unbind('mousedown', mouseDown); bar = null; arrow = null; changeEvents = null; } var offset, timeout, x = 0, y = 0, minX = 0, maxX = 100, rangeX = 100, minY = 0, maxY = 100, rangeY = 100, arrow = bar.find('img:first'), // the arrow image to drag changeEvents = []; $.extend(true, // public properties, methods, and event bindings - these we need // to access from other controls that, { val: val, range: range, bind: bind, unbind: unbind, destroy: destroy }); // initialize this control arrow.src = options.arrow && options.arrow.image; arrow.w = options.arrow && options.arrow.width || arrow.width(); arrow.h = options.arrow && options.arrow.height || arrow.height(); bar.w = options.map && options.map.width || bar.width(); bar.h = options.map && options.map.height || bar.height(); // bind mousedown event bar.bind('mousedown', mouseDown); bind.call(that, draw); }; /** * Controls for all the input elements for the typing in color values. */ var ColorValuePicker = /** * @param {external:jQuery} picker * @param {external:jQuery.jPicker.Color} color * @param {external:jQuery.fn.$.fn.jPicker} bindedHex * @param {Float} alphaPrecision */ function ColorValuePicker(picker, color, bindedHex, alphaPrecision) { _classCallCheck(this, ColorValuePicker); var that = this; // private properties and methods var inputs = picker.find('td.Text input'); // input box key down - use arrows to alter color /** * * @param {Event} e * @returns {Event|false|void} */ function keyDown(e) { if (e.target.value === '' && e.target !== hex.get(0) && (!isNullish$2(bindedHex) && e.target !== bindedHex.get(0) || isNullish$2(bindedHex))) return undefined; if (!validateKey(e)) return e; switch (e.target) { case red.get(0): switch (e.keyCode) { case 38: red.val(setValueInRange.call(that, (red.val() << 0) + 1, 0, 255)); color.val('r', red.val(), e.target); return false; case 40: red.val(setValueInRange.call(that, (red.val() << 0) - 1, 0, 255)); color.val('r', red.val(), e.target); return false; } break; case green.get(0): switch (e.keyCode) { case 38: green.val(setValueInRange.call(that, (green.val() << 0) + 1, 0, 255)); color.val('g', green.val(), e.target); return false; case 40: green.val(setValueInRange.call(that, (green.val() << 0) - 1, 0, 255)); color.val('g', green.val(), e.target); return false; } break; case blue.get(0): switch (e.keyCode) { case 38: blue.val(setValueInRange.call(that, (blue.val() << 0) + 1, 0, 255)); color.val('b', blue.val(), e.target); return false; case 40: blue.val(setValueInRange.call(that, (blue.val() << 0) - 1, 0, 255)); color.val('b', blue.val(), e.target); return false; } break; case alpha && alpha.get(0): switch (e.keyCode) { case 38: alpha.val(setValueInRange.call(that, Number.parseFloat(alpha.val()) + 1, 0, 100)); color.val('a', toFixedNumeric(alpha.val() * 255 / 100, alphaPrecision), e.target); return false; case 40: alpha.val(setValueInRange.call(that, Number.parseFloat(alpha.val()) - 1, 0, 100)); color.val('a', toFixedNumeric(alpha.val() * 255 / 100, alphaPrecision), e.target); return false; } break; case hue.get(0): switch (e.keyCode) { case 38: hue.val(setValueInRange.call(that, (hue.val() << 0) + 1, 0, 360)); color.val('h', hue.val(), e.target); return false; case 40: hue.val(setValueInRange.call(that, (hue.val() << 0) - 1, 0, 360)); color.val('h', hue.val(), e.target); return false; } break; case saturation.get(0): switch (e.keyCode) { case 38: saturation.val(setValueInRange.call(that, (saturation.val() << 0) + 1, 0, 100)); color.val('s', saturation.val(), e.target); return false; case 40: saturation.val(setValueInRange.call(that, (saturation.val() << 0) - 1, 0, 100)); color.val('s', saturation.val(), e.target); return false; } break; case value.get(0): switch (e.keyCode) { case 38: value.val(setValueInRange.call(that, (value.val() << 0) + 1, 0, 100)); color.val('v', value.val(), e.target); return false; case 40: value.val(setValueInRange.call(that, (value.val() << 0) - 1, 0, 100)); color.val('v', value.val(), e.target); return false; } break; } return undefined; } // input box key up - validate value and set color /** * @param {Event} e * @returns {Event|void} * @todo Why is this returning an event? */ function keyUp(e) { if (e.target.value === '' && e.target !== hex.get(0) && (!isNullish$2(bindedHex) && e.target !== bindedHex.get(0) || isNullish$2(bindedHex))) return undefined; if (!validateKey(e)) return e; switch (e.target) { case red.get(0): red.val(setValueInRange.call(that, red.val(), 0, 255)); color.val('r', red.val(), e.target); break; case green.get(0): green.val(setValueInRange.call(that, green.val(), 0, 255)); color.val('g', green.val(), e.target); break; case blue.get(0): blue.val(setValueInRange.call(that, blue.val(), 0, 255)); color.val('b', blue.val(), e.target); break; case alpha && alpha.get(0): alpha.val(setValueInRange.call(that, alpha.val(), 0, 100)); color.val('a', toFixedNumeric(alpha.val() * 255 / 100, alphaPrecision), e.target); break; case hue.get(0): hue.val(setValueInRange.call(that, hue.val(), 0, 360)); color.val('h', hue.val(), e.target); break; case saturation.get(0): saturation.val(setValueInRange.call(that, saturation.val(), 0, 100)); color.val('s', saturation.val(), e.target); break; case value.get(0): value.val(setValueInRange.call(that, value.val(), 0, 100)); color.val('v', value.val(), e.target); break; case hex.get(0): hex.val(hex.val().replace(/[^a-fA-F\d]/g, '').toLowerCase().substring(0, 6)); bindedHex && bindedHex.val(hex.val()); color.val('hex', hex.val() !== '' ? hex.val() : null, e.target); break; case bindedHex && bindedHex.get(0): bindedHex.val(bindedHex.val().replace(/[^a-fA-F\d]/g, '').toLowerCase().substring(0, 6)); hex.val(bindedHex.val()); color.val('hex', bindedHex.val() !== '' ? bindedHex.val() : null, e.target); break; case ahex && ahex.get(0): ahex.val(ahex.val().replace(/[^a-fA-F\d]/g, '').toLowerCase().substring(0, 2)); color.val('a', !isNullish$2(ahex.val()) ? Number.parseInt(ahex.val(), 16) : null, e.target); break; } return undefined; } // input box blur - reset to original if value empty /** * @param {Event} e * @returns {void} */ function blur(e) { if (!isNullish$2(color.val())) { switch (e.target) { case red.get(0): red.val(color.val('r')); break; case green.get(0): green.val(color.val('g')); break; case blue.get(0): blue.val(color.val('b')); break; case alpha && alpha.get(0): alpha.val(toFixedNumeric(color.val('a') * 100 / 255, alphaPrecision)); break; case hue.get(0): hue.val(color.val('h')); break; case saturation.get(0): saturation.val(color.val('s')); break; case value.get(0): value.val(color.val('v')); break; case hex.get(0): case bindedHex && bindedHex.get(0): hex.val(color.val('hex')); bindedHex && bindedHex.val(color.val('hex')); break; case ahex && ahex.get(0): ahex.val(color.val('ahex').substring(6)); break; } } } /** * @param {Event} e * @returns {boolean} */ function validateKey(e) { switch (e.keyCode) { case 9: case 16: case 29: case 37: case 39: return false; case 'c'.charCodeAt(): case 'v'.charCodeAt(): if (e.ctrlKey) return false; } return true; } /** * Constrain value within range. * @param {Float|string} value * @param {Float} min * @param {Float} max * @returns {Float|string} Returns a number or numeric string */ function setValueInRange(value, min, max) { if (value === '' || isNaN(value)) return min; if (value > max) return max; if (value < min) return min; return value; } /** * @param {external:jQuery} ui * @param {Element} context * @returns {void} */ function colorChanged(ui, context) { var all = ui.val('all'); if (context !== red.get(0)) red.val(!isNullish$2(all) ? all.r : ''); if (context !== green.get(0)) green.val(!isNullish$2(all) ? all.g : ''); if (context !== blue.get(0)) blue.val(!isNullish$2(all) ? all.b : ''); if (alpha && context !== alpha.get(0)) alpha.val(!isNullish$2(all) ? toFixedNumeric(all.a * 100 / 255, alphaPrecision) : ''); if (context !== hue.get(0)) hue.val(!isNullish$2(all) ? all.h : ''); if (context !== saturation.get(0)) saturation.val(!isNullish$2(all) ? all.s : ''); if (context !== value.get(0)) value.val(!isNullish$2(all) ? all.v : ''); if (context !== hex.get(0) && (bindedHex && context !== bindedHex.get(0) || !bindedHex)) hex.val(!isNullish$2(all) ? all.hex : ''); if (bindedHex && context !== bindedHex.get(0) && context !== hex.get(0)) bindedHex.val(!isNullish$2(all) ? all.hex : ''); if (ahex && context !== ahex.get(0)) ahex.val(!isNullish$2(all) ? all.ahex.substring(6) : ''); } /** * Unbind all events and null objects. * @returns {void} */ function destroy() { red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).add(hex).add(bindedHex).add(ahex).unbind('keyup', keyUp).unbind('blur', blur); red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).unbind('keydown', keyDown); color.unbind(colorChanged); red = null; green = null; blue = null; alpha = null; hue = null; saturation = null; value = null; hex = null; ahex = null; } var red = inputs.eq(3), green = inputs.eq(4), blue = inputs.eq(5), alpha = inputs.length > 7 ? inputs.eq(6) : null, hue = inputs.eq(0), saturation = inputs.eq(1), value = inputs.eq(2), hex = inputs.eq(inputs.length > 7 ? 7 : 6), ahex = inputs.length > 7 ? inputs.eq(8) : null; $.extend(true, that, { // public properties and methods destroy: destroy }); red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).add(hex).add(bindedHex).add(ahex).bind('keyup', keyUp).bind('blur', blur); red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).bind('keydown', keyDown); color.bind(colorChanged); }; /** * @typedef {PlainObject} module:jPicker.JPickerInit * @property {Integer} [a] * @property {Integer} [b] * @property {Integer} [g] * @property {Integer} [h] * @property {Integer} [r] * @property {Integer} [s] * @property {Integer} [v] * @property {string} [hex] * @property {string} [ahex] */ /* eslint-disable jsdoc/require-property */ /** * @namespace {PlainObject} jPicker * @memberof external:jQuery */ $.jPicker = /** @lends external:jQuery.jPicker */ { /* eslint-enable jsdoc/require-property */ /** * Array holding references to each active instance of the jPicker control. * @type {external:jQuery.fn.$.fn.jPicker[]} */ List: [], /** * Color object - we will be able to assign by any color space type or * retrieve any color space info. * We want this public so we can optionally assign new color objects to * initial values using inputs other than a string hex value (also supported) * Note: JSDoc didn't document when expressed here as an ES6 Class. * @namespace * @class * @memberof external:jQuery.jPicker * @param {module:jPicker.JPickerInit} init * @returns {external:jQuery.jPicker.Color} */ Color: function Color(init) { // eslint-disable-line object-shorthand var that = this; /** * * @param {module:jPicker.Slider} context * @returns {void} */ function fireChangeEvents(context) { for (var i = 0; i < changeEvents.length; i++) { changeEvents[i].call(that, that, context); } } /** * @param {string|"ahex"|"hex"|"all"|""|null|void} name String composed of letters "r", "g", "b", "a", "h", "s", and/or "v" * @param {module:jPicker.RGBA|module:jPicker.JPickerInit|string} [value] * @param {external:jQuery.jPicker.Color} context * @returns {module:jPicker.JPickerInit|string|null|void} */ function val(name, value, context) { // Kind of ugly var set = Boolean(value); if (set && value.ahex === '') value.ahex = '00000000'; if (!set) { var ret; if (isNullish$2(name) || name === '') name = 'all'; if (isNullish$2(r)) return null; switch (name.toLowerCase()) { case 'ahex': return ColorMethods.rgbaToHex({ r: r, g: g, b: b, a: a }); case 'hex': return val('ahex').substring(0, 6); case 'all': return { r: r, g: g, b: b, a: a, h: h, s: s, v: v, hex: val.call(that, 'hex'), ahex: val.call(that, 'ahex') }; default: { ret = {}; var nameLength = name.length; _toConsumableArray(name).forEach(function (ch) { switch (ch) { case 'r': if (nameLength === 1) ret = r;else ret.r = r; break; case 'g': if (nameLength === 1) ret = g;else ret.g = g; break; case 'b': if (nameLength === 1) ret = b;else ret.b = b; break; case 'a': if (nameLength === 1) ret = a;else ret.a = a; break; case 'h': if (nameLength === 1) ret = h;else ret.h = h; break; case 's': if (nameLength === 1) ret = s;else ret.s = s; break; case 'v': if (nameLength === 1) ret = v;else ret.v = v; break; } }); } } return _typeof(ret) === 'object' && !Object.keys(ret).length ? val.call(that, 'all') : ret; } if (!isNullish$2(context) && context === that) return undefined; if (isNullish$2(name)) name = ''; var changed = false; if (isNullish$2(value)) { if (!isNullish$2(r)) { r = null; changed = true; } if (!isNullish$2(g)) { g = null; changed = true; } if (!isNullish$2(b)) { b = null; changed = true; } if (!isNullish$2(a)) { a = null; changed = true; } if (!isNullish$2(h)) { h = null; changed = true; } if (!isNullish$2(s)) { s = null; changed = true; } if (!isNullish$2(v)) { v = null; changed = true; } changed && fireChangeEvents.call(that, context || that); return undefined; } switch (name.toLowerCase()) { case 'ahex': case 'hex': { var _ret = ColorMethods.hexToRgba(value && (value.ahex || value.hex) || value || 'none'); val.call(that, 'rgba', { r: _ret.r, g: _ret.g, b: _ret.b, a: name === 'ahex' ? _ret.a : !isNullish$2(a) ? a : 255 }, context); break; } default: { if (value && (!isNullish$2(value.ahex) || !isNullish$2(value.hex))) { val.call(that, 'ahex', value.ahex || value.hex || '00000000', context); return undefined; } var newV = {}; var rgb = false, hsv = false; if (value.r !== undefined && !name.includes('r')) name += 'r'; if (value.g !== undefined && !name.includes('g')) name += 'g'; if (value.b !== undefined && !name.includes('b')) name += 'b'; if (value.a !== undefined && !name.includes('a')) name += 'a'; if (value.h !== undefined && !name.includes('h')) name += 'h'; if (value.s !== undefined && !name.includes('s')) name += 's'; if (value.v !== undefined && !name.includes('v')) name += 'v'; _toConsumableArray(name).forEach(function (ch) { switch (ch) { case 'r': if (hsv) return; rgb = true; newV.r = value.r && value.r | 0 || value | 0 || 0; if (newV.r < 0) newV.r = 0;else if (newV.r > 255) newV.r = 255; if (r !== newV.r) { r = newV.r; changed = true; } break; case 'g': if (hsv) return; rgb = true; newV.g = value && value.g && value.g | 0 || value && value | 0 || 0; if (newV.g < 0) newV.g = 0;else if (newV.g > 255) newV.g = 255; if (g !== newV.g) { g = newV.g; changed = true; } break; case 'b': if (hsv) return; rgb = true; newV.b = value && value.b && value.b | 0 || value && value | 0 || 0; if (newV.b < 0) newV.b = 0;else if (newV.b > 255) newV.b = 255; if (b !== newV.b) { b = newV.b; changed = true; } break; case 'a': newV.a = value && !isNullish$2(value.a) ? value.a | 0 : value | 0; if (newV.a < 0) newV.a = 0;else if (newV.a > 255) newV.a = 255; if (a !== newV.a) { a = newV.a; changed = true; } break; case 'h': if (rgb) return; hsv = true; newV.h = value && value.h && value.h | 0 || value && value | 0 || 0; if (newV.h < 0) newV.h = 0;else if (newV.h > 360) newV.h = 360; if (h !== newV.h) { h = newV.h; changed = true; } break; case 's': if (rgb) return; hsv = true; newV.s = !isNullish$2(value.s) ? value.s | 0 : value | 0; if (newV.s < 0) newV.s = 0;else if (newV.s > 100) newV.s = 100; if (s !== newV.s) { s = newV.s; changed = true; } break; case 'v': if (rgb) return; hsv = true; newV.v = !isNullish$2(value.v) ? value.v | 0 : value | 0; if (newV.v < 0) newV.v = 0;else if (newV.v > 100) newV.v = 100; if (v !== newV.v) { v = newV.v; changed = true; } break; } }); if (changed) { if (rgb) { r = r || 0; g = g || 0; b = b || 0; var _ret2 = ColorMethods.rgbToHsv({ r: r, g: g, b: b }); h = _ret2.h; s = _ret2.s; v = _ret2.v; } else if (hsv) { h = h || 0; s = !isNullish$2(s) ? s : 100; v = !isNullish$2(v) ? v : 100; var _ret3 = ColorMethods.hsvToRgb({ h: h, s: s, v: v }); r = _ret3.r; g = _ret3.g; b = _ret3.b; } a = !isNullish$2(a) ? a : 255; fireChangeEvents.call(that, context || that); } break; } } return undefined; } /** * @param {GenericCallback} callback * @returns {void} */ function bind(callback) { // eslint-disable-line promise/prefer-await-to-callbacks if (typeof callback === 'function') changeEvents.push(callback); } /** * @param {GenericCallback} callback * @returns {void} */ function unbind(callback) { // eslint-disable-line promise/prefer-await-to-callbacks if (typeof callback !== 'function') return; var i; while (i = changeEvents.includes(callback)) { changeEvents.splice(i, 1); } } /** * Unset `changeEvents` * @returns {void} */ function destroy() { changeEvents = null; } var r, g, b, a, h, s, v, changeEvents = []; $.extend(true, that, { // public properties and methods val: val, bind: bind, unbind: unbind, destroy: destroy }); if (init) { if (!isNullish$2(init.ahex)) { val('ahex', init); } else if (!isNullish$2(init.hex)) { val((!isNullish$2(init.a) ? 'a' : '') + 'hex', !isNullish$2(init.a) ? { ahex: init.hex + ColorMethods.intToHex(init.a) } : init); } else if (!isNullish$2(init.r) && !isNullish$2(init.g) && !isNullish$2(init.b)) { val('rgb' + (!isNullish$2(init.a) ? 'a' : ''), init); } else if (!isNullish$2(init.h) && !isNullish$2(init.s) && !isNullish$2(init.v)) { val('hsv' + (!isNullish$2(init.a) ? 'a' : ''), init); } } }, /** * Color conversion methods - make public to give use to external scripts. * @namespace */ ColorMethods: { /** * @typedef {PlainObject} module:jPicker.RGBA * @property {Integer} r * @property {Integer} g * @property {Integer} b * @property {Integer} a */ /** * @typedef {PlainObject} module:jPicker.RGB * @property {Integer} r * @property {Integer} g * @property {Integer} b */ /** * @param {string} hex * @returns {module:jPicker.RGBA} */ hexToRgba: function hexToRgba(hex) { if (hex === '' || hex === 'none') return { r: null, g: null, b: null, a: null }; hex = this.validateHex(hex); var r = '00', g = '00', b = '00', a = '255'; if (hex.length === 6) hex += 'ff'; if (hex.length > 6) { r = hex.substring(0, 2); g = hex.substring(2, 4); b = hex.substring(4, 6); a = hex.substring(6, hex.length); } else { if (hex.length > 4) { r = hex.substring(4, hex.length); hex = hex.substring(0, 4); } if (hex.length > 2) { g = hex.substring(2, hex.length); hex = hex.substring(0, 2); } if (hex.length > 0) b = hex.substring(0, hex.length); } return { r: this.hexToInt(r), g: this.hexToInt(g), b: this.hexToInt(b), a: this.hexToInt(a) }; }, /** * @param {string} hex * @returns {string} */ validateHex: function validateHex(hex) { // if (typeof hex === 'object') return ''; hex = hex.toLowerCase().replace(/[^a-f\d]/g, ''); if (hex.length > 8) hex = hex.substring(0, 8); return hex; }, /** * @param {module:jPicker.RGBA} rgba * @returns {string} */ rgbaToHex: function rgbaToHex(rgba) { return this.intToHex(rgba.r) + this.intToHex(rgba.g) + this.intToHex(rgba.b) + this.intToHex(rgba.a); }, /** * @param {Integer} dec * @returns {string} */ intToHex: function intToHex(dec) { var result = (dec | 0).toString(16); if (result.length === 1) result = '0' + result; return result.toLowerCase(); }, /** * @param {string} hex * @returns {Integer} */ hexToInt: function hexToInt(hex) { return Number.parseInt(hex, 16); }, /** * @typedef {PlainObject} module:jPicker.HSV * @property {Integer} h * @property {Integer} s * @property {Integer} v */ /** * @param {module:jPicker.RGB} rgb * @returns {module:jPicker.HSV} */ rgbToHsv: function rgbToHsv(rgb) { var r = rgb.r / 255, g = rgb.g / 255, b = rgb.b / 255, hsv = { h: 0, s: 0, v: 0 }; var min = 0, max = 0; if (r >= g && r >= b) { max = r; min = g > b ? b : g; } else if (g >= b && g >= r) { max = g; min = r > b ? b : r; } else { max = b; min = g > r ? r : g; } hsv.v = max; hsv.s = max ? (max - min) / max : 0; var delta; if (!hsv.s) hsv.h = 0;else { delta = max - min; if (r === max) hsv.h = (g - b) / delta;else if (g === max) hsv.h = 2 + (b - r) / delta;else hsv.h = 4 + (r - g) / delta; hsv.h = Number.parseInt(hsv.h * 60); if (hsv.h < 0) hsv.h += 360; } hsv.s = hsv.s * 100 | 0; hsv.v = hsv.v * 100 | 0; return hsv; }, /** * @param {module:jPicker.HSV} hsv * @returns {module:jPicker.RGB} */ hsvToRgb: function hsvToRgb(hsv) { var rgb = { r: 0, g: 0, b: 0, a: 100 }; var h = hsv.h, s = hsv.s, v = hsv.v; if (s === 0) { if (v === 0) rgb.r = rgb.g = rgb.b = 0;else rgb.r = rgb.g = rgb.b = v * 255 / 100 | 0; } else { if (h === 360) h = 0; h /= 60; s /= 100; v /= 100; var i = h | 0, f = h - i, p = v * (1 - s), q = v * (1 - s * f), t = v * (1 - s * (1 - f)); switch (i) { case 0: rgb.r = v; rgb.g = t; rgb.b = p; break; case 1: rgb.r = q; rgb.g = v; rgb.b = p; break; case 2: rgb.r = p; rgb.g = v; rgb.b = t; break; case 3: rgb.r = p; rgb.g = q; rgb.b = v; break; case 4: rgb.r = t; rgb.g = p; rgb.b = v; break; case 5: rgb.r = v; rgb.g = p; rgb.b = q; break; } rgb.r = rgb.r * 255 | 0; rgb.g = rgb.g * 255 | 0; rgb.b = rgb.b * 255 | 0; } return rgb; } } }; var _$$jPicker = $.jPicker, Color = _$$jPicker.Color, List = _$$jPicker.List, ColorMethods = _$$jPicker.ColorMethods; // local copies for YUI compressor /* eslint-disable jsdoc/require-returns */ /** * @function external:jQuery.fn.jPicker * @see {@link external:jQuery.fn.$.fn.jPicker} */ /* eslint-enable jsdoc/require-returns */ /** * Will be bound to active {@link jQuery.jPicker.Color}. * @callback module:jPicker.LiveCallback * @param {external:jQuery} ui * @param {Element} context * @returns {void} */ /** * @callback module:jPicker.CommitCallback * @param {external:jQuery.jPicker.Color} activeColor * @param {external:jQuery} okButton * @returns {void} Return value not used. */ /** * @callback module:jPicker.CancelCallback * @param {external:jQuery.jPicker.Color} activeColor * @param {external:jQuery} cancelButton * @returns {void} Return value not used. */ /** * While it would seem this should specify the name `jPicker` for JSDoc, that doesn't * get us treated as a function as well as a namespace (even with `@function name`), * so we use an approach to add a redundant `$.fn.` in the name. * @namespace * @memberof external:jQuery.fn * @param {external:jQuery.fn.jPickerOptions} options * @param {module:jPicker.CommitCallback} [commitCallback] * @param {module:jPicker.LiveCallback} [liveCallback] * @param {module:jPicker.CancelCallback} [cancelCallback] * @returns {external:jQuery} */ $.fn.jPicker = function (options, commitCallback, liveCallback, cancelCallback) { return this.each(function () { var that = this, settings = $.extend(true, {}, $.fn.jPicker.defaults, options); // local copies for YUI compressor if ($(that).get(0).nodeName.toLowerCase() === 'input') { // Add color picker icon if binding to an input element and bind the events to the input $.extend(true, settings, { window: { bindToInput: true, expandable: true, input: $(that) } }); if ($(that).val() === '') { settings.color.active = new Color({ hex: null }); settings.color.current = new Color({ hex: null }); } else if (ColorMethods.validateHex($(that).val())) { settings.color.active = new Color({ hex: $(that).val(), a: settings.color.active.val('a') }); settings.color.current = new Color({ hex: $(that).val(), a: settings.color.active.val('a') }); } } if (settings.window.expandable) { $(that).after('<span class="jPicker"><span class="Icon"><span class="Color"> </span><span class="Alpha"> </span><span class="Image" title="Click To Open Color Picker"> </span><span class="Container"> </span></span></span>'); } else { settings.window.liveUpdate = false; // Basic control binding for inline use - You will need to override the liveCallback or commitCallback function to retrieve results } var isLessThanIE7 = Number.parseFloat(navigator.appVersion.split('MSIE')[1]) < 7 && document.body.filters; // needed to run the AlphaImageLoader function for IE6 // set color mode and update visuals for the new color mode /** * * @param {"h"|"s"|"v"|"r"|"g"|"b"|"a"} colorMode * @throws {Error} Invalid mode * @returns {void} */ function setColorMode(colorMode) { var active = color.active, hex = active.val('hex'); var rgbMap, rgbBar; settings.color.mode = colorMode; switch (colorMode) { case 'h': setTimeout(function () { setBG.call(that, colorMapDiv, 'transparent'); setImgLoc.call(that, colorMapL1, 0); setAlpha.call(that, colorMapL1, 100); setImgLoc.call(that, colorMapL2, 260); setAlpha.call(that, colorMapL2, 100); setBG.call(that, colorBarDiv, 'transparent'); setImgLoc.call(that, colorBarL1, 0); setAlpha.call(that, colorBarL1, 100); setImgLoc.call(that, colorBarL2, 260); setAlpha.call(that, colorBarL2, 100); setImgLoc.call(that, colorBarL3, 260); setAlpha.call(that, colorBarL3, 100); setImgLoc.call(that, colorBarL4, 260); setAlpha.call(that, colorBarL4, 100); setImgLoc.call(that, colorBarL6, 260); setAlpha.call(that, colorBarL6, 100); }, 0); colorMap.range('all', { minX: 0, maxX: 100, minY: 0, maxY: 100 }); colorBar.range('rangeY', { minY: 0, maxY: 360 }); if (isNullish$2(active.val('ahex'))) break; colorMap.val('xy', { x: active.val('s'), y: 100 - active.val('v') }, colorMap); colorBar.val('y', 360 - active.val('h'), colorBar); break; case 's': setTimeout(function () { setBG.call(that, colorMapDiv, 'transparent'); setImgLoc.call(that, colorMapL1, -260); setImgLoc.call(that, colorMapL2, -520); setImgLoc.call(that, colorBarL1, -260); setImgLoc.call(that, colorBarL2, -520); setImgLoc.call(that, colorBarL6, 260); setAlpha.call(that, colorBarL6, 100); }, 0); colorMap.range('all', { minX: 0, maxX: 360, minY: 0, maxY: 100 }); colorBar.range('rangeY', { minY: 0, maxY: 100 }); if (isNullish$2(active.val('ahex'))) break; colorMap.val('xy', { x: active.val('h'), y: 100 - active.val('v') }, colorMap); colorBar.val('y', 100 - active.val('s'), colorBar); break; case 'v': setTimeout(function () { setBG.call(that, colorMapDiv, '000000'); setImgLoc.call(that, colorMapL1, -780); setImgLoc.call(that, colorMapL2, 260); setBG.call(that, colorBarDiv, hex); setImgLoc.call(that, colorBarL1, -520); setImgLoc.call(that, colorBarL2, 260); setAlpha.call(that, colorBarL2, 100); setImgLoc.call(that, colorBarL6, 260); setAlpha.call(that, colorBarL6, 100); }, 0); colorMap.range('all', { minX: 0, maxX: 360, minY: 0, maxY: 100 }); colorBar.range('rangeY', { minY: 0, maxY: 100 }); if (isNullish$2(active.val('ahex'))) break; colorMap.val('xy', { x: active.val('h'), y: 100 - active.val('s') }, colorMap); colorBar.val('y', 100 - active.val('v'), colorBar); break; case 'r': rgbMap = -1040; rgbBar = -780; colorMap.range('all', { minX: 0, maxX: 255, minY: 0, maxY: 255 }); colorBar.range('rangeY', { minY: 0, maxY: 255 }); if (isNullish$2(active.val('ahex'))) break; colorMap.val('xy', { x: active.val('b'), y: 255 - active.val('g') }, colorMap); colorBar.val('y', 255 - active.val('r'), colorBar); break; case 'g': rgbMap = -1560; rgbBar = -1820; colorMap.range('all', { minX: 0, maxX: 255, minY: 0, maxY: 255 }); colorBar.range('rangeY', { minY: 0, maxY: 255 }); if (isNullish$2(active.val('ahex'))) break; colorMap.val('xy', { x: active.val('b'), y: 255 - active.val('r') }, colorMap); colorBar.val('y', 255 - active.val('g'), colorBar); break; case 'b': rgbMap = -2080; rgbBar = -2860; colorMap.range('all', { minX: 0, maxX: 255, minY: 0, maxY: 255 }); colorBar.range('rangeY', { minY: 0, maxY: 255 }); if (isNullish$2(active.val('ahex'))) break; colorMap.val('xy', { x: active.val('r'), y: 255 - active.val('g') }, colorMap); colorBar.val('y', 255 - active.val('b'), colorBar); break; case 'a': setTimeout(function () { setBG.call(that, colorMapDiv, 'transparent'); setImgLoc.call(that, colorMapL1, -260); setImgLoc.call(that, colorMapL2, -520); setImgLoc.call(that, colorBarL1, 260); setImgLoc.call(that, colorBarL2, 260); setAlpha.call(that, colorBarL2, 100); setImgLoc.call(that, colorBarL6, 0); setAlpha.call(that, colorBarL6, 100); }, 0); colorMap.range('all', { minX: 0, maxX: 360, minY: 0, maxY: 100 }); colorBar.range('rangeY', { minY: 0, maxY: 255 }); if (isNullish$2(active.val('ahex'))) break; colorMap.val('xy', { x: active.val('h'), y: 100 - active.val('v') }, colorMap); colorBar.val('y', 255 - active.val('a'), colorBar); break; default: throw new Error('Invalid Mode'); } switch (colorMode) { case 'h': break; case 's': case 'v': case 'a': setTimeout(function () { setAlpha.call(that, colorMapL1, 100); setAlpha.call(that, colorBarL1, 100); setImgLoc.call(that, colorBarL3, 260); setAlpha.call(that, colorBarL3, 100); setImgLoc.call(that, colorBarL4, 260); setAlpha.call(that, colorBarL4, 100); }, 0); break; case 'r': case 'g': case 'b': setTimeout(function () { setBG.call(that, colorMapDiv, 'transparent'); setBG.call(that, colorBarDiv, 'transparent'); setAlpha.call(that, colorBarL1, 100); setAlpha.call(that, colorMapL1, 100); setImgLoc.call(that, colorMapL1, rgbMap); setImgLoc.call(that, colorMapL2, rgbMap - 260); setImgLoc.call(that, colorBarL1, rgbBar - 780); setImgLoc.call(that, colorBarL2, rgbBar - 520); setImgLoc.call(that, colorBarL3, rgbBar); setImgLoc.call(that, colorBarL4, rgbBar - 260); setImgLoc.call(that, colorBarL6, 260); setAlpha.call(that, colorBarL6, 100); }, 0); break; } if (isNullish$2(active.val('ahex'))) return; activeColorChanged.call(that, active); } /** * Update color when user changes text values. * @param {external:jQuery} ui * @param {?module:jPicker.Slider} context * @returns {void} */ function activeColorChanged(ui, context) { if (isNullish$2(context) || context !== colorBar && context !== colorMap) positionMapAndBarArrows.call(that, ui, context); setTimeout(function () { updatePreview.call(that, ui); updateMapVisuals.call(that, ui); updateBarVisuals.call(that, ui); }, 0); } /** * User has dragged the ColorMap pointer. * @param {external:jQuery} ui * @param {?module:jPicker.Slider} context * @returns {void} */ function mapValueChanged(ui, context) { var active = color.active; if (context !== colorMap && isNullish$2(active.val())) return; var xy = ui.val('all'); switch (settings.color.mode) { case 'h': active.val('sv', { s: xy.x, v: 100 - xy.y }, context); break; case 's': case 'a': active.val('hv', { h: xy.x, v: 100 - xy.y }, context); break; case 'v': active.val('hs', { h: xy.x, s: 100 - xy.y }, context); break; case 'r': active.val('gb', { g: 255 - xy.y, b: xy.x }, context); break; case 'g': active.val('rb', { r: 255 - xy.y, b: xy.x }, context); break; case 'b': active.val('rg', { r: xy.x, g: 255 - xy.y }, context); break; } } /** * User has dragged the ColorBar slider. * @param {external:jQuery} ui * @param {?module:jPicker.Slider} context * @returns {void} */ function colorBarValueChanged(ui, context) { var active = color.active; if (context !== colorBar && isNullish$2(active.val())) return; switch (settings.color.mode) { case 'h': active.val('h', { h: 360 - ui.val('y') }, context); break; case 's': active.val('s', { s: 100 - ui.val('y') }, context); break; case 'v': active.val('v', { v: 100 - ui.val('y') }, context); break; case 'r': active.val('r', { r: 255 - ui.val('y') }, context); break; case 'g': active.val('g', { g: 255 - ui.val('y') }, context); break; case 'b': active.val('b', { b: 255 - ui.val('y') }, context); break; case 'a': active.val('a', 255 - ui.val('y'), context); break; } } /** * Position map and bar arrows to match current color. * @param {external:jQuery} ui * @param {?module:jPicker.Slider} context * @returns {void} */ function positionMapAndBarArrows(ui, context) { if (context !== colorMap) { switch (settings.color.mode) { case 'h': { var sv = ui.val('sv'); colorMap.val('xy', { x: !isNullish$2(sv) ? sv.s : 100, y: 100 - (!isNullish$2(sv) ? sv.v : 100) }, context); break; } case 's': // Fall through case 'a': { var hv = ui.val('hv'); colorMap.val('xy', { x: hv && hv.h || 0, y: 100 - (!isNullish$2(hv) ? hv.v : 100) }, context); break; } case 'v': { var hs = ui.val('hs'); colorMap.val('xy', { x: hs && hs.h || 0, y: 100 - (!isNullish$2(hs) ? hs.s : 100) }, context); break; } case 'r': { var bg = ui.val('bg'); colorMap.val('xy', { x: bg && bg.b || 0, y: 255 - (bg && bg.g || 0) }, context); break; } case 'g': { var br = ui.val('br'); colorMap.val('xy', { x: br && br.b || 0, y: 255 - (br && br.r || 0) }, context); break; } case 'b': { var rg = ui.val('rg'); colorMap.val('xy', { x: rg && rg.r || 0, y: 255 - (rg && rg.g || 0) }, context); break; } } } if (context !== colorBar) { switch (settings.color.mode) { case 'h': colorBar.val('y', 360 - (ui.val('h') || 0), context); break; case 's': { var s = ui.val('s'); colorBar.val('y', 100 - (!isNullish$2(s) ? s : 100), context); break; } case 'v': { var v = ui.val('v'); colorBar.val('y', 100 - (!isNullish$2(v) ? v : 100), context); break; } case 'r': colorBar.val('y', 255 - (ui.val('r') || 0), context); break; case 'g': colorBar.val('y', 255 - (ui.val('g') || 0), context); break; case 'b': colorBar.val('y', 255 - (ui.val('b') || 0), context); break; case 'a': { var a = ui.val('a'); colorBar.val('y', 255 - (!isNullish$2(a) ? a : 255), context); break; } } } } /** * @param {external:jQuery} ui * @returns {void} */ function updatePreview(ui) { try { var all = ui.val('all'); activePreview.css({ backgroundColor: all && '#' + all.hex || 'transparent' }); setAlpha.call(that, activePreview, all && toFixedNumeric(all.a * 100 / 255, 4) || 0); } catch (e) {} } /** * @param {external:jQuery} ui * @returns {void} */ function updateMapVisuals(ui) { switch (settings.color.mode) { case 'h': setBG.call(that, colorMapDiv, new Color({ h: ui.val('h') || 0, s: 100, v: 100 }).val('hex')); break; case 's': case 'a': { var s = ui.val('s'); setAlpha.call(that, colorMapL2, 100 - (!isNullish$2(s) ? s : 100)); break; } case 'v': { var v = ui.val('v'); setAlpha.call(that, colorMapL1, !isNullish$2(v) ? v : 100); break; } case 'r': setAlpha.call(that, colorMapL2, toFixedNumeric((ui.val('r') || 0) / 255 * 100, 4)); break; case 'g': setAlpha.call(that, colorMapL2, toFixedNumeric((ui.val('g') || 0) / 255 * 100, 4)); break; case 'b': setAlpha.call(that, colorMapL2, toFixedNumeric((ui.val('b') || 0) / 255 * 100)); break; } var a = ui.val('a'); setAlpha.call(that, colorMapL3, toFixedNumeric((255 - (a || 0)) * 100 / 255, 4)); } /** * @param {external:jQuery} ui * @returns {void} */ function updateBarVisuals(ui) { switch (settings.color.mode) { case 'h': { var a = ui.val('a'); setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (a || 0)) * 100 / 255, 4)); break; } case 's': { var hva = ui.val('hva'), saturatedColor = new Color({ h: hva && hva.h || 0, s: 100, v: !isNullish$2(hva) ? hva.v : 100 }); setBG.call(that, colorBarDiv, saturatedColor.val('hex')); setAlpha.call(that, colorBarL2, 100 - (!isNullish$2(hva) ? hva.v : 100)); setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (hva && hva.a || 0)) * 100 / 255, 4)); break; } case 'v': { var hsa = ui.val('hsa'), valueColor = new Color({ h: hsa && hsa.h || 0, s: !isNullish$2(hsa) ? hsa.s : 100, v: 100 }); setBG.call(that, colorBarDiv, valueColor.val('hex')); setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (hsa && hsa.a || 0)) * 100 / 255, 4)); break; } case 'r': case 'g': case 'b': { var rgba = ui.val('rgba'); var hValue = 0, vValue = 0; if (settings.color.mode === 'r') { hValue = rgba && rgba.b || 0; vValue = rgba && rgba.g || 0; } else if (settings.color.mode === 'g') { hValue = rgba && rgba.b || 0; vValue = rgba && rgba.r || 0; } else if (settings.color.mode === 'b') { hValue = rgba && rgba.r || 0; vValue = rgba && rgba.g || 0; } var middle = vValue > hValue ? hValue : vValue; setAlpha.call(that, colorBarL2, hValue > vValue ? toFixedNumeric((hValue - vValue) / (255 - vValue) * 100, 4) : 0); setAlpha.call(that, colorBarL3, vValue > hValue ? toFixedNumeric((vValue - hValue) / (255 - hValue) * 100, 4) : 0); setAlpha.call(that, colorBarL4, toFixedNumeric(middle / 255 * 100, 4)); setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (rgba && rgba.a || 0)) * 100 / 255, 4)); break; } case 'a': { var _a = ui.val('a'); setBG.call(that, colorBarDiv, ui.val('hex') || '000000'); setAlpha.call(that, colorBarL5, !isNullish$2(_a) ? 0 : 100); setAlpha.call(that, colorBarL6, !isNullish$2(_a) ? 100 : 0); break; } } } /** * @param {external:jQuery} el * @param {string} [c="transparent"] * @returns {void} */ function setBG(el, c) { el.css({ backgroundColor: c && c.length === 6 && '#' + c || 'transparent' }); } /** * @param {external:jQuery} img * @param {string} src The image source * @returns {void} */ function setImg(img, src) { if (isLessThanIE7 && (src.includes('AlphaBar.png') || src.includes('Bars.png') || src.includes('Maps.png'))) { img.attr('pngSrc', src); img.css({ backgroundImage: 'none', filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=\'scale\')' }); } else img.css({ backgroundImage: 'url(\'' + src + '\')' }); } /** * @param {external:jQuery} img * @param {Float} y * @returns {void} */ function setImgLoc(img, y) { img.css({ top: y + 'px' }); } /** * @param {external:jQuery} obj * @param {Float} alpha * @returns {void} */ function setAlpha(obj, alpha) { obj.css({ visibility: alpha > 0 ? 'visible' : 'hidden' }); if (alpha > 0 && alpha < 100) { if (isLessThanIE7) { var src = obj.attr('pngSrc'); if (!isNullish$2(src) && (src.includes('AlphaBar.png') || src.includes('Bars.png') || src.includes('Maps.png'))) { obj.css({ filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=\'scale\') progid:DXImageTransform.Microsoft.Alpha(opacity=' + alpha + ')' }); } else obj.css({ opacity: toFixedNumeric(alpha / 100, 4) }); } else obj.css({ opacity: toFixedNumeric(alpha / 100, 4) }); } else if (alpha === 0 || alpha === 100) { if (isLessThanIE7) { var _src = obj.attr('pngSrc'); if (!isNullish$2(_src) && (_src.includes('AlphaBar.png') || _src.includes('Bars.png') || _src.includes('Maps.png'))) { obj.css({ filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + _src + '\', sizingMethod=\'scale\')' }); } else obj.css({ opacity: '' }); } else obj.css({ opacity: '' }); } } /** * Revert color to original color when opened. * @returns {void} */ function revertColor() { color.active.val('ahex', color.current.val('ahex')); } /** * Commit the color changes. * @returns {void} */ function commitColor() { color.current.val('ahex', color.active.val('ahex')); } /** * @param {Event} e * @returns {void} */ function radioClicked(e) { $(this).parents('tbody:first').find('input:radio[value!="' + e.target.value + '"]').removeAttr('checked'); setColorMode.call(that, e.target.value); } /** * * @returns {void} */ function currentClicked() { revertColor.call(that); } /** * * @returns {void} */ function cancelClicked() { revertColor.call(that); settings.window.expandable && hide.call(that); typeof cancelCallback === 'function' && cancelCallback.call(that, color.active, cancelButton); } /** * * @returns {void} */ function okClicked() { commitColor.call(that); settings.window.expandable && hide.call(that); typeof commitCallback === 'function' && commitCallback.call(that, color.active, okButton); } /** * * @returns {void} */ function iconImageClicked() { show.call(that); } /** * @param {external:jQuery} ui * @returns {void} */ function currentColorChanged(ui) { var hex = ui.val('hex'); currentPreview.css({ backgroundColor: hex && '#' + hex || 'transparent' }); setAlpha.call(that, currentPreview, toFixedNumeric((ui.val('a') || 0) * 100 / 255, 4)); } /** * @param {external:jQuery} ui * @returns {void} */ function expandableColorChanged(ui) { var hex = ui.val('hex'); var va = ui.val('va'); iconColor.css({ backgroundColor: hex && '#' + hex || 'transparent' }); setAlpha.call(that, iconAlpha, toFixedNumeric((255 - (va && va.a || 0)) * 100 / 255, 4)); if (settings.window.bindToInput && settings.window.updateInputColor) { settings.window.input.css({ backgroundColor: hex && '#' + hex || 'transparent', color: isNullish$2(va) || va.v > 75 ? '#000000' : '#ffffff' }); } } /** * @param {Event} e * @returns {void} */ function moveBarMouseDown(e) { // const {element} = settings.window, // local copies for YUI compressor // {page} = settings.window; elementStartX = Number.parseInt(container.css('left')); elementStartY = Number.parseInt(container.css('top')); pageStartX = e.pageX; pageStartY = e.pageY; // bind events to document to move window - we will unbind these on mouseup $(document).bind('mousemove', documentMouseMove).bind('mouseup', documentMouseUp); e.preventDefault(); // prevent attempted dragging of the column } /** * @param {Event} e * @returns {false} */ function documentMouseMove(e) { container.css({ left: elementStartX - (pageStartX - e.pageX) + 'px', top: elementStartY - (pageStartY - e.pageY) + 'px' }); if (settings.window.expandable && !$.support.boxModel) { container.prev().css({ left: container.css('left'), top: container.css('top') }); } e.stopPropagation(); e.preventDefault(); return false; } /** * @param {Event} e * @returns {false} */ function documentMouseUp(e) { $(document).unbind('mousemove', documentMouseMove).unbind('mouseup', documentMouseUp); e.stopPropagation(); e.preventDefault(); return false; } /** * @param {Event} e * @returns {false} */ function quickPickClicked(e) { e.preventDefault(); e.stopPropagation(); color.active.val('ahex', $(this).attr('title') || null, e.target); return false; } /** * * @returns {void} */ function show() { color.current.val('ahex', color.active.val('ahex')); /** * * @returns {void} */ function attachIFrame() { if (!settings.window.expandable || $.support.boxModel) return; var table = container.find('table:first'); container.before('<iframe/>'); container.prev().css({ width: table.width(), height: container.height(), opacity: 0, position: 'absolute', left: container.css('left'), top: container.css('top') }); } if (settings.window.expandable) { $(document.body).children('div.jPicker.Container').css({ zIndex: 10 }); container.css({ zIndex: 20 }); } switch (settings.window.effects.type) { case 'fade': container.fadeIn(settings.window.effects.speed.show, attachIFrame); break; case 'slide': container.slideDown(settings.window.effects.speed.show, attachIFrame); break; case 'show': default: container.show(settings.window.effects.speed.show, attachIFrame); break; } } /** * * @returns {void} */ function hide() { /** * * @returns {void} */ function removeIFrame() { if (settings.window.expandable) container.css({ zIndex: 10 }); if (!settings.window.expandable || $.support.boxModel) return; container.prev().remove(); } switch (settings.window.effects.type) { case 'fade': container.fadeOut(settings.window.effects.speed.hide, removeIFrame); break; case 'slide': container.slideUp(settings.window.effects.speed.hide, removeIFrame); break; case 'show': default: container.hide(settings.window.effects.speed.hide, removeIFrame); break; } } /** * * @returns {void} */ function initialize() { var win = settings.window, popup = win.expandable ? $(that).next().find('.Container:first') : null; container = win.expandable ? $('<div/>') : $(that); container.addClass('jPicker Container'); if (win.expandable) container.hide(); container.get(0).onselectstart = function (e) { if (e.target.nodeName.toLowerCase() !== 'input') return false; return true; }; // inject html source code - we are using a single table for this control - I know tables are considered bad, but it takes care of equal height columns and // this control really is tabular data, so I believe it is the right move var all = color.active.val('all'); if (win.alphaPrecision < 0) win.alphaPrecision = 0;else if (win.alphaPrecision > 2) win.alphaPrecision = 2; var controlHtml = "<table class=\"jPicker\" cellpadding=\"0\" cellspacing=\"0\">\n <tbody>\n ".concat(win.expandable ? '<tr><td class="Move" colspan="5"> </td></tr>' : '', "\n <tr>\n <td rowspan=\"9\"><h2 class=\"Title\">").concat(win.title || localization.text.title, "</h2><div class=\"Map\"><span class=\"Map1\"> </span><span class=\"Map2\"> </span><span class=\"Map3\"> </span><img src=\"").concat(images.clientPath + images.colorMap.arrow.file, "\" class=\"Arrow\"/></div></td>\n <td rowspan=\"9\"><div class=\"Bar\"><span class=\"Map1\"> </span><span class=\"Map2\"> </span><span class=\"Map3\"> </span><span class=\"Map4\"> </span><span class=\"Map5\"> </span><span class=\"Map6\"> </span><img src=\"").concat(images.clientPath + images.colorBar.arrow.file, "\" class=\"Arrow\"/></div></td>\n <td colspan=\"2\" class=\"Preview\">").concat(localization.text.newColor, "<div><span class=\"Active\" title=\"").concat(localization.tooltips.colors.newColor, "\"> </span><span class=\"Current\" title=\"").concat(localization.tooltips.colors.currentColor, "\"> </span></div>").concat(localization.text.currentColor, "</td>\n <td rowspan=\"9\" class=\"Button\"><input type=\"button\" class=\"Ok\" value=\"").concat(localization.text.ok, "\" title=\"").concat(localization.tooltips.buttons.ok, "\"/><input type=\"button\" class=\"Cancel\" value=\"").concat(localization.text.cancel, "\" title=\"").concat(localization.tooltips.buttons.cancel, "\"/><hr/><div class=\"Grid\"> </div></td>\n </tr>\n <tr class=\"Hue\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.hue.radio, "\"><input type=\"radio\" value=\"h\"").concat(settings.color.mode === 'h' ? ' checked="checked"' : '', "/>H:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$2(all) ? all.h : '', "\" title=\"").concat(localization.tooltips.hue.textbox, "\"/> °</td>\n </tr>\n <tr class=\"Saturation\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.saturation.radio, "\"><input type=\"radio\" value=\"s\"").concat(settings.color.mode === 's' ? ' checked="checked"' : '', "/>S:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$2(all) ? all.s : '', "\" title=\"").concat(localization.tooltips.saturation.textbox, "\"/> %</td>\n </tr>\n <tr class=\"Value\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.value.radio, "\"><input type=\"radio\" value=\"v\"").concat(settings.color.mode === 'v' ? ' checked="checked"' : '', "/>V:</label><br/><br/></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$2(all) ? all.v : '', "\" title=\"").concat(localization.tooltips.value.textbox, "\"/> %<br/><br/></td>\n </tr>\n <tr class=\"Red\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.red.radio, "\"><input type=\"radio\" value=\"r\"").concat(settings.color.mode === 'r' ? ' checked="checked"' : '', "/>R:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$2(all) ? all.r : '', "\" title=\"").concat(localization.tooltips.red.textbox, "\"/></td>\n </tr>\n <tr class=\"Green\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.green.radio, "\"><input type=\"radio\" value=\"g\"").concat(settings.color.mode === 'g' ? ' checked="checked"' : '', "/>G:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$2(all) ? all.g : '', "\" title=\"").concat(localization.tooltips.green.textbox, "\"/></td>\n </tr>\n <tr class=\"Blue\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.blue.radio, "\"><input type=\"radio\" value=\"b\"").concat(settings.color.mode === 'b' ? ' checked="checked"' : '', "/>B:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$2(all) ? all.b : '', "\" title=\"").concat(localization.tooltips.blue.textbox, "\"/></td>\n </tr>\n <tr class=\"Alpha\">\n <td class=\"Radio\">").concat(win.alphaSupport ? "<label title=\"".concat(localization.tooltips.alpha.radio, "\"><input type=\"radio\" value=\"a\"").concat(settings.color.mode === 'a' ? ' checked="checked"' : '', "/>A:</label>") : ' ', "</td>\n <td class=\"Text\">").concat(win.alphaSupport ? "<input type=\"text\" maxlength=\"".concat(3 + win.alphaPrecision, "\" value=\"").concat(!isNullish$2(all) ? toFixedNumeric(all.a * 100 / 255, win.alphaPrecision) : '', "\" title=\"").concat(localization.tooltips.alpha.textbox, "\"/> %") : ' ', "</td>\n </tr>\n <tr class=\"Hex\">\n <td colspan=\"2\" class=\"Text\"><label title=\"").concat(localization.tooltips.hex.textbox, "\">#:<input type=\"text\" maxlength=\"6\" class=\"Hex\" value=\"").concat(!isNullish$2(all) ? all.hex : '', "\"/></label>").concat(win.alphaSupport ? "<input type=\"text\" maxlength=\"2\" class=\"AHex\" value=\"".concat(!isNullish$2(all) ? all.ahex.substring(6) : '', "\" title=\"").concat(localization.tooltips.hex.alpha, "\"/></td>") : ' ', "\n </tr>\n </tbody></table>"); if (win.expandable) { container.html(controlHtml); if (!$(document.body).children('div.jPicker.Container').length) { $(document.body).prepend(container); } else { $(document.body).children('div.jPicker.Container:last').after(container); } container.mousedown(function () { $(document.body).children('div.jPicker.Container').css({ zIndex: 10 }); container.css({ zIndex: 20 }); }); container.css( // positions must be set and display set to absolute before source code injection or IE will size the container to fit the window { left: win.position.x === 'left' ? popup.offset().left - 530 - (win.position.y === 'center' ? 25 : 0) + 'px' : win.position.x === 'center' ? popup.offset().left - 260 + 'px' : win.position.x === 'right' ? popup.offset().left - 10 + (win.position.y === 'center' ? 25 : 0) + 'px' : win.position.x === 'screenCenter' ? ($(document).width() >> 1) - 260 + 'px' : popup.offset().left + Number.parseInt(win.position.x) + 'px', position: 'absolute', top: win.position.y === 'top' ? popup.offset().top - 312 + 'px' : win.position.y === 'center' ? popup.offset().top - 156 + 'px' : win.position.y === 'bottom' ? popup.offset().top + 25 + 'px' : popup.offset().top + Number.parseInt(win.position.y) + 'px' }); } else { container = $(that); container.html(controlHtml); } // initialize the objects to the source code just injected var tbody = container.find('tbody:first'); colorMapDiv = tbody.find('div.Map:first'); colorBarDiv = tbody.find('div.Bar:first'); var MapMaps = colorMapDiv.find('span'); var BarMaps = colorBarDiv.find('span'); colorMapL1 = MapMaps.filter('.Map1:first'); colorMapL2 = MapMaps.filter('.Map2:first'); colorMapL3 = MapMaps.filter('.Map3:first'); colorBarL1 = BarMaps.filter('.Map1:first'); colorBarL2 = BarMaps.filter('.Map2:first'); colorBarL3 = BarMaps.filter('.Map3:first'); colorBarL4 = BarMaps.filter('.Map4:first'); colorBarL5 = BarMaps.filter('.Map5:first'); colorBarL6 = BarMaps.filter('.Map6:first'); // create color pickers and maps colorMap = new Slider(colorMapDiv, { map: { width: images.colorMap.width, height: images.colorMap.height }, arrow: { image: images.clientPath + images.colorMap.arrow.file, width: images.colorMap.arrow.width, height: images.colorMap.arrow.height } }); colorMap.bind(mapValueChanged); colorBar = new Slider(colorBarDiv, { map: { width: images.colorBar.width, height: images.colorBar.height }, arrow: { image: images.clientPath + images.colorBar.arrow.file, width: images.colorBar.arrow.width, height: images.colorBar.arrow.height } }); colorBar.bind(colorBarValueChanged); colorPicker = new ColorValuePicker(tbody, color.active, win.expandable && win.bindToInput ? win.input : null, win.alphaPrecision); var hex = !isNullish$2(all) ? all.hex : null, preview = tbody.find('.Preview'), button = tbody.find('.Button'); activePreview = preview.find('.Active:first').css({ backgroundColor: hex && '#' + hex || 'transparent' }); currentPreview = preview.find('.Current:first').css({ backgroundColor: hex && '#' + hex || 'transparent' }).bind('click', currentClicked); setAlpha.call(that, currentPreview, toFixedNumeric(color.current.val('a') * 100 / 255, 4)); okButton = button.find('.Ok:first').bind('click', okClicked); cancelButton = button.find('.Cancel:first').bind('click', cancelClicked); grid = button.find('.Grid:first'); setTimeout(function () { setImg.call(that, colorMapL1, images.clientPath + 'Maps.png'); setImg.call(that, colorMapL2, images.clientPath + 'Maps.png'); setImg.call(that, colorMapL3, images.clientPath + 'map-opacity.png'); setImg.call(that, colorBarL1, images.clientPath + 'Bars.png'); setImg.call(that, colorBarL2, images.clientPath + 'Bars.png'); setImg.call(that, colorBarL3, images.clientPath + 'Bars.png'); setImg.call(that, colorBarL4, images.clientPath + 'Bars.png'); setImg.call(that, colorBarL5, images.clientPath + 'bar-opacity.png'); setImg.call(that, colorBarL6, images.clientPath + 'AlphaBar.png'); setImg.call(that, preview.find('div:first'), images.clientPath + 'preview-opacity.png'); }, 0); tbody.find('td.Radio input').bind('click', radioClicked); // initialize quick list if (color.quickList && color.quickList.length > 0) { var html = ''; for (var i = 0; i < color.quickList.length; i++) { /* if default colors are hex strings, change them to color objects */ if (_typeof(color.quickList[i]).toString().toLowerCase() === 'string') { color.quickList[i] = new Color({ hex: color.quickList[i] }); } var _alpha = color.quickList[i].val('a'); var _ahex = color.quickList[i].val('ahex'); if (!win.alphaSupport && _ahex) _ahex = _ahex.substring(0, 6) + 'ff'; var quickHex = color.quickList[i].val('hex'); if (!_ahex) _ahex = '00000000'; html += '<span class="QuickColor"' + (' title="#' + _ahex + '"') + ' style="background-color:' + (quickHex && '#' + quickHex || '') + ';' + (quickHex ? '' : 'background-image:url(' + images.clientPath + 'NoColor.png)') + (win.alphaSupport && _alpha && _alpha < 255 ? ';opacity:' + toFixedNumeric(_alpha / 255, 4) + ';filter:Alpha(opacity=' + toFixedNumeric(_alpha / 2.55, 4) + ')' : '') + '"> </span>'; } setImg.call(that, grid, images.clientPath + 'bar-opacity.png'); grid.html(html); grid.find('.QuickColor').click(quickPickClicked); } setColorMode.call(that, settings.color.mode); color.active.bind(activeColorChanged); typeof liveCallback === 'function' && color.active.bind(liveCallback); color.current.bind(currentColorChanged); // bind to input if (win.expandable) { that.icon = popup.parents('.Icon:first'); iconColor = that.icon.find('.Color:first').css({ backgroundColor: hex && '#' + hex || 'transparent' }); iconAlpha = that.icon.find('.Alpha:first'); setImg.call(that, iconAlpha, images.clientPath + 'bar-opacity.png'); setAlpha.call(that, iconAlpha, toFixedNumeric((255 - (!isNullish$2(all) ? all.a : 0)) * 100 / 255, 4)); iconImage = that.icon.find('.Image:first').css({ backgroundImage: 'url(\'' + images.clientPath + images.picker.file + '\')' }).bind('click', iconImageClicked); if (win.bindToInput && win.updateInputColor) { win.input.css({ backgroundColor: hex && '#' + hex || 'transparent', color: isNullish$2(all) || all.v > 75 ? '#000000' : '#ffffff' }); } moveBar = tbody.find('.Move:first').bind('mousedown', moveBarMouseDown); color.active.bind(expandableColorChanged); } else show.call(that); } /** * * @returns {void} */ function destroy() { container.find('td.Radio input').unbind('click', radioClicked); currentPreview.unbind('click', currentClicked); cancelButton.unbind('click', cancelClicked); okButton.unbind('click', okClicked); if (settings.window.expandable) { iconImage.unbind('click', iconImageClicked); moveBar.unbind('mousedown', moveBarMouseDown); that.icon = null; } container.find('.QuickColor').unbind('click', quickPickClicked); colorMapDiv = null; colorBarDiv = null; colorMapL1 = null; colorMapL2 = null; colorMapL3 = null; colorBarL1 = null; colorBarL2 = null; colorBarL3 = null; colorBarL4 = null; colorBarL5 = null; colorBarL6 = null; colorMap.destroy(); colorMap = null; colorBar.destroy(); colorBar = null; colorPicker.destroy(); colorPicker = null; activePreview = null; currentPreview = null; okButton = null; cancelButton = null; grid = null; commitCallback = null; cancelCallback = null; liveCallback = null; container.html(''); for (var i = 0; i < List.length; i++) { if (List[i] === that) { List.splice(i, 1); i--; // Decrement to ensure we don't miss next item (lgtm warning) } } } var images = settings.images, localization = settings.localization; // local copies for YUI compressor var color = { active: _typeof(settings.color.active).toString().toLowerCase() === 'string' ? new Color({ ahex: !settings.window.alphaSupport && settings.color.active ? settings.color.active.substring(0, 6) + 'ff' : settings.color.active }) : new Color({ ahex: !settings.window.alphaSupport && settings.color.active.val('ahex') ? settings.color.active.val('ahex').substring(0, 6) + 'ff' : settings.color.active.val('ahex') }), current: _typeof(settings.color.active).toString().toLowerCase() === 'string' ? new Color({ ahex: !settings.window.alphaSupport && settings.color.active ? settings.color.active.substring(0, 6) + 'ff' : settings.color.active }) : new Color({ ahex: !settings.window.alphaSupport && settings.color.active.val('ahex') ? settings.color.active.val('ahex').substring(0, 6) + 'ff' : settings.color.active.val('ahex') }), quickList: settings.color.quickList }; if (typeof commitCallback !== 'function') { commitCallback = null; } if (typeof liveCallback !== 'function') { liveCallback = null; } if (typeof cancelCallback !== 'function') { cancelCallback = null; } var elementStartX = null, // Used to record the starting css positions for dragging the control elementStartY = null, pageStartX = null, // Used to record the mousedown coordinates for dragging the control pageStartY = null, container = null, colorMapDiv = null, colorBarDiv = null, colorMapL1 = null, // different layers of colorMap and colorBar colorMapL2 = null, colorMapL3 = null, colorBarL1 = null, colorBarL2 = null, colorBarL3 = null, colorBarL4 = null, colorBarL5 = null, colorBarL6 = null, colorMap = null, // color maps colorBar = null, colorPicker = null, activePreview = null, // color boxes above the radio buttons currentPreview = null, okButton = null, cancelButton = null, grid = null, // preset colors grid iconColor = null, // iconColor for popup icon iconAlpha = null, // iconAlpha for popup icon iconImage = null, // iconImage popup icon moveBar = null; // drag bar $.extend(true, that, { // public properties, methods, and callbacks commitCallback: commitCallback, // commitCallback function can be overridden to return the selected color to a method you specify when the user clicks "OK" liveCallback: liveCallback, // liveCallback function can be overridden to return the selected color to a method you specify in live mode (continuous update) cancelCallback: cancelCallback, // cancelCallback function can be overridden to a method you specify when the user clicks "Cancel" color: color, show: show, hide: hide, destroy: destroy // destroys this control entirely, removing all events and objects, and removing itself from the List }); List.push(that); setTimeout(function () { initialize.call(that); }, 0); }); }; /** * @typedef {PlainObject} external:jQuery.fn.jPickerOptionsIconInfo * @property {string} file Color Map/Color Bar/Color Picker arrow icon * @property {Float} width * @property {Float} height */ /** * @typedef {PlainObject} external:jQuery.fn.jPickerOptionsImagesDimensionsArrow * @property {Float} width * @property {Float} height * @property {external:jQuery.fn.jPickerOptionsIconInfo} arrow */ /** * @typedef {PlainObject} external:jQuery.fn.jPickerOptionsRadioTextboxLocale * @property {string} radio * @property {string} textbox */ /** * @typedef {PlainObject} external:jQuery.fn.jPickerOptions * @property {PlainObject} window * @property {string|null} window.title Any title for the jPicker window itself - displays * "Drag Markers To Pick A Color" if left null * @property {PlainObject} window.effects * @property {"slide"|"show"|"fade"} window.effects.type Effect used to show/hide an expandable picker * @property {PlainObject} window.effects.speed * @property {"fast"|"slow"|Float} window.effects.speed.show Duration of "show" effect. Time in milliseconds. * @property {"fast"|"slow"|Float} window.effects.speed.hide Duration of "hide" effect. Time in milliseconds * @property {PlainObject} window.position * @property {"left"|"center"|"right"|"screenCenter"|Float} window.position.x Relative px value * @property {"top"|"bottom"|"center"|Float} window.position.y Relative px value * @property {boolean} window.expandable Defaults to large static picker - set to `true` to make an expandable * picker (small icon with popup) - set automatically when binded to input element; added by `$.fn.jPicker` * @property {boolean} window.liveUpdate Set `false` if you want the user to have to click "OK" before the * binded input box updates values (always `true` for expandable picker) * @property {boolean} window.alphaSupport Set to `true` to enable alpha picking * @property {Float} window.alphaPrecision Set decimal precision for alpha percentage display - hex codes do * not map directly to percentage integers - range 0-2 * @property {boolean} window.updateInputColor Set to `false` to prevent binded input colors from changing * @property {boolean} [window.bindToInput] Added by `$.fn.jPicker` * @property {external:jQuery} [window.input] Added by `$.fn.jPicker` * @property {PlainObject} color * @property {"h"|"s"|"v"|"r"|"g"|"b"|"a"} color.mode Symbols stand for "h" (hue), "s" (saturation), "v" (value), "r" (red), "g" (green), "b" (blue), "a" (alpha) * @property {Color|string} color.active Strings are HEX values (e.g. #ffc000) WITH OR WITHOUT the "#" prefix * @property {Color[]|string[]} color.quickList The quick pick color list * Strings are HEX values (e.g. #ffc000) WITH OR WITHOUT the "#" prefix * @property {PlainObject} images * @property {string} images.clientPath Path to image files * @property {external:jQuery.fn.jPickerOptionsImagesDimensionsArrow} images.colorMap * @property {external:jQuery.fn.jPickerOptionsImagesDimensionsArrow} images.colorBar * @property {external:jQuery.fn.jPickerOptionsIconInfo} images.picker * @property {PlainObject} localization alter these to change the text presented by the picker (e.g. different language) * @property {PlainObject} localization.text * @property {string} localization.text.title * @property {string} localization.text.newColor * @property {string} localization.text.currentColor * @property {string} localization.text.ok * @property {string} localization.text.cancel * @property {PlainObject} localization.tooltips * @property {PlainObject} localization.tooltips.colors * @property {string} localization.tooltips.colors.newColor * @property {string} localization.tooltips.colors.currentColor * @property {PlainObject} localization.tooltips.buttons * @property {string} localization.tooltips.buttons.ok * @property {string} localization.tooltips.buttons.cancel * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.hue * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.saturation * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.value * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.red * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.green * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.blue * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.alpha * @property {PlainObject} localization.tooltips.hex * @property {string} localization.tooltips.hex.textbox * @property {string} localization.tooltips.hex.alpha */ /** * The jPicker defaults - you can change anything in this section (such as the * clientPath to your images) without fear of breaking the program. * @namespace {external:jQuery.fn.jPickerOptions} defaults * @memberof external:jQuery.fn.$.fn.jPicker * @borrows external:jQuery.fn.jPickerOptions as external:jQuery.fn.jPicker.defaults * @see Source for all of the values */ $.fn.jPicker.defaults = { window: { title: null, effects: { type: 'slide', speed: { show: 'slow', hide: 'fast' } }, position: { x: 'screenCenter', y: 'top' }, expandable: false, liveUpdate: true, alphaSupport: false, alphaPrecision: 0, updateInputColor: true }, color: { mode: 'h', active: new Color({ ahex: '#ffcc00ff' }), quickList: [new Color({ h: 360, s: 33, v: 100 }), new Color({ h: 360, s: 66, v: 100 }), new Color({ h: 360, s: 100, v: 100 }), new Color({ h: 360, s: 100, v: 75 }), new Color({ h: 360, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 100 }), new Color({ h: 30, s: 33, v: 100 }), new Color({ h: 30, s: 66, v: 100 }), new Color({ h: 30, s: 100, v: 100 }), new Color({ h: 30, s: 100, v: 75 }), new Color({ h: 30, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 90 }), new Color({ h: 60, s: 33, v: 100 }), new Color({ h: 60, s: 66, v: 100 }), new Color({ h: 60, s: 100, v: 100 }), new Color({ h: 60, s: 100, v: 75 }), new Color({ h: 60, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 80 }), new Color({ h: 90, s: 33, v: 100 }), new Color({ h: 90, s: 66, v: 100 }), new Color({ h: 90, s: 100, v: 100 }), new Color({ h: 90, s: 100, v: 75 }), new Color({ h: 90, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 70 }), new Color({ h: 120, s: 33, v: 100 }), new Color({ h: 120, s: 66, v: 100 }), new Color({ h: 120, s: 100, v: 100 }), new Color({ h: 120, s: 100, v: 75 }), new Color({ h: 120, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 60 }), new Color({ h: 150, s: 33, v: 100 }), new Color({ h: 150, s: 66, v: 100 }), new Color({ h: 150, s: 100, v: 100 }), new Color({ h: 150, s: 100, v: 75 }), new Color({ h: 150, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 50 }), new Color({ h: 180, s: 33, v: 100 }), new Color({ h: 180, s: 66, v: 100 }), new Color({ h: 180, s: 100, v: 100 }), new Color({ h: 180, s: 100, v: 75 }), new Color({ h: 180, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 40 }), new Color({ h: 210, s: 33, v: 100 }), new Color({ h: 210, s: 66, v: 100 }), new Color({ h: 210, s: 100, v: 100 }), new Color({ h: 210, s: 100, v: 75 }), new Color({ h: 210, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 30 }), new Color({ h: 240, s: 33, v: 100 }), new Color({ h: 240, s: 66, v: 100 }), new Color({ h: 240, s: 100, v: 100 }), new Color({ h: 240, s: 100, v: 75 }), new Color({ h: 240, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 20 }), new Color({ h: 270, s: 33, v: 100 }), new Color({ h: 270, s: 66, v: 100 }), new Color({ h: 270, s: 100, v: 100 }), new Color({ h: 270, s: 100, v: 75 }), new Color({ h: 270, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 10 }), new Color({ h: 300, s: 33, v: 100 }), new Color({ h: 300, s: 66, v: 100 }), new Color({ h: 300, s: 100, v: 100 }), new Color({ h: 300, s: 100, v: 75 }), new Color({ h: 300, s: 100, v: 50 }), new Color({ h: 180, s: 0, v: 0 }), new Color({ h: 330, s: 33, v: 100 }), new Color({ h: 330, s: 66, v: 100 }), new Color({ h: 330, s: 100, v: 100 }), new Color({ h: 330, s: 100, v: 75 }), new Color({ h: 330, s: 100, v: 50 }), new Color()] }, images: { clientPath: '/jPicker/images/', colorMap: { width: 256, height: 256, arrow: { file: 'mappoint.gif', width: 15, height: 15 } }, colorBar: { width: 20, height: 256, arrow: { file: 'rangearrows.gif', width: 20, height: 7 } }, picker: { file: 'picker.gif', width: 25, height: 24 } }, localization: { text: { title: 'Drag Markers To Pick A Color', newColor: 'new', currentColor: 'current', ok: 'OK', cancel: 'Cancel' }, tooltips: { colors: { newColor: 'New Color - Press “OK” To Commit', currentColor: 'Click To Revert To Original Color' }, buttons: { ok: 'Commit To This Color Selection', cancel: 'Cancel And Revert To Original Color' }, hue: { radio: 'Set To “Hue” Color Mode', textbox: 'Enter A “Hue” Value (0-360°)' }, saturation: { radio: 'Set To “Saturation” Color Mode', textbox: 'Enter A “Saturation” Value (0-100%)' }, value: { radio: 'Set To “Value” Color Mode', textbox: 'Enter A “Value” Value (0-100%)' }, red: { radio: 'Set To “Red” Color Mode', textbox: 'Enter A “Red” Value (0-255)' }, green: { radio: 'Set To “Green” Color Mode', textbox: 'Enter A “Green” Value (0-255)' }, blue: { radio: 'Set To “Blue” Color Mode', textbox: 'Enter A “Blue” Value (0-255)' }, alpha: { radio: 'Set To “Alpha” Color Mode', textbox: 'Enter A “Alpha” Value (0-100)' }, hex: { textbox: 'Enter A “Hex” Color Value (#000000-#ffffff)', alpha: 'Enter A “Alpha” Value (#00-#ff)' } } } }; return $; }; function __variableDynamicImportRuntime0__(path) { switch (path) { case './locale/lang.af.js': return Promise.resolve().then(function () { return lang_af$1; }); case './locale/lang.ar.js': return Promise.resolve().then(function () { return lang_ar$1; }); case './locale/lang.az.js': return Promise.resolve().then(function () { return lang_az$1; }); case './locale/lang.be.js': return Promise.resolve().then(function () { return lang_be$1; }); case './locale/lang.bg.js': return Promise.resolve().then(function () { return lang_bg$1; }); case './locale/lang.ca.js': return Promise.resolve().then(function () { return lang_ca$1; }); case './locale/lang.cs.js': return Promise.resolve().then(function () { return lang_cs$1; }); case './locale/lang.cy.js': return Promise.resolve().then(function () { return lang_cy$1; }); case './locale/lang.da.js': return Promise.resolve().then(function () { return lang_da$1; }); case './locale/lang.de.js': return Promise.resolve().then(function () { return lang_de$1; }); case './locale/lang.el.js': return Promise.resolve().then(function () { return lang_el$1; }); case './locale/lang.en.js': return Promise.resolve().then(function () { return lang_en$1; }); case './locale/lang.es.js': return Promise.resolve().then(function () { return lang_es$1; }); case './locale/lang.et.js': return Promise.resolve().then(function () { return lang_et$1; }); case './locale/lang.fa.js': return Promise.resolve().then(function () { return lang_fa$1; }); case './locale/lang.fi.js': return Promise.resolve().then(function () { return lang_fi$1; }); case './locale/lang.fr.js': return Promise.resolve().then(function () { return lang_fr$1; }); case './locale/lang.fy.js': return Promise.resolve().then(function () { return lang_fy$1; }); case './locale/lang.ga.js': return Promise.resolve().then(function () { return lang_ga$1; }); case './locale/lang.gl.js': return Promise.resolve().then(function () { return lang_gl$1; }); case './locale/lang.he.js': return Promise.resolve().then(function () { return lang_he$1; }); case './locale/lang.hi.js': return Promise.resolve().then(function () { return lang_hi$1; }); case './locale/lang.hr.js': return Promise.resolve().then(function () { return lang_hr$1; }); case './locale/lang.hu.js': return Promise.resolve().then(function () { return lang_hu$1; }); case './locale/lang.hy.js': return Promise.resolve().then(function () { return lang_hy$1; }); case './locale/lang.id.js': return Promise.resolve().then(function () { return lang_id$1; }); case './locale/lang.is.js': return Promise.resolve().then(function () { return lang_is$1; }); case './locale/lang.it.js': return Promise.resolve().then(function () { return lang_it$1; }); case './locale/lang.ja.js': return Promise.resolve().then(function () { return lang_ja$1; }); case './locale/lang.ko.js': return Promise.resolve().then(function () { return lang_ko$1; }); case './locale/lang.lt.js': return Promise.resolve().then(function () { return lang_lt$1; }); case './locale/lang.lv.js': return Promise.resolve().then(function () { return lang_lv$1; }); case './locale/lang.mk.js': return Promise.resolve().then(function () { return lang_mk$1; }); case './locale/lang.ms.js': return Promise.resolve().then(function () { return lang_ms$1; }); case './locale/lang.mt.js': return Promise.resolve().then(function () { return lang_mt$1; }); case './locale/lang.nl.js': return Promise.resolve().then(function () { return lang_nl$1; }); case './locale/lang.no.js': return Promise.resolve().then(function () { return lang_no$1; }); case './locale/lang.pl.js': return Promise.resolve().then(function () { return lang_pl$1; }); case './locale/lang.pt-BR.js': return Promise.resolve().then(function () { return lang_ptBR$1; }); case './locale/lang.pt-PT.js': return Promise.resolve().then(function () { return lang_ptPT$1; }); case './locale/lang.ro.js': return Promise.resolve().then(function () { return lang_ro$1; }); case './locale/lang.ru.js': return Promise.resolve().then(function () { return lang_ru$1; }); case './locale/lang.sk.js': return Promise.resolve().then(function () { return lang_sk$1; }); case './locale/lang.sl.js': return Promise.resolve().then(function () { return lang_sl$1; }); case './locale/lang.sq.js': return Promise.resolve().then(function () { return lang_sq$1; }); case './locale/lang.sr.js': return Promise.resolve().then(function () { return lang_sr$1; }); case './locale/lang.sv.js': return Promise.resolve().then(function () { return lang_sv$1; }); case './locale/lang.sw.js': return Promise.resolve().then(function () { return lang_sw$1; }); case './locale/lang.test.js': return Promise.resolve().then(function () { return lang_test$1; }); case './locale/lang.th.js': return Promise.resolve().then(function () { return lang_th$1; }); case './locale/lang.tl.js': return Promise.resolve().then(function () { return lang_tl$1; }); case './locale/lang.tr.js': return Promise.resolve().then(function () { return lang_tr$1; }); case './locale/lang.uk.js': return Promise.resolve().then(function () { return lang_uk$1; }); case './locale/lang.vi.js': return Promise.resolve().then(function () { return lang_vi$1; }); case './locale/lang.yi.js': return Promise.resolve().then(function () { return lang_yi$1; }); case './locale/lang.zh-CN.js': return Promise.resolve().then(function () { return lang_zhCN$1; }); case './locale/lang.zh-HK.js': return Promise.resolve().then(function () { return lang_zhHK$1; }); case './locale/lang.zh-TW.js': return Promise.resolve().then(function () { return lang_zhTW$1; }); default: return Promise.reject(new Error("Unknown variable dynamic import: " + path)); } } /* globals jQuery */ /** * Localizing script for SVG-edit UI. * @module locale * @license MIT * * @copyright 2010 Narendra Sisodya * @copyright 2010 Alexis Deveria * */ /** * Used, for example, in the ImageLibs extension, to present libraries * (with name/URL/description) in order. * @typedef {GenericArray<module:locale.LocaleStrings>} module:locale.LocaleArray */ /** * The string keys of the object are two-letter language codes. * @tutorial LocaleDocs * @typedef {PlainObject<string, string|module:locale.LocaleStrings|module:locale.LocaleArray>} module:locale.LocaleStrings */ // keyed to an array of objects with "id" and "title" or "textContent" properties /** * @typedef {PlainObject<string, string>} module:locale.LocaleSelectorValue */ var $$c = jQuery; var langParam; /** * Looks for elements to localize using the supplied `obj` to indicate * on which selectors (or IDs if `ids` is set to `true`) to set its * strings (with selectors relative to the editor root element). All * keys will be translated, but for each selector, only the first item * found matching will be modified. * If the type is `content`, the selector-identified element's children * will be checked, and the first (non-empty) text (placeholder) node * found will have its text replaced. * If the type is `title`, the element's `title` * property will be set. * If the type is `aria-label`, the element's `aria-label` attribute * will be set (i.e., instructions for screen readers when there is * otherwise no visible text to be read for the function of the form * control). * @param {"content"|"title"} type * @param {module:locale.LocaleSelectorValue} obj Selectors or IDs keyed to strings * @param {boolean} ids * @returns {void} */ var setStrings = function setStrings(type, obj, ids) { // Root element to look for element from var parent = $$c('#svg_editor').parent(); Object.entries(obj).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), sel = _ref2[0], val = _ref2[1]; if (!val) { console.log(sel); // eslint-disable-line no-console return; // keep old text when has no translation } if (ids) { sel = '#' + sel; } var $elem = parent.find(sel); if ($elem.length) { var elem = $elem[0]; switch (type) { case 'aria-label': elem.setAttribute('aria-label', val); break; case 'content': _toConsumableArray(elem.childNodes).some(function (node) { if (node.nodeType === 3 /* Node.TEXT_NODE */ && node.textContent.trim()) { node.textContent = val; return true; } return false; }); break; case 'title': elem.title = val; break; } } else { console.log('Missing element for localization: ' + sel); // eslint-disable-line no-console } }); }; /** * The "data" property is generally set to an an array of objects with * "id" and "title" or "textContent" properties. * @typedef {PlainObject} module:locale.AddLangExtensionLocaleData * @property {module:locale.LocaleStrings[]} data See {@tutorial LocaleDocs} */ /** * @interface module:locale.LocaleEditorInit */ /** * @function module:locale.LocaleEditorInit#addLangData * @param {string} langParam * @returns {module:locale.AddLangExtensionLocaleData} */ var editor_; /** * Sets the current editor instance (on which `addLangData`) exists. * @function init * @memberof module:locale * @param {module:locale.LocaleEditorInit} editor * @returns {void} */ var init$7 = function init(editor) { editor_ = editor; }; /** * @typedef {PlainObject} module:locale.LangAndData * @property {string} langParam * @property {module:locale.LocaleStrings} langData */ /** * @function module:locale.readLang * @param {module:locale.LocaleStrings} langData See {@tutorial LocaleDocs} * @fires module:svgcanvas.SvgCanvas#event:ext_addLangData * @returns {Promise<module:locale.LangAndData>} Resolves to [`LangAndData`]{@link module:locale.LangAndData} */ var readLang = /*#__PURE__*/function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(langData) { var more, _langData, tools, properties, config, layers, common, ui, opts, ariaLabels; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return editor_.addLangData(langParam); case 2: more = _context.sent; $$c.each(more, function (i, m) { if (m.data) { langData = $$c.merge(langData, m.data); } }); // Old locale file, do nothing for now. if (langData.tools) { _context.next = 6; break; } return _context.abrupt("return", undefined); case 6: _langData = langData, tools = _langData.tools, properties = _langData.properties, config = _langData.config, layers = _langData.layers, common = _langData.common, ui = _langData.ui; setStrings('content', { // Todo: Add this powered by (probably by default) but with config to remove // copyrightLabel: misc.powered_by, // Currently commented out in svg-editor.html curve_segments: properties.curve_segments, fitToContent: tools.fitToContent, fit_to_all: tools.fit_to_all, fit_to_canvas: tools.fit_to_canvas, fit_to_layer_content: tools.fit_to_layer_content, fit_to_sel: tools.fit_to_sel, icon_large: config.icon_large, icon_medium: config.icon_medium, icon_small: config.icon_small, icon_xlarge: config.icon_xlarge, image_opt_embed: config.image_opt_embed, image_opt_ref: config.image_opt_ref, includedImages: config.included_images, largest_object: tools.largest_object, layersLabel: layers.layers, page: tools.page, relativeToLabel: tools.relativeTo, selLayerLabel: layers.move_elems_to, selectedPredefined: config.select_predefined, selected_objects: tools.selected_objects, smallest_object: tools.smallest_object, straight_segments: properties.straight_segments, svginfo_bg_url: config.editor_img_url + ':', svginfo_bg_note: config.editor_bg_note, svginfo_change_background: config.background, svginfo_dim: config.doc_dims, svginfo_editor_prefs: config.editor_prefs, svginfo_height: common.height, svginfo_icons: config.icon_size, svginfo_image_props: config.image_props, svginfo_lang: config.language, svginfo_title: config.doc_title, svginfo_width: common.width, tool_docprops_cancel: common.cancel, tool_docprops_save: common.ok, tool_source_cancel: common.cancel, tool_source_save: common.ok, tool_prefs_cancel: common.cancel, tool_prefs_save: common.ok, sidepanel_handle: layers.layers.split('').join(' '), tool_clear: tools.new_doc, tool_docprops: tools.docprops, tool_export: tools.export_img, tool_import: tools.import_doc, tool_open: tools.open_doc, tool_save: tools.save_doc, tool_editor_prefs: config.editor_prefs, tool_editor_homepage: tools.editor_homepage, svginfo_units_rulers: config.units_and_rulers, svginfo_rulers_onoff: config.show_rulers, svginfo_unit: config.base_unit, svginfo_grid_settings: config.grid, svginfo_snap_onoff: config.snapping_onoff, svginfo_snap_step: config.snapping_stepsize, svginfo_grid_color: config.grid_color }, true); // Context menus opts = {}; ['cut', 'copy', 'paste', 'paste_in_place', 'delete', 'group', 'ungroup', 'move_front', 'move_up', 'move_down', 'move_back'].forEach(function (item) { opts['#cmenu_canvas a[href="#' + item + '"]'] = tools[item]; }); ['dupe', 'merge_down', 'merge_all'].forEach(function (item) { opts['#cmenu_layers a[href="#' + item + '"]'] = layers[item]; }); opts['#cmenu_layers a[href="#delete"]'] = layers.del; setStrings('content', opts); ariaLabels = {}; Object.entries({ tool_blur: properties.blur, tool_position: tools.align_to_page, tool_font_family: properties.font_family, zoom_panel: ui.zoom_level, stroke_linejoin: properties.linejoin_miter, stroke_linecap: properties.linecap_butt, tool_opacity: properties.opacity }).forEach(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 2), id = _ref5[0], value = _ref5[1]; ariaLabels['#' + id + ' button'] = value; }); Object.entries({ group_opacity: properties.opacity, zoom: ui.zoom_level }).forEach(function (_ref6) { var _ref7 = _slicedToArray(_ref6, 2), id = _ref7[0], value = _ref7[1]; ariaLabels['#' + id] = value; }); setStrings('aria-label', ariaLabels); setStrings('title', { align_relative_to: tools.align_relative_to, circle_cx: properties.circle_cx, circle_cy: properties.circle_cy, circle_r: properties.circle_r, cornerRadiusLabel: properties.corner_radius, ellipse_cx: properties.ellipse_cx, ellipse_cy: properties.ellipse_cy, ellipse_rx: properties.ellipse_rx, ellipse_ry: properties.ellipse_ry, fill_color: properties.fill_color, font_family: properties.font_family, idLabel: properties.id, image_height: properties.image_height, image_url: properties.image_url, image_width: properties.image_width, layer_delete: layers.del, layer_down: layers.move_down, layer_new: layers["new"], layer_rename: layers.rename, layer_moreopts: common.more_opts, layer_up: layers.move_up, line_x1: properties.line_x1, line_x2: properties.line_x2, line_y1: properties.line_y1, line_y2: properties.line_y2, linecap_butt: properties.linecap_butt, linecap_round: properties.linecap_round, linecap_square: properties.linecap_square, linejoin_bevel: properties.linejoin_bevel, linejoin_miter: properties.linejoin_miter, linejoin_round: properties.linejoin_round, main_icon: tools.main_menu, palette: ui.palette_info, zoom_panel: ui.zoom_level, path_node_x: properties.node_x, path_node_y: properties.node_y, rect_height_tool: properties.rect_height, rect_width_tool: properties.rect_width, seg_type: properties.seg_type, selLayerNames: layers.move_selected, selected_x: properties.pos_x, selected_y: properties.pos_y, stroke_color: properties.stroke_color, stroke_style: properties.stroke_style, stroke_width: properties.stroke_width, svginfo_title: config.doc_title, text: properties.text_contents, toggle_stroke_tools: ui.toggle_stroke_tools, tool_add_subpath: tools.add_subpath, tool_alignbottom: tools.align_bottom, tool_aligncenter: tools.align_center, tool_alignleft: tools.align_left, tool_alignmiddle: tools.align_middle, tool_alignright: tools.align_right, tool_aligntop: tools.align_top, tool_angle: properties.angle, tool_blur: properties.blur, tool_bold: properties.bold, tool_circle: tools.mode_circle, tool_clone: tools.clone, tool_clone_multi: tools.clone, tool_delete: tools.del, tool_delete_multi: tools.del, tool_ellipse: tools.mode_ellipse, tool_fhellipse: tools.mode_fhellipse, tool_fhpath: tools.mode_fhpath, tool_fhrect: tools.mode_fhrect, tool_font_size: properties.font_size, tool_group_elements: tools.group_elements, tool_make_link: tools.make_link, tool_link_url: tools.set_link_url, tool_image: tools.mode_image, tool_italic: properties.italic, tool_line: tools.mode_line, tool_move_bottom: tools.move_bottom, tool_move_top: tools.move_top, tool_node_clone: tools.node_clone, tool_node_delete: tools.node_delete, tool_node_link: tools.node_link, tool_opacity: properties.opacity, tool_openclose_path: tools.openclose_path, tool_path: tools.mode_path, tool_position: tools.align_to_page, tool_rect: tools.mode_rect, tool_redo: tools.redo, tool_reorient: tools.reorient_path, tool_select: tools.mode_select, tool_source: tools.source_save, tool_square: tools.mode_square, tool_text: tools.mode_text, tool_topath: tools.to_path, tool_undo: tools.undo, tool_ungroup: tools.ungroup, tool_wireframe: tools.wireframe_mode, tool_zoom: tools.mode_zoom, url_notice: tools.no_embed }, true); return _context.abrupt("return", { langParam: langParam, langData: langData }); case 19: case "end": return _context.stop(); } } }, _callee); })); return function readLang(_x) { return _ref3.apply(this, arguments); }; }(); /** * * @function module:locale.putLocale * @param {string} givenParam * @param {string[]} goodLangs * @fires module:svgcanvas.SvgCanvas#event:ext_addLangData * @fires module:svgcanvas.SvgCanvas#event:ext_langReady * @fires module:svgcanvas.SvgCanvas#event:ext_langChanged * @returns {Promise<module:locale.LangAndData>} Resolves to result of {@link module:locale.readLang} */ var putLocale = /*#__PURE__*/function () { var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(givenParam, goodLangs) { var module; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (givenParam) { langParam = givenParam; } else if (navigator.userLanguage) { // Explorer langParam = navigator.userLanguage; } else if (navigator.language) { // FF, Opera, ... langParam = navigator.language; } console.log('Lang: ' + langParam); // eslint-disable-line no-console // Set to English if language is not in list of good langs if (!goodLangs.includes(langParam) && langParam !== 'test') { langParam = 'en'; } // eslint-disable-next-line node/no-unsupported-features/es-syntax _context2.next = 5; return __variableDynamicImportRuntime0__("./locale/lang.".concat(langParam, ".js")); case 5: module = _context2.sent; return _context2.abrupt("return", readLang(module["default"])); case 7: case "end": return _context2.stop(); } } }, _callee2); })); return function putLocale(_x2, _x3) { return _ref8.apply(this, arguments); }; }(); var $q$1 = $q; var editor = {}; var $$d = [jQueryPluginJSHotkeys, jQueryPluginSVGIcons, jQueryPluginJGraduate, jQueryPluginSpinButton, jQueryPluginSVG, jQueryContextMenu, jPicker].reduce(function (jq, func) { return func(jq); }, jQuery); var homePage = 'https://github.com/SVG-Edit/svgedit'; // EDITOR PROPERTIES: (defined below) // curPrefs, curConfig, canvas, storage, uiStrings // // STATE MAINTENANCE PROPERTIES /** * @type {Float} */ editor.tool_scale = 1; // Dependent on icon size, so any use to making configurable instead? Used by `jQuery.SpinButton.js` /** * @type {Integer} */ editor.exportWindowCt = 0; /** * @type {boolean} */ editor.langChanged = false; /** * @type {boolean} */ editor.showSaveWarning = false; /** * Will be set to a boolean by `ext-storage.js` * @type {"ignore"|"waiting"|"closed"} */ editor.storagePromptState = 'ignore'; var callbacks = [], /** * @typedef {"s"|"m"|"l"|"xl"|Float} module:SVGEditor.IconSize */ /** * Preferences. * @interface module:SVGEditor.Prefs * @property {string} [lang="en"] Two-letter language code. The language must exist in the Editor Preferences language list. Defaults to "en" if `locale.js` detection does not detect another language. * @property {module:SVGEditor.IconSize} [iconsize="s"|"m"] Size of the toolbar icons. Will default to 's' if the window height is smaller than the minimum height and 'm' otherwise. * @property {string} [bkgd_color="#FFF"] Color hex for canvas background color. Defaults to white. * @property {string} [bkgd_url=""] Background raster image URL. This image will fill the background of the document; useful for tracing purposes. * @property {"embed"|"ref"} [img_save="embed"] Defines whether included raster images should be saved as Data URIs when possible, or as URL references. Settable in the Document Properties dialog. * @property {boolean} [save_notice_done=false] Used to track alert status * @property {boolean} [export_notice_done=false] Used to track alert status * @todo `save_notice_done` and `export_notice_done` should be changed to flags rather than preferences */ /** * @namespace {module:SVGEditor.Prefs} defaultPrefs * @memberof module:SVGEditor~ * @implements {module:SVGEditor.Prefs} */ // The iteration algorithm for defaultPrefs does not currently support array/objects defaultPrefs = /** @lends module:SVGEditor~defaultPrefs */ { // EDITOR OPTIONS (DIALOG) /** * Default to "en" if locale.js detection does not detect another language. */ lang: '', /** * Will default to 's' if the window height is smaller than the minimum * height and 'm' otherwise. */ iconsize: '', bkgd_color: '#FFF', bkgd_url: '', // DOCUMENT PROPERTIES (DIALOG) img_save: 'embed', // ALERT NOTICES // Only shows in UI as far as alert notices, but useful to remember, so keeping as pref save_notice_done: false, export_notice_done: false }, /** * @name module:SVGEditor~defaultExtensions * @type {string[]} */ defaultExtensions = ['ext-connector.js', 'ext-eyedropper.js', 'ext-grid.js', 'ext-imagelib.js', 'ext-markers.js', 'ext-overview_window.js', 'ext-panning.js', 'ext-polygon.js', 'ext-shapes.js', 'ext-star.js', 'ext-storage.js'], /** * @typedef {"@default"|string} module:SVGEditor.Stylesheet `@default` will automatically load all of the default CSS paths for SVGEditor */ /** * @typedef {GenericArray} module:SVGEditor.XYDimensions * @property {Integer} length 2 * @property {Float} 0 * @property {Float} 1 */ /** * @tutorial ConfigOptions * @interface module:SVGEditor.Config * @property {string} [canvasName="default"] Used to namespace storage provided via `ext-storage.js`; you can use this if you wish to have multiple independent instances of SVG Edit on the same domain * @property {boolean} [no_save_warning=false] If `true`, prevents the warning dialog box from appearing when closing/reloading the page. Mostly useful for testing. * @property {string} [imgPath="images/"] The path where the SVG icons are located, with trailing slash. Note that as of version 2.7, this is not configurable by URL for security reasons. * @property {string} [extPath="extensions/"] The path used for extension files, with trailing slash. Default will be changed to `../dist/extensions/` if this is a modular load. Note that as of version 2.7, this is not configurable by URL for security reasons. * @property {boolean} [preventAllURLConfig=false] Set to `true` to override the ability for URLs to set non-content configuration (including extension config). Must be set early, i.e., in `svgedit-config-iife.js`; extension loading is too late! * @property {boolean} [preventURLContentLoading=false] Set to `true` to override the ability for URLs to set URL-based SVG content. Must be set early, i.e., in `svgedit-config-iife.js`; extension loading is too late! * @property {boolean} [lockExtensions=false] Set to `true` to override the ability for URLs to set their own extensions; disallowed in URL setting. There is no need for this when `preventAllURLConfig` is used. Must be set early, i.e., in `svgedit-config-iife.js`; extension loading is too late! * @property {boolean} [noDefaultExtensions=false] If set to `true`, prohibits automatic inclusion of default extensions (though "extensions" can still be used to add back any desired default extensions along with any other extensions). This can only be meaningfully used in `svgedit-config-iife.js` or in the URL * @property {boolean} [noStorageOnLoad=false] Some interaction with `ext-storage.js`; prevent even the loading of previously saved local storage. * @property {boolean} [forceStorage=false] Some interaction with `ext-storage.js`; strongly discouraged from modification as it bypasses user privacy by preventing them from choosing whether to keep local storage or not (and may be required by law in some regions) * @property {boolean} [emptyStorageOnDecline=false] Used by `ext-storage.js`; empty any prior storage if the user declines to store * @property {boolean} [avoidClientSide=false] DEPRECATED (use `avoidClientSideDownload` instead); Used by `ext-server_opensave.js`; set to `true` if you wish to always save to server and not only as fallback when client support is lacking * @property {boolean} [avoidClientSideDownload=false] Used by `ext-server_opensave.js`; set to `true` if you wish to always save to server and not only as fallback when client support is lacking * @property {boolean} [avoidClientSideOpen=false] Used by `ext-server_opensave.js`; set to `true` if you wish to always open from the server and not only as fallback when FileReader client support is lacking * @property {string[]} [extensions=module:SVGEditor~defaultExtensions] Extensions to load on startup. Use an array in `setConfig` and comma separated file names in the URL. Extension names must begin with "ext-". Note that as of version 2.7, paths containing "/", "\", or ":", are disallowed for security reasons. Although previous versions of this list would entirely override the default list, as of version 2.7, the defaults will always be added to this explicit list unless the configuration `noDefaultExtensions` is included. * @property {string[]} [allowedOrigins=[]] Used by `ext-xdomain-messaging.js` to indicate which origins are permitted for cross-domain messaging (e.g., between the embedded editor and main editor code). Besides explicit domains, one might add '*' to allow all domains (not recommended for privacy/data integrity of your user's content!), `window.location.origin` for allowing the same origin (should be safe if you trust all apps on your domain), 'null' to allow `file:///` URL usage * @property {null|PlainObject} [colorPickerCSS=null] Object of CSS properties mapped to values (for jQuery) to apply to the color picker. See {@link http://api.jquery.com/css/#css-properties}. A `null` value (the default) will cause the CSS to default to `left` with a position equal to that of the `fill_color` or `stroke_color` element minus 140, and a `bottom` equal to 40 * @property {string} [paramurl] This was available via URL only. Allowed an un-encoded URL within the query string (use "url" or "source" with a data: URI instead) * @property {Float} [canvas_expansion=3] The minimum area visible outside the canvas, as a multiple of the image dimensions. The larger the number, the more one can scroll outside the canvas. * @property {PlainObject} [initFill] Init fill properties * @property {string} [initFill.color="FF0000"] The initial fill color. Must be a hex code string. Defaults to solid red. * @property {Float} [initFill.opacity=1] The initial fill opacity. Must be a number between 0 and 1 * @property {PlainObject} [initStroke] Init stroke properties * @property {Float} [initStroke.width=5] The initial stroke width. Must be a positive number. * @property {string} [initStroke.color="000000"] The initial stroke color. Must be a hex code. Defaults to solid black. * @property {Float} [initStroke.opacity=1] The initial stroke opacity. Must be a number between 0 and 1. * @property {PlainObject} text Text style properties * @property {Float} [text.stroke_width=0] Text stroke width * @property {Float} [text.font_size=24] Text font size * @property {string} [text.font_family="serif"] Text font family * @property {Float} [initOpacity=1] Initial opacity (multiplied by 100) * @property {module:SVGEditor.XYDimensions} [dimensions=[640, 480]] The default width/height of a new document. Use an array in `setConfig` (e.g., `[800, 600]`) and comma separated numbers in the URL. * @property {boolean} [gridSnapping=false] Enable snap to grid by default. Set in Editor Options. * @property {string} [gridColor="#000"] Accepts hex, e.g., '#000'. Set in Editor Options. Defaults to black. * @property {string} [baseUnit="px"] Set in Editor Options. * @property {Float} [snappingStep=10] Set the default grid snapping value. Set in Editor Options. * @property {boolean} [showRulers=true] Initial state of ruler display (v2.6). Set in Editor Options. * @property {string} [initTool="select"] The initially selected tool. Must be either the ID of the button for the tool, or the ID without `tool_` prefix (e.g., "select"). * @property {boolean} [wireframe=false] Start in wireframe mode * @property {boolean} [showlayers=false] Open the layers side-panel by default. * @property {"new"|"same"} [exportWindowType="new"] Can be "new" or "same" to indicate whether new windows will be generated for each export; the `window.name` of the export window is namespaced based on the `canvasName` (and incremented if "new" is selected as the type). Introduced 2.8. * @property {boolean} [showGrid=false] Set by `ext-grid.js`; determines whether or not to show the grid by default * @property {boolean} [show_outside_canvas=true] Defines whether or not elements outside the canvas should be visible. Set and used in `svgcanvas.js`. * @property {boolean} [selectNew=true] If true, will replace the selection with the current element and automatically select element objects (when not in "path" mode) after they are created, showing their grips (v2.6). Set and used in `svgcanvas.js` (`mouseUp`). * @todo Some others could be preferences as well (e.g., preventing URL changing of extensions, defaultExtensions, stylesheets, colorPickerCSS); Change the following to preferences and add pref controls where missing to the UI (e.g., `canvas_expansion`, `initFill`, `initStroke`, `text`, `initOpacity`, `dimensions`, `initTool`, `wireframe`, `showlayers`, `gridSnapping`, `gridColor`, `baseUnit`, `snappingStep`, `showRulers`, `exportWindowType`, `showGrid`, `show_outside_canvas`, `selectNew`)? */ /** * @namespace {module:SVGEditor.Config} defaultConfig * @memberof module:SVGEditor~ * @implements {module:SVGEditor.Config} */ defaultConfig = { canvasName: 'default', canvas_expansion: 3, initFill: { color: 'FF0000', // solid red opacity: 1 }, initStroke: { width: 5, color: '000000', // solid black opacity: 1 }, text: { stroke_width: 0, font_size: 24, font_family: 'serif' }, initOpacity: 1, colorPickerCSS: null, // Defaults to 'left' with a position equal to that of the fill_color or stroke_color element minus 140, and a 'bottom' equal to 40 initTool: 'select', exportWindowType: 'new', // 'same' (todo: also support 'download') wireframe: false, showlayers: false, no_save_warning: false, // PATH CONFIGURATION // The following path configuration items are disallowed in the URL (as should any future path configurations) extPath: './extensions/', // Default will be changed if this is a non-modular load imgPath: './images/', // DOCUMENT PROPERTIES // Change the following to a preference (already in the Document Properties dialog)? dimensions: [640, 480], // EDITOR OPTIONS // Change the following to preferences (already in the Editor Options dialog)? gridSnapping: false, gridColor: '#000', baseUnit: 'px', snappingStep: 10, showRulers: true, // URL BEHAVIOR CONFIGURATION preventAllURLConfig: false, preventURLContentLoading: false, // EXTENSION CONFIGURATION (see also preventAllURLConfig) lockExtensions: false, // Disallowed in URL setting noDefaultExtensions: false, // noDefaultExtensions can only be meaningfully used in `svgedit-config-iife.js` or in the URL // EXTENSION-RELATED (GRID) showGrid: false, // Set by ext-grid.js // EXTENSION-RELATED (STORAGE) noStorageOnLoad: false, // Some interaction with ext-storage.js; prevent even the loading of previously saved local storage forceStorage: false, // Some interaction with ext-storage.js; strongly discouraged from modification as it bypasses user privacy by preventing them from choosing whether to keep local storage or not emptyStorageOnDecline: false, // Used by ext-storage.js; empty any prior storage if the user declines to store // EXTENSION (CLIENT VS. SERVER SAVING/OPENING) avoidClientSide: false, // Deprecated in favor of `avoidClientSideDownload` avoidClientSideDownload: false, avoidClientSideOpen: false }, /** * LOCALE. * @name module:SVGEditor.uiStrings * @type {PlainObject} */ uiStrings$1 = editor.uiStrings = {}; var svgCanvas, urldata = {}, isReady = false, customExportImage = false, customExportPDF = false, curPrefs = {}, // Note: The difference between Prefs and Config is that Prefs // can be changed in the UI and are stored in the browser, // while config cannot curConfig = { // We do not put on defaultConfig to simplify object copying // procedures (we obtain instead from defaultExtensions) extensions: [], /** * Can use `location.origin` to indicate the current * origin. Can contain a '*' to allow all domains or 'null' (as * a string) to support all `file:///` URLs. Cannot be set by * URL for security reasons (not safe, at least for * privacy or data integrity of SVG content). * Might have been fairly safe to allow * `new URL(location.href).origin` by default but * avoiding it ensures some more security that even third * party apps on the same domain also cannot communicate * with this app by default. * For use with `ext-xdomain-messaging.js` * @todo We might instead make as a user-facing preference. */ allowedOrigins: [] }; /** * * @param {string} str SVG string * @param {PlainObject} [opts={}] * @param {boolean} [opts.noAlert] * @throws {Error} Upon failure to load SVG * @returns {Promise<void>} Resolves to undefined upon success (or if `noAlert` is * falsey, though only until after the `alert` is closed); rejects if SVG * loading fails and `noAlert` is truthy. */ function loadSvgString(_x) { return _loadSvgString.apply(this, arguments); } /** * @function module:SVGEditor~getImportLocale * @param {PlainObject} defaults * @param {string} defaults.defaultLang * @param {string} defaults.defaultName * @returns {module:SVGEditor~ImportLocale} */ function _loadSvgString() { _loadSvgString = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee24(str) { var _ref41, noAlert, success, _args24 = arguments; return regeneratorRuntime.wrap(function _callee24$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: _ref41 = _args24.length > 1 && _args24[1] !== undefined ? _args24[1] : {}, noAlert = _ref41.noAlert; success = svgCanvas.setSvgString(str) !== false; if (!success) { _context24.next = 4; break; } return _context24.abrupt("return"); case 4: if (noAlert) { _context24.next = 8; break; } _context24.next = 7; return $$d.alert(uiStrings$1.notification.errorLoadingSVG); case 7: return _context24.abrupt("return"); case 8: throw new Error('Error loading SVG'); case 9: case "end": return _context24.stop(); } } }, _callee24); })); return _loadSvgString.apply(this, arguments); } function getImportLocale(_ref) { var defaultLang = _ref.defaultLang, defaultName = _ref.defaultName; /** * @function module:SVGEditor~ImportLocale * @param {PlainObject} localeInfo * @param {string} [localeInfo.name] Defaults to `defaultName` of {@link module:SVGEditor~getImportLocale} * @param {string} [localeInfo.lang=defaultLang] Defaults to `defaultLang` of {@link module:SVGEditor~getImportLocale} * @returns {Promise<module:locale.LocaleStrings>} Resolves to {@link module:locale.LocaleStrings} */ return /*#__PURE__*/function () { var _importLocaleDefaulting = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { var _ref2, _ref2$name, name, _ref2$lang, lang, importLocale, _importLocale, _args2 = arguments; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _importLocale = function _importLocale3() { _importLocale = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(language) { var url, locale; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: url = "".concat(curConfig.extPath, "ext-locale/").concat(name, "/").concat(language, ".js"); // eslint-disable-next-line node/no-unsupported-features/es-syntax _context.next = 3; return import(url); case 3: locale = _context.sent; return _context.abrupt("return", locale["default"]); case 5: case "end": return _context.stop(); } } }, _callee); })); return _importLocale.apply(this, arguments); }; importLocale = function _importLocale2(_x2) { return _importLocale.apply(this, arguments); }; _ref2 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref2$name = _ref2.name, name = _ref2$name === void 0 ? defaultName : _ref2$name, _ref2$lang = _ref2.lang, lang = _ref2$lang === void 0 ? defaultLang : _ref2$lang; _context2.prev = 3; _context2.next = 6; return importLocale(lang); case 6: return _context2.abrupt("return", _context2.sent); case 9: _context2.prev = 9; _context2.t0 = _context2["catch"](3); return _context2.abrupt("return", importLocale('en')); case 12: case "end": return _context2.stop(); } } }, _callee2, null, [[3, 9]]); })); function importLocaleDefaulting() { return _importLocaleDefaulting.apply(this, arguments); } return importLocaleDefaulting; }(); } /** * EXPORTS. */ /** * Store and retrieve preferences. * @function module:SVGEditor.pref * @param {string} key The preference name to be retrieved or set * @param {string} [val] The value. If the value supplied is missing or falsey, no change to the preference will * be made unless `mayBeEmpty` is set. * @param {boolean} [mayBeEmpty] If value may be falsey. * @returns {string|void} If val is missing or falsey and `mayBeEmpty` is not set, the * value of the previously stored preference will be returned. * @todo Review whether any remaining existing direct references to * getting `curPrefs` can be changed to use `svgEditor.pref()` getting to ensure * `defaultPrefs` fallback (also for sake of `allowInitialUserOverride`); * specifically, `bkgd_color` could be changed so that the pref dialog has a * button to auto-calculate background, but otherwise uses `svgEditor.pref()` to * be able to get default prefs or overridable settings */ editor.pref = function (key, val, mayBeEmpty) { if (mayBeEmpty || val) { curPrefs[key] = val; /** * @name curPrefs * @memberof module:SVGEditor * @implements {module:SVGEditor.Prefs} */ editor.curPrefs = curPrefs; // Update exported value return undefined; } return key in curPrefs ? curPrefs[key] : defaultPrefs[key]; }; /* * EDITOR PUBLIC METHODS // Todo: Sort these methods per invocation order, ideally with init at the end // Todo: Prevent execution until init executes if dependent on it? */ editor.putLocale = putLocale; editor.readLang = readLang; editor.setStrings = setStrings; /** * Where permitted, sets canvas and/or `defaultPrefs` based on previous * storage. This will override URL settings (for security reasons) but * not `svgedit-config-iife.js` configuration (unless initial user * overriding is explicitly permitted there via `allowInitialUserOverride`). * @function module:SVGEditor.loadContentAndPrefs * @todo Split `allowInitialUserOverride` into `allowOverrideByURL` and * `allowOverrideByUserStorage` so `svgedit-config-iife.js` can disallow some * individual items for URL setting but allow for user storage AND/OR * change URL setting so that it always uses a different namespace, * so it won't affect pre-existing user storage (but then if users saves * that, it will then be subject to tampering * @returns {void} */ editor.loadContentAndPrefs = function () { if (!curConfig.forceStorage && (curConfig.noStorageOnLoad || !document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/))) { return; } // LOAD CONTENT if (editor.storage && ( // Cookies do not have enough available memory to hold large documents curConfig.forceStorage || !curConfig.noStorageOnLoad && document.cookie.match(/(?:^|;\s*)svgeditstore=prefsAndContent/))) { var _name = 'svgedit-' + curConfig.canvasName; var cached = editor.storage.getItem(_name); if (cached) { editor.loadFromString(cached); } } // LOAD PREFS Object.keys(defaultPrefs).forEach(function (key) { var storeKey = 'svg-edit-' + key; if (editor.storage) { var val = editor.storage.getItem(storeKey); if (val) { defaultPrefs[key] = String(val); // Convert to string for FF (.value fails in Webkit) } } else if (window.widget) { defaultPrefs[key] = window.widget.preferenceForKey(storeKey); } else { var result = document.cookie.match(new RegExp('(?:^|;\\s*)' + regexEscape(encodeURIComponent(storeKey)) + '=([^;]+)')); defaultPrefs[key] = result ? decodeURIComponent(result[1]) : ''; } }); }; /** * Allows setting of preferences or configuration (including extensions). * @function module:SVGEditor.setConfig * @param {module:SVGEditor.Config|module:SVGEditor.Prefs} opts The preferences or configuration (including extensions). See the tutorial on {@tutorial ConfigOptions} for info on config and preferences. * @param {PlainObject} [cfgCfg] Describes configuration which applies to the * particular batch of supplied options * @param {boolean} [cfgCfg.allowInitialUserOverride=false] Set to true if you wish * to allow initial overriding of settings by the user via the URL * (if permitted) or previously stored preferences (if permitted); * note that it will be too late if you make such calls in extension * code because the URL or preference storage settings will * have already taken place. * @param {boolean} [cfgCfg.overwrite=true] Set to false if you wish to * prevent the overwriting of prior-set preferences or configuration * (URL settings will always follow this requirement for security * reasons, so `svgedit-config-iife.js` settings cannot be overridden unless it * explicitly permits via `allowInitialUserOverride` but extension config * can be overridden as they will run after URL settings). Should * not be needed in `svgedit-config-iife.js`. * @returns {void} */ editor.setConfig = function (opts, cfgCfg) { cfgCfg = cfgCfg || {}; /** * * @param {module:SVGEditor.Config|module:SVGEditor.Prefs} cfgObj * @param {string} key * @param {any} val See {@link module:SVGEditor.Config} or {@link module:SVGEditor.Prefs} * @returns {void} */ function extendOrAdd(cfgObj, key, val) { if (cfgObj[key] && _typeof(cfgObj[key]) === 'object') { $$d.extend(true, cfgObj[key], val); } else { cfgObj[key] = val; } } Object.entries(opts).forEach(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), key = _ref4[0], val = _ref4[1]; // Only allow prefs defined in defaultPrefs or... if ({}.hasOwnProperty.call(defaultPrefs, key)) { if (cfgCfg.overwrite === false && (curConfig.preventAllURLConfig || {}.hasOwnProperty.call(curPrefs, key))) { return; } if (cfgCfg.allowInitialUserOverride === true) { defaultPrefs[key] = val; } else { editor.pref(key, val); } } else if (['extensions', 'allowedOrigins'].includes(key)) { if (cfgCfg.overwrite === false && (curConfig.preventAllURLConfig || ['allowedOrigins'].includes(key) || key === 'extensions' && curConfig.lockExtensions)) { return; } curConfig[key] = curConfig[key].concat(val); // We will handle any dupes later // Only allow other curConfig if defined in defaultConfig } else if ({}.hasOwnProperty.call(defaultConfig, key)) { if (cfgCfg.overwrite === false && (curConfig.preventAllURLConfig || {}.hasOwnProperty.call(curConfig, key))) { return; } // Potentially overwriting of previously set config if ({}.hasOwnProperty.call(curConfig, key)) { if (cfgCfg.overwrite === false) { return; } extendOrAdd(curConfig, key, val); } else if (cfgCfg.allowInitialUserOverride === true) { extendOrAdd(defaultConfig, key, val); } else if (defaultConfig[key] && _typeof(defaultConfig[key]) === 'object') { curConfig[key] = Array.isArray(defaultConfig[key]) ? [] : {}; $$d.extend(true, curConfig[key], val); // Merge properties recursively, e.g., on initFill, initStroke objects } else { curConfig[key] = val; } } }); /** * @name curConfig * @memberof module:SVGEditor * @implements {module:SVGEditor.Config} */ editor.curConfig = curConfig; // Update exported value }; /** * All methods are optional. * @interface module:SVGEditor.CustomHandler * @type {PlainObject} */ /** * Its responsibilities are: * - invoke a file chooser dialog in 'open' mode * - let user pick a SVG file * - calls [svgCanvas.setSvgString()]{@link module:svgcanvas.SvgCanvas#setSvgString} with the string contents of that file. * Not passed any parameters. * @function module:SVGEditor.CustomHandler#open * @returns {void} */ /** * Its responsibilities are: * - accept the string contents of the current document * - invoke a file chooser dialog in 'save' mode * - save the file to location chosen by the user. * @function module:SVGEditor.CustomHandler#save * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:saved} svgStr A string of the SVG * @listens module:svgcanvas.SvgCanvas#event:saved * @returns {void} */ /** * Its responsibilities (with regard to the object it is supplied in its 2nd argument) are: * - inform user of any issues supplied via the "issues" property * - convert the "svg" property SVG string into an image for export; * utilize the properties "type" (currently 'PNG', 'JPEG', 'BMP', * 'WEBP', 'PDF'), "mimeType", and "quality" (for 'JPEG' and 'WEBP' * types) to determine the proper output. * @function module:SVGEditor.CustomHandler#exportImage * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:exported} data * @listens module:svgcanvas.SvgCanvas#event:exported * @returns {void} */ /** * @function module:SVGEditor.CustomHandler#exportPDF * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:exportedPDF} data * @listens module:svgcanvas.SvgCanvas#event:exportedPDF * @returns {void} */ /** * Allows one to override default SVGEdit `open`, `save`, and * `export` editor behaviors. * @function module:SVGEditor.setCustomHandlers * @param {module:SVGEditor.CustomHandler} opts Extension mechanisms may call `setCustomHandlers` with three functions: `opts.open`, `opts.save`, and `opts.exportImage` * @returns {Promise<void>} */ editor.setCustomHandlers = function (opts) { return editor.ready(function () { if (opts.open) { $$d('#tool_open > input[type="file"]').remove(); $$d('#tool_open').show(); svgCanvas.open = opts.open; } if (opts.save) { editor.showSaveWarning = false; svgCanvas.bind('saved', opts.save); } if (opts.exportImage) { customExportImage = opts.exportImage; svgCanvas.bind('exported', customExportImage); // canvg and our RGBColor will be available to the method } if (opts.exportPDF) { customExportPDF = opts.exportPDF; svgCanvas.bind('exportedPDF', customExportPDF); // jsPDF and our RGBColor will be available to the method } }); }; /** * @function module:SVGEditor.randomizeIds * @param {boolean} arg * @returns {void} */ editor.randomizeIds = function (arg) { svgCanvas.randomizeIds(arg); }; /** * Auto-run after a Promise microtask. * @function module:SVGEditor.init * @returns {void} */ editor.init = function () { // const host = location.hostname, // onWeb = host && host.includes('.'); // Some FF versions throw security errors here when directly accessing try { if ('localStorage' in window) { // && onWeb removed so Webkit works locally /** * The built-in interface implemented by `localStorage` * @external Storage */ /** * @name storage * @memberof module:SVGEditor * @type {external:Storage} */ editor.storage = localStorage; } } catch (err) {} // Todo: Avoid const-defined functions and group functions together, etc. where possible var goodLangs = []; $$d('#lang_select option').each(function () { goodLangs.push(this.value); }); /** * Sets up current preferences based on defaults. * @returns {void} */ function setupCurPrefs() { curPrefs = $$d.extend(true, {}, defaultPrefs, curPrefs); // Now safe to merge with priority for curPrefs in the event any are already set // Export updated prefs editor.curPrefs = curPrefs; } /** * Sets up current config based on defaults. * @returns {void} */ function setupCurConfig() { curConfig = $$d.extend(true, {}, defaultConfig, curConfig); // Now safe to merge with priority for curConfig in the event any are already set // Now deal with extensions and other array config if (!curConfig.noDefaultExtensions) { curConfig.extensions = curConfig.extensions.concat(defaultExtensions); } // ...and remove any dupes ['extensions', 'allowedOrigins'].forEach(function (cfg) { curConfig[cfg] = $$d.grep(curConfig[cfg], function (n, i) { // Supposedly faster than filter per http://amandeep1986.blogspot.hk/2015/02/jquery-grep-vs-js-filter.html return i === curConfig[cfg].indexOf(n); }); }); // Export updated config editor.curConfig = curConfig; } (function () { // Load config/data from URL if given var _URL = new URL(location), search = _URL.search, searchParams = _URL.searchParams; if (search) { urldata = deparam(searchParams.toString(), true); ['initStroke', 'initFill'].forEach(function (prop) { if (searchParams.has("".concat(prop, "[color]"))) { // Restore back to original non-deparamed value to avoid color // strings being converted to numbers urldata[prop].color = searchParams.get("".concat(prop, "[color]")); } }); if (searchParams.has('bkgd_color')) { urldata.bkgd_color = '#' + searchParams.get('bkgd_color'); } if (urldata.dimensions) { urldata.dimensions = urldata.dimensions.split(','); } if (urldata.extensions) { // For security reasons, disallow cross-domain or cross-folder // extensions via URL urldata.extensions = urldata.extensions.match(/[:/\\]/) ? '' : urldata.extensions.split(','); } // Disallowing extension paths via URL for // security reasons, even for same-domain // ones given potential to interact in undesirable // ways with other script resources ['extPath', 'imgPath'].forEach(function (pathConfig) { if (urldata[pathConfig]) { delete urldata[pathConfig]; } }); // Note: `source` and `url` (as with `storagePrompt` later) are not // set on config but are used below editor.setConfig(urldata, { overwrite: false }); setupCurConfig(); if (!curConfig.preventURLContentLoading) { var _urldata = urldata, source = _urldata.source; if (!source) { // urldata.source may have been null if it ended with '=' var src = searchParams.get('source'); if (src && src.startsWith('data:')) { source = src; } } if (source) { if (source.startsWith('data:')) { editor.loadFromDataURI(source); } else { editor.loadFromString(source); } return; } if (urldata.url) { editor.loadFromURL(urldata.url); return; } } if (!urldata.noStorageOnLoad || curConfig.forceStorage) { editor.loadContentAndPrefs(); } } else { setupCurConfig(); editor.loadContentAndPrefs(); } })(); setupCurPrefs(); /** * Called internally. * @function module:SVGEditor.setIcon * @param {string|Element|external:jQuery} elem * @param {string|external:jQuery} iconId * @param {Float} forcedSize Not in use * @returns {void} */ var setIcon = editor.setIcon = function (elem, iconId, forcedSize) { var icon = typeof iconId === 'string' ? $$d.getSvgIcon(iconId, true) : iconId.clone(); if (!icon) { // Todo: Investigate why this still occurs in some cases console.log('NOTE: Icon image missing: ' + iconId); // eslint-disable-line no-console return; } $$d(elem).empty().append(icon); }; /** * @fires module:svgcanvas.SvgCanvas#event:ext_addLangData * @fires module:svgcanvas.SvgCanvas#event:ext_langReady * @fires module:svgcanvas.SvgCanvas#event:ext_langChanged * @fires module:svgcanvas.SvgCanvas#event:extensions_added * @returns {Promise<module:locale.LangAndData>} Resolves to result of {@link module:locale.readLang} */ var extAndLocaleFunc = /*#__PURE__*/function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() { var _yield$editor$putLoca, langParam, langData, _uiStrings$common, ok, cancel; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return editor.putLocale(editor.pref('lang'), goodLangs); case 2: _yield$editor$putLoca = _context4.sent; langParam = _yield$editor$putLoca.langParam; langData = _yield$editor$putLoca.langData; _context4.next = 7; return setLang(langParam, langData); case 7: _uiStrings$common = uiStrings$1.common, ok = _uiStrings$common.ok, cancel = _uiStrings$common.cancel; jQueryPluginDBox($$d, { ok: ok, cancel: cancel }); setIcons(); // Wait for dbox as needed for i18n _context4.prev = 10; _context4.next = 13; return Promise.all(curConfig.extensions.map( /*#__PURE__*/function () { var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(extname) { var extensionName, url, imported, _imported$default, _imported$default$nam, _name2, init, importLocale; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: extensionName = extname.match(/^ext-(.+)\.js/); // const {extName} = extname.match(/^ext-(?<extName>.+)\.js/).groups; if (extensionName) { _context3.next = 3; break; } return _context3.abrupt("return", undefined); case 3: url = curConfig.extPath + extname; /** * @tutorial ExtensionDocs * @typedef {PlainObject} module:SVGEditor.ExtensionObject * @property {string} [name] Name of the extension. Used internally; no need for i18n. Defaults to extension name without beginning "ext-" or ending ".js". * @property {module:svgcanvas.ExtensionInitCallback} [init] */ _context3.prev = 4; _context3.next = 7; return import(url); case 7: imported = _context3.sent; _imported$default = imported["default"], _imported$default$nam = _imported$default.name, _name2 = _imported$default$nam === void 0 ? extensionName[1] : _imported$default$nam, init = _imported$default.init; // const {name = extName, init} = imported; importLocale = getImportLocale({ defaultLang: langParam, defaultName: _name2 }); return _context3.abrupt("return", editor.addExtension(_name2, init && init.bind(editor), { $: $$d, importLocale: importLocale })); case 13: _context3.prev = 13; _context3.t0 = _context3["catch"](4); // Todo: Add config to alert any errors console.log(_context3.t0); // eslint-disable-line no-console console.error('Extension failed to load: ' + extname + '; ' + _context3.t0); // eslint-disable-line no-console return _context3.abrupt("return", undefined); case 18: case "end": return _context3.stop(); } } }, _callee3, null, [[4, 13]]); })); return function (_x3) { return _ref6.apply(this, arguments); }; }())); case 13: svgCanvas.bind('extensions_added', /** * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:extensions_added} data * @listens module:svgcanvas.SvgCanvas#event:extensions_added * @returns {void} */ function (win, data) { extensionsAdded = true; Actions.setAll(); $$d('.flyout_arrow_horiz:empty').each(function () { $$d(this).append($$d.getSvgIcon('arrow_right', true).width(5).height(5)); }); if (editor.storagePromptState === 'ignore') { updateCanvas(true); } messageQueue.forEach( /** * @param {module:svgcanvas.SvgCanvas#event:message} messageObj * @fires module:svgcanvas.SvgCanvas#event:message * @returns {void} */ function (messageObj) { svgCanvas.call('message', messageObj); }); }); svgCanvas.call('extensions_added'); _context4.next = 20; break; case 17: _context4.prev = 17; _context4.t0 = _context4["catch"](10); // Todo: Report errors through the UI console.log(_context4.t0); // eslint-disable-line no-console case 20: case "end": return _context4.stop(); } } }, _callee4, null, [[10, 17]]); })); return function extAndLocaleFunc() { return _ref5.apply(this, arguments); }; }(); var stateObj = { tool_scale: editor.tool_scale }; /** * * @returns {void} */ var setFlyoutPositions = function setFlyoutPositions() { $$d('.tools_flyout').each(function () { var shower = $$d('#' + this.id + '_show'); var _shower$offset = shower.offset(), left = _shower$offset.left, top = _shower$offset.top; var w = shower.outerWidth(); $$d(this).css({ left: (left + w) * editor.tool_scale, top: top }); }); }; /** * @type {string} */ var uaPrefix = function () { var regex = /^(?:Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/; var someScript = document.getElementsByTagName('script')[0]; for (var prop in someScript.style) { if (regex.test(prop)) { // test is faster than match, so it's better to perform // that on the lot and match only when necessary return prop.match(regex)[0]; } } // Nothing found so far? if ('WebkitOpacity' in someScript.style) { return 'Webkit'; } if ('KhtmlOpacity' in someScript.style) { return 'Khtml'; } return ''; }(); /** * @param {external:jQuery} elems * @param {Float} scale * @returns {void} */ var scaleElements = function scaleElements(elems, scale) { // const prefix = '-' + uaPrefix.toLowerCase() + '-'; // Currently unused var sides = ['top', 'left', 'bottom', 'right']; elems.each(function () { // Handled in CSS // this.style[uaPrefix + 'Transform'] = 'scale(' + scale + ')'; var el = $$d(this); var w = el.outerWidth() * (scale - 1); var h = el.outerHeight() * (scale - 1); // const margins = {}; // Currently unused for (var i = 0; i < 4; i++) { var s = sides[i]; var cur = el.data('orig_margin-' + s); if (isNullish(cur)) { cur = Number.parseInt(el.css('margin-' + s)); // Cache the original margin el.data('orig_margin-' + s, cur); } var val = cur * scale; if (s === 'right') { val += w; } else if (s === 'bottom') { val += h; } el.css('margin-' + s, val); // el.css('outline', '1px solid red'); } }); }; /** * Called internally. * @function module:SVGEditor.setIconSize * @param {module:SVGEditor.IconSize} size * @returns {void} */ var setIconSize = editor.setIconSize = function (size) { // const elems = $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open'); var selToscale = '#tools_top .toolset, #editor_panel > *, #history_panel > *,' + ' #main_button, #tools_left > *, #path_node_panel > *, #multiselected_panel > *,' + ' #g_panel > *, #tool_font_size > *, .tools_flyout'; var elems = $$d(selToscale); var scale = 1; if (typeof size === 'number') { scale = size; } else { var iconSizes = { s: 0.75, m: 1, l: 1.25, xl: 1.5 }; scale = iconSizes[size]; } stateObj.tool_scale = editor.tool_scale = scale; setFlyoutPositions(); // $('.tools_flyout').each(function () { // const pos = $(this).position(); // console.log($(this), pos.left+(34 * scale)); // $(this).css({left: pos.left+(34 * scale), top: pos.top+(77 * scale)}); // console.log('l', $(this).css('left')); // }); // // const scale = .75; var hiddenPs = elems.parents(':hidden'); hiddenPs.css('visibility', 'hidden').show(); scaleElements(elems, scale); hiddenPs.css('visibility', 'visible').hide(); // return; editor.pref('iconsize', size); $$d('#iconsize').val(size); // Note that all rules will be prefixed with '#svg_editor' when parsed var cssResizeRules = { '#tools_top': { left: 50 + $$d('#main_button').width(), height: 72 }, '#tools_left': { width: 31, top: 74 }, 'div#workarea': { left: 38, top: 74 } }; var ruleElem = $$d('#tool_size_rules'); if (!ruleElem.length) { ruleElem = $$d('<style id="tool_size_rules"></style>').appendTo('head'); } else { ruleElem.empty(); } if (size !== 'm') { var styleStr = ''; $$d.each(cssResizeRules, function (selector, rules) { selector = '#svg_editor ' + selector.replace(/,/g, ', #svg_editor'); styleStr += selector + '{'; $$d.each(rules, function (prop, values) { var val; if (typeof values === 'number') { val = values * scale + 'px'; } else if (values[size] || values.all) { val = values[size] || values.all; } styleStr += prop + ':' + val + ';'; }); styleStr += '}'; }); // this.style[uaPrefix + 'Transform'] = 'scale(' + scale + ')'; var prefix = '-' + uaPrefix.toLowerCase() + '-'; styleStr += selToscale + '{' + prefix + 'transform: scale(' + scale + ');}' + ' #svg_editor div.toolset .toolset {' + prefix + 'transform: scale(1); margin: 1px !important;}' + // Hack for markers ' #svg_editor .ui-slider {' + prefix + 'transform: scale(' + 1 / scale + ');}' // Hack for sliders ; ruleElem.text(styleStr); } setFlyoutPositions(); }; /** * Setup SVG icons. * @returns {void} */ function setIcons() { $$d.svgIcons(curConfig.imgPath + 'svg_edit_icons.svg', { w: 24, h: 24, id_match: false, no_img: !isWebkit(), // Opera & Firefox 4 gives odd behavior w/images fallback_path: curConfig.imgPath, // Todo: Set `alts: {}` with keys as the IDs in fallback set to // `uiStrings` (localized) values fallback: { logo: 'logo.png', select: 'select.png', select_node: 'select_node.png', square: 'square.png', rect: 'rect.png', fh_rect: 'freehand-square.png', circle: 'circle.png', ellipse: 'ellipse.png', fh_ellipse: 'freehand-circle.png', pencil: 'fhpath.png', pen: 'line.png', text: 'text.png', path: 'path.png', add_subpath: 'add_subpath.png', close_path: 'closepath.png', open_path: 'openpath.png', image: 'image.png', zoom: 'zoom.png', arrow_right: 'flyouth.png', arrow_right_big: 'arrow_right_big.png', arrow_down: 'dropdown.gif', fill: 'fill.png', stroke: 'stroke.png', opacity: 'opacity.png', new_image: 'clear.png', save: 'save.png', "export": 'export.png', open: 'open.png', "import": 'import.png', docprops: 'document-properties.png', source: 'source.png', wireframe: 'wireframe.png', undo: 'undo.png', redo: 'redo.png', clone: 'clone.png', "delete": 'delete.png', go_up: 'go-up.png', go_down: 'go-down.png', context_menu: 'context_menu.png', move_bottom: 'move_bottom.png', move_top: 'move_top.png', to_path: 'to_path.png', link_controls: 'link_controls.png', reorient: 'reorient.png', group_elements: 'shape_group_elements.png', ungroup: 'shape_ungroup.png', unlink_use: 'unlink_use.png', width: 'width.png', height: 'height.png', c_radius: 'c_radius.png', angle: 'angle.png', blur: 'blur.png', fontsize: 'fontsize.png', align: 'align.png', align_left: 'align-left.png', align_center: 'align-center.png', align_right: 'align-right.png', align_top: 'align-top.png', align_middle: 'align-middle.png', align_bottom: 'align-bottom.png', linecap_butt: 'linecap_butt.png', linecap_square: 'linecap_square.png', linecap_round: 'linecap_round.png', linejoin_miter: 'linejoin_miter.png', linejoin_bevel: 'linejoin_bevel.png', linejoin_round: 'linejoin_round.png', eye: 'eye.png', no_color: 'no_color.png', ok: 'save.png', cancel: 'cancel.png', warning: 'warning.png', node_delete: 'node_delete.png', node_clone: 'node_clone.png', globe_link: 'globe_link.png', config: 'config.png' }, placement: { '#logo': 'logo', '#tool_clear div,#layer_new': 'new_image', '#tool_save div': 'save', '#tool_export div': 'export', '#tool_open div': 'open', '#tool_import div': 'import', '#tool_source': 'source', '#tool_docprops > div': 'docprops', '#tool_editor_prefs > div': 'config', '#tool_editor_homepage > div': 'globe_link', '#tool_wireframe': 'wireframe', '#tool_undo': 'undo', '#tool_redo': 'redo', '#tool_select': 'select', '#tool_fhpath': 'pencil', '#tool_line': 'pen', '#tool_rect,#tools_rect_show': 'rect', '#tool_square': 'square', '#tool_fhrect': 'fh_rect', '#tool_ellipse,#tools_ellipse_show': 'ellipse', '#tool_circle': 'circle', '#tool_fhellipse': 'fh_ellipse', '#tool_path': 'path', '#tool_text,#layer_rename': 'text', '#tool_image': 'image', '#tool_zoom': 'zoom', '#tool_clone,#tool_clone_multi': 'clone', '#tool_node_clone': 'node_clone', '#layer_delete,#tool_delete,#tool_delete_multi': 'delete', '#tool_node_delete': 'node_delete', '#tool_add_subpath': 'add_subpath', '#tool_openclose_path': 'open_path', '#tool_move_top': 'move_top', '#tool_move_bottom': 'move_bottom', '#tool_topath': 'to_path', '#tool_node_link': 'link_controls', '#tool_reorient': 'reorient', '#tool_group_elements': 'group_elements', '#tool_ungroup': 'ungroup', '#tool_unlink_use': 'unlink_use', '#tool_alignleft, #tool_posleft': 'align_left', '#tool_aligncenter, #tool_poscenter': 'align_center', '#tool_alignright, #tool_posright': 'align_right', '#tool_aligntop, #tool_postop': 'align_top', '#tool_alignmiddle, #tool_posmiddle': 'align_middle', '#tool_alignbottom, #tool_posbottom': 'align_bottom', '#cur_position': 'align', '#linecap_butt,#cur_linecap': 'linecap_butt', '#linecap_round': 'linecap_round', '#linecap_square': 'linecap_square', '#linejoin_miter,#cur_linejoin': 'linejoin_miter', '#linejoin_round': 'linejoin_round', '#linejoin_bevel': 'linejoin_bevel', '#url_notice': 'warning', '#layer_up': 'go_up', '#layer_down': 'go_down', '#layer_moreopts': 'context_menu', '#layerlist td.layervis': 'eye', '#tool_source_save,#tool_docprops_save,#tool_prefs_save': 'ok', '#tool_source_cancel,#tool_docprops_cancel,#tool_prefs_cancel': 'cancel', '#rwidthLabel, #iwidthLabel': 'width', '#rheightLabel, #iheightLabel': 'height', '#cornerRadiusLabel span': 'c_radius', '#angleLabel': 'angle', '#linkLabel,#tool_make_link,#tool_make_link_multi': 'globe_link', '#zoomLabel': 'zoom', '#tool_fill label': 'fill', '#tool_stroke .icon_label': 'stroke', '#group_opacityLabel': 'opacity', '#blurLabel': 'blur', '#font_sizeLabel': 'fontsize', '.flyout_arrow_horiz': 'arrow_right', '.dropdown button, #main_button .dropdown': 'arrow_down', '#palette .palette_item:first, #fill_bg, #stroke_bg': 'no_color' }, resize: { '#logo .svg_icon': 28, '.flyout_arrow_horiz .svg_icon': 5, '.layer_button .svg_icon, #layerlist td.layervis .svg_icon': 14, '.dropdown button .svg_icon': 7, '#main_button .dropdown .svg_icon': 9, '.palette_item:first .svg_icon': 15, '#fill_bg .svg_icon, #stroke_bg .svg_icon': 16, '.toolbar_button button .svg_icon': 16, '.stroke_tool div div .svg_icon': 20, '#tools_bottom label .svg_icon': 18 }, callback: function callback(icons) { return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { var tleft, minHeight, size; return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: $$d('.toolbar_button button > svg, .toolbar_button button > img').each(function () { $$d(this).parent().prepend(this); }); tleft = $$d('#tools_left'); if (tleft.length) { minHeight = tleft.offset().top + tleft.outerHeight(); } size = editor.pref('iconsize'); editor.setIconSize(size || ($$d(window).height() < minHeight ? 's' : 'm')); // Look for any missing flyout icons from plugins $$d('.tools_flyout').each(function () { var shower = $$d('#' + this.id + '_show'); var sel = shower.attr('data-curopt'); // Check if there's an icon here if (!shower.children('svg, img').length) { var clone = $$d(sel).children().clone(); if (clone.length) { clone[0].removeAttribute('style'); // Needed for Opera shower.append(clone); } } }); $$d('#svg_container')[0].style.visibility = 'visible'; _context5.next = 9; return editor.runCallbacks(); case 9: case "end": return _context5.stop(); } } }, _callee5); }))(); } }); } /** * @name module:SVGEditor.canvas * @type {module:svgcanvas.SvgCanvas} */ editor.canvas = svgCanvas = new SvgCanvas(document.getElementById('svgcanvas'), curConfig); var palette = [// Todo: Make into configuration item? '#000000', '#3f3f3f', '#7f7f7f', '#bfbfbf', '#ffffff', '#ff0000', '#ff7f00', '#ffff00', '#7fff00', '#00ff00', '#00ff7f', '#00ffff', '#007fff', '#0000ff', '#7f00ff', '#ff00ff', '#ff007f', '#7f0000', '#7f3f00', '#7f7f00', '#3f7f00', '#007f00', '#007f3f', '#007f7f', '#003f7f', '#00007f', '#3f007f', '#7f007f', '#7f003f', '#ffaaaa', '#ffd4aa', '#ffffaa', '#d4ffaa', '#aaffaa', '#aaffd4', '#aaffff', '#aad4ff', '#aaaaff', '#d4aaff', '#ffaaff', '#ffaad4'], modKey = isMac() ? 'meta+' : 'ctrl+', path = svgCanvas.pathActions, _svgCanvas = svgCanvas, undoMgr = _svgCanvas.undoMgr, workarea = $$d('#workarea'), canvMenu = $$d('#cmenu_canvas'), paintBox = { fill: null, stroke: null }; var resizeTimer, curScrollPos; var exportWindow = null, defaultImageURL = curConfig.imgPath + 'logo.png', zoomInIcon = 'crosshair', zoomOutIcon = 'crosshair', uiContext = 'toolbars'; // For external openers (function () { // let the opener know SVG Edit is ready (now that config is set up) var w = window.opener || window.parent; if (w) { try { /** * Triggered on a containing `document` (of `window.opener` * or `window.parent`) when the editor is loaded. * @event module:SVGEditor#event:svgEditorReadyEvent * @type {Event} * @property {true} bubbles * @property {true} cancelable */ /** * @name module:SVGEditor.svgEditorReadyEvent * @type {module:SVGEditor#event:svgEditorReadyEvent} */ var svgEditorReadyEvent = new w.CustomEvent('svgEditorReady', { bubbles: true, cancelable: true }); w.document.documentElement.dispatchEvent(svgEditorReadyEvent); } catch (e) {} } })(); /** * * @returns {void} */ var setSelectMode = function setSelectMode() { var curr = $$d('.tool_button_current'); if (curr.length && curr[0].id !== 'tool_select') { curr.removeClass('tool_button_current').addClass('tool_button'); $$d('#tool_select').addClass('tool_button_current').removeClass('tool_button'); $$d('#styleoverrides').text("\n #svgcanvas svg * {\n cursor: move;\n pointer-events: all;\n }\n #svgcanvas svg {\n cursor: default;\n }\n "); } svgCanvas.setMode('select'); workarea.css('cursor', 'auto'); }; // used to make the flyouts stay on the screen longer the very first time // const flyoutspeed = 1250; // Currently unused // let textBeingEntered = false; // Currently unused var origTitle = $$d('title:first').text(); // Make [1,2,5] array var rIntervals = []; for (var i = 0.1; i < 1e5; i *= 10) { rIntervals.push(i); rIntervals.push(2 * i); rIntervals.push(5 * i); } /** * This function highlights the layer passed in (by fading out the other layers). * If no layer is passed in, this function restores the other layers. * @param {string} [layerNameToHighlight] * @returns {void} */ var toggleHighlightLayer = function toggleHighlightLayer(layerNameToHighlight) { var i; var curNames = [], numLayers = svgCanvas.getCurrentDrawing().getNumLayers(); for (i = 0; i < numLayers; i++) { curNames[i] = svgCanvas.getCurrentDrawing().getLayerName(i); } if (layerNameToHighlight) { curNames.forEach(function (curName) { if (curName !== layerNameToHighlight) { svgCanvas.getCurrentDrawing().setLayerOpacity(curName, 0.5); } }); } else { curNames.forEach(function (curName) { svgCanvas.getCurrentDrawing().setLayerOpacity(curName, 1.0); }); } }; /** * * @returns {void} */ var populateLayers = function populateLayers() { svgCanvas.clearSelection(); var layerlist = $$d('#layerlist tbody').empty(); var selLayerNames = $$d('#selLayerNames').empty(); var drawing = svgCanvas.getCurrentDrawing(); var currentLayerName = drawing.getCurrentLayerName(); var icon = $$d.getSvgIcon('eye'); var layer = svgCanvas.getCurrentDrawing().getNumLayers(); // we get the layers in the reverse z-order (the layer rendered on top is listed first) while (layer--) { var _name3 = drawing.getLayerName(layer); var layerTr = $$d('<tr class="layer">').toggleClass('layersel', _name3 === currentLayerName); var layerVis = $$d('<td class="layervis">').toggleClass('layerinvis', !drawing.getLayerVisibility(_name3)); var layerName = $$d('<td class="layername">' + _name3 + '</td>'); layerlist.append(layerTr.append(layerVis, layerName)); selLayerNames.append('<option value="' + _name3 + '">' + _name3 + '</option>'); } if (icon !== undefined) { var copy = icon.clone(); $$d('td.layervis', layerlist).append(copy); $$d.resizeSvgIcons({ 'td.layervis .svg_icon': 14 }); } // handle selection of layer $$d('#layerlist td.layername').mouseup(function (evt) { $$d('#layerlist tr.layer').removeClass('layersel'); $$d(this.parentNode).addClass('layersel'); svgCanvas.setCurrentLayer(this.textContent); evt.preventDefault(); }).mouseover(function () { toggleHighlightLayer(this.textContent); }).mouseout(function () { toggleHighlightLayer(); }); $$d('#layerlist td.layervis').click(function () { var row = $$d(this.parentNode).prevAll().length; var name = $$d('#layerlist tr.layer:eq(' + row + ') td.layername').text(); var vis = $$d(this).hasClass('layerinvis'); svgCanvas.setLayerVisibility(name, vis); $$d(this).toggleClass('layerinvis'); }); // if there were too few rows, let's add a few to make it not so lonely var num = 5 - $$d('#layerlist tr.layer').size(); while (num-- > 0) { // TODO: there must a better way to do this layerlist.append('<tr><td style="color:white">_</td><td/></tr>'); } }; var editingsource = false; var origSource = ''; /** * @param {Event} [e] Not used. * @param {boolean} forSaving * @returns {void} */ var showSourceEditor = function showSourceEditor(e, forSaving) { if (editingsource) { return; } editingsource = true; origSource = svgCanvas.getSvgString(); $$d('#save_output_btns').toggle(Boolean(forSaving)); $$d('#tool_source_back').toggle(!forSaving); $$d('#svg_source_textarea').val(origSource); $$d('#svg_source_editor').fadeIn(); $$d('#svg_source_textarea').focus(); }; var selectedElement = null; var multiselected = false; /** * @param {boolean} editmode * @param {module:svgcanvas.SvgCanvas#event:selected} elems * @returns {void} */ var togglePathEditMode = function togglePathEditMode(editmode, elems) { $$d('#path_node_panel').toggle(editmode); $$d('#tools_bottom_2,#tools_bottom_3').toggle(!editmode); if (editmode) { // Change select icon $$d('.tool_button_current').removeClass('tool_button_current').addClass('tool_button'); $$d('#tool_select').addClass('tool_button_current').removeClass('tool_button'); setIcon('#tool_select', 'select_node'); multiselected = false; if (elems.length) { selectedElement = elems[0]; } } else { setTimeout(function () { setIcon('#tool_select', 'select'); }, 1000); } }; /** * @type {module:svgcanvas.EventHandler} * @param {external:Window} wind * @param {module:svgcanvas.SvgCanvas#event:saved} svg The SVG source * @listens module:svgcanvas.SvgCanvas#event:saved * @returns {void} */ var saveHandler = function saveHandler(wind, svg) { editor.showSaveWarning = false; // by default, we add the XML prolog back, systems integrating SVG-edit (wikis, CMSs) // can just provide their own custom save handler and might not want the XML prolog svg = '<?xml version="1.0"?>\n' + svg; // IE9 doesn't allow standalone Data URLs // https://connect.microsoft.com/IE/feedback/details/542600/data-uri-images-fail-when-loaded-by-themselves if (isIE()) { showSourceEditor(0, true); return; } // Since saving SVGs by opening a new window was removed in Chrome use artificial link-click // https://stackoverflow.com/questions/45603201/window-is-not-allowed-to-navigate-top-frame-navigations-to-data-urls var a = document.createElement('a'); a.href = 'data:image/svg+xml;base64,' + encode64(svg); a.download = 'icon.svg'; a.style.display = 'none'; document.body.append(a); // Need to append for Firefox a.click(); // Alert will only appear the first time saved OR the // first time the bug is encountered var done = editor.pref('save_notice_done'); if (done !== 'all') { var note = uiStrings$1.notification.saveFromBrowser.replace('%s', 'SVG'); // Check if FF and has <defs/> if (isGecko()) { if (svg.includes('<defs')) { // warning about Mozilla bug #308590 when applicable (seems to be fixed now in Feb 2013) note += '\n\n' + uiStrings$1.notification.defsFailOnSave; editor.pref('save_notice_done', 'all'); done = 'all'; } else { editor.pref('save_notice_done', 'part'); } } else { editor.pref('save_notice_done', 'all'); } if (done !== 'part') { $$d.alert(note); } } }; /** * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:exported} data * @listens module:svgcanvas.SvgCanvas#event:exported * @returns {void} */ var exportHandler = function exportHandler(win, data) { var issues = data.issues, exportWindowName = data.exportWindowName; exportWindow = window.open(blankPageObjectURL || '', exportWindowName); // A hack to get the window via JSON-able name without opening a new one if (!exportWindow || exportWindow.closed) { /* await */ $$d.alert(uiStrings$1.notification.popupWindowBlocked); return; } exportWindow.location.href = data.bloburl || data.datauri; var done = editor.pref('export_notice_done'); if (done !== 'all') { var note = uiStrings$1.notification.saveFromBrowser.replace('%s', data.type); // Check if there are issues if (issues.length) { var pre = "\n \u2022 "; note += '\n\n' + uiStrings$1.notification.noteTheseIssues + pre + issues.join(pre); } // Note that this will also prevent the notice even though new issues may appear later. // May want to find a way to deal with that without annoying the user editor.pref('export_notice_done', 'all'); exportWindow.alert(note); } }; /** * * @returns {void} */ var operaRepaint = function operaRepaint() { // Repaints canvas in Opera. Needed for stroke-dasharray change as well as fill change if (!window.opera) { return; } $$d('<p/>').hide().appendTo('body').remove(); }; /** * * @param {Element} opt * @param {boolean} changeElem * @returns {void} */ function setStrokeOpt(opt, changeElem) { var id = opt.id; var bits = id.split('_'); var _bits = _slicedToArray(bits, 2), pre = _bits[0], val = _bits[1]; if (changeElem) { svgCanvas.setStrokeAttr('stroke-' + pre, val); } operaRepaint(); setIcon('#cur_' + pre, id, 20); $$d(opt).addClass('current').siblings().removeClass('current'); } /** * This is a common function used when a tool has been clicked (chosen). * It does several common things: * - Removes the `tool_button_current` class from whatever tool currently has it. * - Hides any flyouts. * - Adds the `tool_button_current` class to the button passed in. * @function module:SVGEditor.toolButtonClick * @param {string|Element} button The DOM element or string selector representing the toolbar button * @param {boolean} noHiding Whether not to hide any flyouts * @returns {boolean} Whether the button was disabled or not */ var toolButtonClick = editor.toolButtonClick = function (button, noHiding) { if ($$d(button).hasClass('disabled')) { return false; } if ($$d(button).parent().hasClass('tools_flyout')) { return true; } var fadeFlyouts = 'normal'; if (!noHiding) { $$d('.tools_flyout').fadeOut(fadeFlyouts); } $$d('#styleoverrides').text(''); workarea.css('cursor', 'auto'); $$d('.tool_button_current').removeClass('tool_button_current').addClass('tool_button'); $$d(button).addClass('tool_button_current').removeClass('tool_button'); return true; }; /** * Unless the select toolbar button is disabled, sets the button * and sets the select mode and cursor styles. * @function module:SVGEditor.clickSelect * @returns {void} */ var clickSelect = editor.clickSelect = function () { if (toolButtonClick('#tool_select')) { svgCanvas.setMode('select'); $$d('#styleoverrides').text("\n #svgcanvas svg * {\n cursor: move;\n pointer-events: all;\n }\n #svgcanvas svg {\n cursor: default;\n }\n "); } }; /** * Set a selected image's URL. * @function module:SVGEditor.setImageURL * @param {string} url * @returns {void} */ var setImageURL = editor.setImageURL = function (url) { if (!url) { url = defaultImageURL; } svgCanvas.setImageURL(url); $$d('#image_url').val(url); if (url.startsWith('data:')) { // data URI found $$d('#image_url').hide(); $$d('#change_image_url').show(); } else { // regular URL svgCanvas.embedImage(url, function (dataURI) { // Couldn't embed, so show warning $$d('#url_notice').toggle(!dataURI); defaultImageURL = url; }); $$d('#image_url').show(); $$d('#change_image_url').hide(); } }; /** * * @param {string} color * @param {string} url * @returns {void} */ function setBackground(color, url) { // if (color == editor.pref('bkgd_color') && url == editor.pref('bkgd_url')) { return; } editor.pref('bkgd_color', color); editor.pref('bkgd_url', url, true); // This should be done in svgcanvas.js for the borderRect fill svgCanvas.setBackground(color, url); } /** * @param {PlainObject} [opts={}] * @param {boolean} [opts.cancelDeletes=false}] * @returns {Promise<void>} Resolves to `undefined` */ function promptImgURL() { return _promptImgURL.apply(this, arguments); } /** * @param {Element} elem * @returns {void} */ function _promptImgURL() { _promptImgURL = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee19() { var _ref27, _ref27$cancelDeletes, cancelDeletes, curhref, url, _args19 = arguments; return regeneratorRuntime.wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: _ref27 = _args19.length > 0 && _args19[0] !== undefined ? _args19[0] : {}, _ref27$cancelDeletes = _ref27.cancelDeletes, cancelDeletes = _ref27$cancelDeletes === void 0 ? false : _ref27$cancelDeletes; curhref = svgCanvas.getHref(selectedElement); curhref = curhref.startsWith('data:') ? '' : curhref; _context19.next = 5; return $$d.prompt(uiStrings$1.notification.enterNewImgURL, curhref); case 5: url = _context19.sent; if (url) { setImageURL(url); } else if (cancelDeletes) { svgCanvas.deleteSelectedElements(); } case 7: case "end": return _context19.stop(); } } }, _callee19); })); return _promptImgURL.apply(this, arguments); } var setInputWidth = function setInputWidth(elem) { var w = Math.min(Math.max(12 + elem.value.length * 6, 50), 300); $$d(elem).width(w); }; /** * * @param {HTMLDivElement} [scanvas] * @param {Float} [zoom] * @returns {void} */ function updateRulers(scanvas, zoom) { if (!zoom) { zoom = svgCanvas.getZoom(); } if (!scanvas) { scanvas = $$d('#svgcanvas'); } var d, i; var limit = 30000; var contentElem = svgCanvas.getContentElem(); var units = getTypeMap(); var unit = units[curConfig.baseUnit]; // 1 = 1px // draw x ruler then y ruler for (d = 0; d < 2; d++) { var isX = d === 0; var dim = isX ? 'x' : 'y'; var lentype = isX ? 'width' : 'height'; var contentDim = Number(contentElem.getAttribute(dim)); var $hcanvOrig = $$d('#ruler_' + dim + ' canvas:first'); // Bit of a hack to fully clear the canvas in Safari & IE9 var $hcanv = $hcanvOrig.clone(); $hcanvOrig.replaceWith($hcanv); var hcanv = $hcanv[0]; // Set the canvas size to the width of the container var rulerLen = scanvas[lentype](); var totalLen = rulerLen; hcanv.parentNode.style[lentype] = totalLen + 'px'; var ctx = hcanv.getContext('2d'); var ctxArr = void 0, num = void 0, ctxArrNum = void 0; ctx.fillStyle = 'rgb(200,0,0)'; ctx.fillRect(0, 0, hcanv.width, hcanv.height); // Remove any existing canvasses $hcanv.siblings().remove(); // Create multiple canvases when necessary (due to browser limits) if (rulerLen >= limit) { ctxArrNum = Number.parseInt(rulerLen / limit) + 1; ctxArr = []; ctxArr[0] = ctx; var copy = void 0; for (i = 1; i < ctxArrNum; i++) { hcanv[lentype] = limit; copy = hcanv.cloneNode(true); hcanv.parentNode.append(copy); ctxArr[i] = copy.getContext('2d'); } copy[lentype] = rulerLen % limit; // set copy width to last rulerLen = limit; } hcanv[lentype] = rulerLen; var uMulti = unit * zoom; // Calculate the main number interval var rawM = 50 / uMulti; var multi = 1; for (i = 0; i < rIntervals.length; i++) { num = rIntervals[i]; multi = num; if (rawM <= num) { break; } } var bigInt = multi * uMulti; ctx.font = '9px sans-serif'; var rulerD = contentDim / uMulti % multi * uMulti; var labelPos = rulerD - bigInt; // draw big intervals var ctxNum = 0; while (rulerD < totalLen) { labelPos += bigInt; // const realD = rulerD - contentDim; // Currently unused var curD = Math.round(rulerD) + 0.5; if (isX) { ctx.moveTo(curD, 15); ctx.lineTo(curD, 0); } else { ctx.moveTo(15, curD); ctx.lineTo(0, curD); } num = (labelPos - contentDim) / uMulti; var label = void 0; if (multi >= 1) { label = Math.round(num); } else { var decs = String(multi).split('.')[1].length; label = num.toFixed(decs); } // Change 1000s to Ks if (label !== 0 && label !== 1000 && label % 1000 === 0) { label = label / 1000 + 'K'; } if (isX) { ctx.fillText(label, rulerD + 2, 8); } else { // draw label vertically var _str = String(label).split(''); for (i = 0; i < _str.length; i++) { ctx.fillText(_str[i], 1, rulerD + 9 + i * 9); } } var part = bigInt / 10; // draw the small intervals for (i = 1; i < 10; i++) { var subD = Math.round(rulerD + part * i) + 0.5; if (ctxArr && subD > rulerLen) { ctxNum++; ctx.stroke(); if (ctxNum >= ctxArrNum) { i = 10; rulerD = totalLen; continue; } ctx = ctxArr[ctxNum]; rulerD -= limit; subD = Math.round(rulerD + part * i) + 0.5; } // odd lines are slighly longer var lineNum = i % 2 ? 12 : 10; if (isX) { ctx.moveTo(subD, 15); ctx.lineTo(subD, lineNum); } else { ctx.moveTo(15, subD); ctx.lineTo(lineNum, subD); } } rulerD += bigInt; } ctx.strokeStyle = '#000'; ctx.stroke(); } } /** * @function module:SVGEditor.updateCanvas * @param {boolean} center * @param {module:math.XYObject} newCtr * @returns {void} */ var updateCanvas = editor.updateCanvas = function (center, newCtr) { var zoom = svgCanvas.getZoom(); var wArea = workarea; var cnvs = $$d('#svgcanvas'); var w = workarea.width(), h = workarea.height(); var wOrig = w, hOrig = h; var oldCtr = { x: wArea[0].scrollLeft + wOrig / 2, y: wArea[0].scrollTop + hOrig / 2 }; var multi = curConfig.canvas_expansion; w = Math.max(wOrig, svgCanvas.contentW * zoom * multi); h = Math.max(hOrig, svgCanvas.contentH * zoom * multi); if (w === wOrig && h === hOrig) { workarea.css('overflow', 'hidden'); } else { workarea.css('overflow', 'scroll'); } var oldCanY = cnvs.height() / 2; var oldCanX = cnvs.width() / 2; cnvs.width(w).height(h); var newCanY = h / 2; var newCanX = w / 2; var offset = svgCanvas.updateCanvas(w, h); var ratio = newCanX / oldCanX; var scrollX = w / 2 - wOrig / 2; // eslint-disable-line no-shadow var scrollY = h / 2 - hOrig / 2; // eslint-disable-line no-shadow if (!newCtr) { var oldDistX = oldCtr.x - oldCanX; var newX = newCanX + oldDistX * ratio; var oldDistY = oldCtr.y - oldCanY; var newY = newCanY + oldDistY * ratio; newCtr = { x: newX, y: newY }; } else { newCtr.x += offset.x; newCtr.y += offset.y; } if (center) { // Go to top-left for larger documents if (svgCanvas.contentW > wArea.width()) { // Top-left workarea[0].scrollLeft = offset.x - 10; workarea[0].scrollTop = offset.y - 10; } else { // Center wArea[0].scrollLeft = scrollX; wArea[0].scrollTop = scrollY; } } else { wArea[0].scrollLeft = newCtr.x - wOrig / 2; wArea[0].scrollTop = newCtr.y - hOrig / 2; } if (curConfig.showRulers) { updateRulers(cnvs, zoom); workarea.scroll(); } if (urldata.storagePrompt !== true && editor.storagePromptState === 'ignore') { $$d('#dialog_box').hide(); } }; /** * @fires module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate * @returns {void} */ var updateToolButtonState = function updateToolButtonState() { var bNoFill = svgCanvas.getColor('fill') === 'none'; var bNoStroke = svgCanvas.getColor('stroke') === 'none'; var buttonsNeedingStroke = ['#tool_fhpath', '#tool_line']; var buttonsNeedingFillAndStroke = ['#tools_rect .tool_button', '#tools_ellipse .tool_button', '#tool_text', '#tool_path']; if (bNoStroke) { buttonsNeedingStroke.forEach(function (btn) { if ($$d(btn).hasClass('tool_button_current')) { clickSelect(); } $$d(btn).addClass('disabled'); }); } else { buttonsNeedingStroke.forEach(function (btn) { $$d(btn).removeClass('disabled'); }); } if (bNoStroke && bNoFill) { buttonsNeedingFillAndStroke.forEach(function (btn) { if ($$d(btn).hasClass('tool_button_current')) { clickSelect(); } $$d(btn).addClass('disabled'); }); } else { buttonsNeedingFillAndStroke.forEach(function (btn) { $$d(btn).removeClass('disabled'); }); } svgCanvas.runExtensions('toolButtonStateUpdate', /** @type {module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate} */ { nofill: bNoFill, nostroke: bNoStroke }); // Disable flyouts if all inside are disabled $$d('.tools_flyout').each(function () { var shower = $$d('#' + this.id + '_show'); var hasEnabled = false; $$d(this).children().each(function () { if (!$$d(this).hasClass('disabled')) { hasEnabled = true; } }); shower.toggleClass('disabled', !hasEnabled); }); operaRepaint(); }; /** * Updates the toolbar (colors, opacity, etc) based on the selected element. * This function also updates the opacity and id elements that are in the * context panel. * @returns {void} */ var updateToolbar = function updateToolbar() { var i, len; if (!isNullish(selectedElement)) { switch (selectedElement.tagName) { case 'use': case 'image': case 'foreignObject': break; case 'g': case 'a': { // Look for common styles var childs = selectedElement.getElementsByTagName('*'); var gWidth = null; for (i = 0, len = childs.length; i < len; i++) { var swidth = childs[i].getAttribute('stroke-width'); if (i === 0) { gWidth = swidth; } else if (gWidth !== swidth) { gWidth = null; } } $$d('#stroke_width').val(gWidth === null ? '' : gWidth); paintBox.fill.update(true); paintBox.stroke.update(true); break; } default: { paintBox.fill.update(true); paintBox.stroke.update(true); $$d('#stroke_width').val(selectedElement.getAttribute('stroke-width') || 1); $$d('#stroke_style').val(selectedElement.getAttribute('stroke-dasharray') || 'none'); var attr = selectedElement.getAttribute('stroke-linejoin') || 'miter'; if ($$d('#linejoin_' + attr).length) { setStrokeOpt($$d('#linejoin_' + attr)[0]); } attr = selectedElement.getAttribute('stroke-linecap') || 'butt'; if ($$d('#linecap_' + attr).length) { setStrokeOpt($$d('#linecap_' + attr)[0]); } } } } // All elements including image and group have opacity if (!isNullish(selectedElement)) { var opacPerc = (selectedElement.getAttribute('opacity') || 1.0) * 100; $$d('#group_opacity').val(opacPerc); $$d('#opac_slider').slider('option', 'value', opacPerc); $$d('#elem_id').val(selectedElement.id); $$d('#elem_class').val(selectedElement.getAttribute('class')); } updateToolButtonState(); }; /** * Updates the context panel tools based on the selected element. * @returns {void} */ var updateContextPanel = function updateContextPanel() { var elem = selectedElement; // If element has just been deleted, consider it null if (!isNullish(elem) && !elem.parentNode) { elem = null; } var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName(); var currentMode = svgCanvas.getMode(); var unit = curConfig.baseUnit !== 'px' ? curConfig.baseUnit : null; var isNode = currentMode === 'pathedit'; // elem ? (elem.id && elem.id.startsWith('pathpointgrip')) : false; var menuItems = $$d('#cmenu_canvas li'); $$d('#selected_panel, #multiselected_panel, #g_panel, #rect_panel, #circle_panel,' + '#ellipse_panel, #line_panel, #text_panel, #image_panel, #container_panel,' + ' #use_panel, #a_panel').hide(); if (!isNullish(elem)) { var elname = elem.nodeName; // If this is a link with no transform and one child, pretend // its child is selected // if (elname === 'a') { // && !$(elem).attr('transform')) { // elem = elem.firstChild; // } var angle = svgCanvas.getRotationAngle(elem); $$d('#angle').val(angle); var blurval = svgCanvas.getBlur(elem); $$d('#blur').val(blurval); $$d('#blur_slider').slider('option', 'value', blurval); if (svgCanvas.addedNew) { if (elname === 'image' && svgCanvas.getMode() === 'image') { // Prompt for URL if not a data URL if (!svgCanvas.getHref(elem).startsWith('data:')) { /* await */ promptImgURL({ cancelDeletes: true }); } } /* else if (elname == 'text') { // TODO: Do something here for new text } */ } if (!isNode && currentMode !== 'pathedit') { $$d('#selected_panel').show(); // Elements in this array already have coord fields if (['line', 'circle', 'ellipse'].includes(elname)) { $$d('#xy_panel').hide(); } else { var x, y; // Get BBox vals for g, polyline and path if (['g', 'polyline', 'path'].includes(elname)) { var bb = svgCanvas.getStrokedBBox([elem]); if (bb) { x = bb.x; y = bb.y; } } else { x = elem.getAttribute('x'); y = elem.getAttribute('y'); } if (unit) { x = convertUnit(x); y = convertUnit(y); } $$d('#selected_x').val(x || 0); $$d('#selected_y').val(y || 0); $$d('#xy_panel').show(); } // Elements in this array cannot be converted to a path var noPath = !['image', 'text', 'path', 'g', 'use'].includes(elname); $$d('#tool_topath').toggle(noPath); $$d('#tool_reorient').toggle(elname === 'path'); $$d('#tool_reorient').toggleClass('disabled', angle === 0); } else { var point = path.getNodePoint(); $$d('#tool_add_subpath').removeClass('push_button_pressed').addClass('tool_button'); $$d('#tool_node_delete').toggleClass('disabled', !path.canDeleteNodes); // Show open/close button based on selected point setIcon('#tool_openclose_path', path.closed_subpath ? 'open_path' : 'close_path'); if (point) { var segType = $$d('#seg_type'); if (unit) { point.x = convertUnit(point.x); point.y = convertUnit(point.y); } $$d('#path_node_x').val(point.x); $$d('#path_node_y').val(point.y); if (point.type) { segType.val(point.type).removeAttr('disabled'); } else { segType.val(4).attr('disabled', 'disabled'); } } return; } // update contextual tools here var panels = { g: [], a: [], rect: ['rx', 'width', 'height'], image: ['width', 'height'], circle: ['cx', 'cy', 'r'], ellipse: ['cx', 'cy', 'rx', 'ry'], line: ['x1', 'y1', 'x2', 'y2'], text: [], use: [] }; var _elem = elem, tagName = _elem.tagName; // if ($(elem).data('gsvg')) { // $('#g_panel').show(); // } var linkHref = null; if (tagName === 'a') { linkHref = svgCanvas.getHref(elem); $$d('#g_panel').show(); } if (elem.parentNode.tagName === 'a') { if (!$$d(elem).siblings().length) { $$d('#a_panel').show(); linkHref = svgCanvas.getHref(elem.parentNode); } } // Hide/show the make_link buttons $$d('#tool_make_link, #tool_make_link').toggle(!linkHref); if (linkHref) { $$d('#link_url').val(linkHref); } if (panels[tagName]) { var curPanel = panels[tagName]; $$d('#' + tagName + '_panel').show(); $$d.each(curPanel, function (i, item) { var attrVal = elem.getAttribute(item); if (curConfig.baseUnit !== 'px' && elem[item]) { var bv = elem[item].baseVal.value; attrVal = convertUnit(bv); } $$d('#' + tagName + '_' + item).val(attrVal || 0); }); if (tagName === 'text') { $$d('#text_panel').css('display', 'inline'); $$d('#tool_font_size').css('display', 'inline'); if (svgCanvas.getItalic()) { $$d('#tool_italic').addClass('push_button_pressed').removeClass('tool_button'); } else { $$d('#tool_italic').removeClass('push_button_pressed').addClass('tool_button'); } if (svgCanvas.getBold()) { $$d('#tool_bold').addClass('push_button_pressed').removeClass('tool_button'); } else { $$d('#tool_bold').removeClass('push_button_pressed').addClass('tool_button'); } $$d('#font_family').val(elem.getAttribute('font-family')); $$d('#font_size').val(elem.getAttribute('font-size')); $$d('#text').val(elem.textContent); if (svgCanvas.addedNew) { // Timeout needed for IE9 setTimeout(function () { $$d('#text').focus().select(); }, 100); } // text } else if (tagName === 'image' && svgCanvas.getMode() === 'image') { setImageURL(svgCanvas.getHref(elem)); // image } else if (tagName === 'g' || tagName === 'use') { $$d('#container_panel').show(); var title = svgCanvas.getTitle(); var label = $$d('#g_title')[0]; label.value = title; setInputWidth(label); $$d('#g_title').prop('disabled', tagName === 'use'); } } menuItems[(tagName === 'g' ? 'en' : 'dis') + 'ableContextMenuItems']('#ungroup'); menuItems[(tagName === 'g' || !multiselected ? 'dis' : 'en') + 'ableContextMenuItems']('#group'); // if (!Utils.isNullish(elem)) } else if (multiselected) { $$d('#multiselected_panel').show(); menuItems.enableContextMenuItems('#group').disableContextMenuItems('#ungroup'); } else { menuItems.disableContextMenuItems('#delete,#cut,#copy,#group,#ungroup,#move_front,#move_up,#move_down,#move_back'); } // update history buttons $$d('#tool_undo').toggleClass('disabled', undoMgr.getUndoStackSize() === 0); $$d('#tool_redo').toggleClass('disabled', undoMgr.getRedoStackSize() === 0); svgCanvas.addedNew = false; if (elem && !isNode || multiselected) { // update the selected elements' layer $$d('#selLayerNames').removeAttr('disabled').val(currentLayerName); // Enable regular menu options canvMenu.enableContextMenuItems('#delete,#cut,#copy,#move_front,#move_up,#move_down,#move_back'); } else { $$d('#selLayerNames').attr('disabled', 'disabled'); } }; /** * * @returns {void} */ var updateWireFrame = function updateWireFrame() { // Test support if (supportsNonSS) { return; } var rule = "\n #workarea.wireframe #svgcontent * {\n stroke-width: ".concat(1 / svgCanvas.getZoom(), "px;\n }\n "); $$d('#wireframe_rules').text(workarea.hasClass('wireframe') ? rule : ''); }; var curContext = ''; /** * @param {string} [title=svgCanvas.getDocumentTitle()] * @returns {void} */ var updateTitle = function updateTitle(title) { title = title || svgCanvas.getDocumentTitle(); var newTitle = origTitle + (title ? ': ' + title : ''); // Remove title update with current context info, isn't really necessary // if (curContext) { // new_title = new_title + curContext; // } $$d('title:first').text(newTitle); }; // called when we've selected a different element /** * * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:selected} elems Array of elements that were selected * @listens module:svgcanvas.SvgCanvas#event:selected * @fires module:svgcanvas.SvgCanvas#event:ext_selectedChanged * @returns {void} */ var selectedChanged = function selectedChanged(win, elems) { var mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } var isNode = mode === 'pathedit'; // if elems[1] is present, then we have more than one element selectedElement = elems.length === 1 || isNullish(elems[1]) ? elems[0] : null; multiselected = elems.length >= 2 && !isNullish(elems[1]); if (!isNullish(selectedElement)) { // unless we're already in always set the mode of the editor to select because // upon creation of a text element the editor is switched into // select mode and this event fires - we need our UI to be in sync if (!isNode) { updateToolbar(); } } // if (!Utils.isNullish(elem)) // Deal with pathedit mode togglePathEditMode(isNode, elems); updateContextPanel(); svgCanvas.runExtensions('selectedChanged', /** @type {module:svgcanvas.SvgCanvas#event:ext_selectedChanged} */ { elems: elems, selectedElement: selectedElement, multiselected: multiselected }); }; // Call when part of element is in process of changing, generally // on mousemove actions like rotate, move, etc. /** * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:transition} elems * @listens module:svgcanvas.SvgCanvas#event:transition * @fires module:svgcanvas.SvgCanvas#event:ext_elementTransition * @returns {void} */ var elementTransition = function elementTransition(win, elems) { var mode = svgCanvas.getMode(); var elem = elems[0]; if (!elem) { return; } multiselected = elems.length >= 2 && !isNullish(elems[1]); // Only updating fields for single elements for now if (!multiselected) { switch (mode) { case 'rotate': { var ang = svgCanvas.getRotationAngle(elem); $$d('#angle').val(ang); $$d('#tool_reorient').toggleClass('disabled', ang === 0); break; // TODO: Update values that change on move/resize, etc // } case 'select': { // } case 'resize': { // break; // } } } } svgCanvas.runExtensions('elementTransition', /** @type {module:svgcanvas.SvgCanvas#event:ext_elementTransition} */ { elems: elems }); }; /** * Test whether an element is a layer or not. * @param {SVGGElement} elem - The SVGGElement to test. * @returns {boolean} True if the element is a layer */ function isLayer(elem) { return elem && elem.tagName === 'g' && Layer.CLASS_REGEX.test(elem.getAttribute('class')); } // called when any element has changed /** * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:changed} elems * @listens module:svgcanvas.SvgCanvas#event:changed * @fires module:svgcanvas.SvgCanvas#event:ext_elementChanged * @returns {void} */ var elementChanged = function elementChanged(win, elems) { var mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } elems.forEach(function (elem) { var isSvgElem = elem && elem.tagName === 'svg'; if (isSvgElem || isLayer(elem)) { populateLayers(); // if the element changed was the svg, then it could be a resolution change if (isSvgElem) { updateCanvas(); } // Update selectedElement if element is no longer part of the image. // This occurs for the text elements in Firefox } else if (elem && selectedElement && isNullish(selectedElement.parentNode)) { // || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why selectedElement = elem; } }); editor.showSaveWarning = true; // we update the contextual panel with potentially new // positional/sizing information (we DON'T want to update the // toolbar here as that creates an infinite loop) // also this updates the history buttons // we tell it to skip focusing the text control if the // text element was previously in focus updateContextPanel(); // In the event a gradient was flipped: if (selectedElement && mode === 'select') { paintBox.fill.update(); paintBox.stroke.update(); } svgCanvas.runExtensions('elementChanged', /** @type {module:svgcanvas.SvgCanvas#event:ext_elementChanged} */ { elems: elems }); }; /** * @returns {void} */ var zoomDone = function zoomDone() { updateWireFrame(); // updateCanvas(); // necessary? }; /** * @typedef {PlainObject} module:SVGEditor.BBoxObjectWithFactor (like `DOMRect`) * @property {Float} x * @property {Float} y * @property {Float} width * @property {Float} height * @property {Float} [factor] Needed if width or height are 0 * @property {Float} [zoom] * @see module:svgcanvas.SvgCanvas#event:zoomed */ /** * @function module:svgcanvas.SvgCanvas#zoomChanged * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:zoomed} bbox * @param {boolean} autoCenter * @listens module:svgcanvas.SvgCanvas#event:zoomed * @returns {void} */ var zoomChanged = svgCanvas.zoomChanged = function (win, bbox, autoCenter) { var scrbar = 15, // res = svgCanvas.getResolution(), // Currently unused wArea = workarea; // const canvasPos = $('#svgcanvas').position(); // Currently unused var zInfo = svgCanvas.setBBoxZoom(bbox, wArea.width() - scrbar, wArea.height() - scrbar); if (!zInfo) { return; } var zoomlevel = zInfo.zoom, bb = zInfo.bbox; if (zoomlevel < 0.001) { changeZoom({ value: 0.1 }); return; } $$d('#zoom').val((zoomlevel * 100).toFixed(1)); if (autoCenter) { updateCanvas(); } else { updateCanvas(false, { x: bb.x * zoomlevel + bb.width * zoomlevel / 2, y: bb.y * zoomlevel + bb.height * zoomlevel / 2 }); } if (svgCanvas.getMode() === 'zoom' && bb.width) { // Go to select if a zoom box was drawn setSelectMode(); } zoomDone(); }; /** * @type {module:jQuerySpinButton.ValueCallback} */ var changeZoom = function changeZoom(ctl) { var zoomlevel = ctl.value / 100; if (zoomlevel < 0.001) { ctl.value = 0.1; return; } var zoom = svgCanvas.getZoom(); var wArea = workarea; zoomChanged(window, { width: 0, height: 0, // center pt of scroll position x: (wArea[0].scrollLeft + wArea.width() / 2) / zoom, y: (wArea[0].scrollTop + wArea.height() / 2) / zoom, zoom: zoomlevel }, true); }; $$d('#cur_context_panel').delegate('a', 'click', function () { var link = $$d(this); if (link.attr('data-root')) { svgCanvas.leaveContext(); } else { svgCanvas.setContext(link.text()); } svgCanvas.clearSelection(); return false; }); /** * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:contextset} context * @listens module:svgcanvas.SvgCanvas#event:contextset * @returns {void} */ var contextChanged = function contextChanged(win, context) { var linkStr = ''; if (context) { var _str2 = ''; linkStr = '<a href="#" data-root="y">' + svgCanvas.getCurrentDrawing().getCurrentLayerName() + '</a>'; $$d(context).parentsUntil('#svgcontent > g').andSelf().each(function () { if (this.id) { _str2 += ' > ' + this.id; if (this !== context) { linkStr += ' > <a href="#">' + this.id + '</a>'; } else { linkStr += ' > ' + this.id; } } }); curContext = _str2; } else { curContext = null; } $$d('#cur_context_panel').toggle(Boolean(context)).html(linkStr); updateTitle(); }; /** * Makes sure the current selected paint is available to work with. * @returns {void} */ var prepPaints = function prepPaints() { paintBox.fill.prep(); paintBox.stroke.prep(); }; var flyoutFuncs = {}; /** * * @returns {void} */ var setFlyoutTitles = function setFlyoutTitles() { $$d('.tools_flyout').each(function () { var shower = $$d('#' + this.id + '_show'); if (shower.data('isLibrary')) { return; } var tooltips = $$d(this).children().map(function () { return this.title; }).get(); shower[0].title = tooltips.join(' / '); }); }; var allHolders = {}; /** * @param {PlainObject<string, module:SVGEditor.ToolButton>} holders Key is a selector * @returns {void} */ var setupFlyouts = function setupFlyouts(holders) { $$d.each(holders, function (holdSel, btnOpts) { var _allHolders$holdSel; if (!allHolders[holdSel]) { allHolders[holdSel] = []; } (_allHolders$holdSel = allHolders[holdSel]).push.apply(_allHolders$holdSel, _toConsumableArray(btnOpts)); var buttons = $$d(holdSel).children().not('.tool_button_evt_handled'); var showSel = holdSel + '_show'; var shower = $$d(showSel); var def = false; buttons.addClass('tool_button tool_button_evt_handled').unbind('click mousedown mouseup') // may not be necessary .each(function () { // Get this button's options var idSel = '#' + this.getAttribute('id'); var _Object$entries$find = Object.entries(btnOpts).find(function (_ref7) { var _ref8 = _slicedToArray(_ref7, 2), _ = _ref8[0], sel = _ref8[1].sel; return sel === idSel; }), _Object$entries$find2 = _slicedToArray(_Object$entries$find, 2), i = _Object$entries$find2[0], opts = _Object$entries$find2[1]; // Remember the function that goes with this ID flyoutFuncs[opts.sel] = opts.fn; if (opts.isDefault) { def = i; } /** * Clicking the icon in flyout should set this set's icon. * @param {Event} ev * @returns {boolean} */ var flyoutAction = function flyoutAction(ev) { var options = opts; // Find the currently selected tool if comes from keystroke if (ev.type === 'keydown') { var flyoutIsSelected = $$d(options.parent + '_show').hasClass('tool_button_current'); var currentOperation = $$d(options.parent + '_show').attr('data-curopt'); Object.entries(holders[opts.parent]).some(function (_ref9) { var _ref10 = _slicedToArray(_ref9, 2), j = _ref10[0], tool = _ref10[1]; if (tool.sel !== currentOperation) { return false; } if (!ev.shiftKey || !flyoutIsSelected) { options = tool; } else { // If flyout is selected, allow shift key to iterate through subitems j = Number.parseInt(j); // Use `allHolders` to include both extension `includeWith` and toolbarButtons options = allHolders[opts.parent][j + 1] || holders[opts.parent][0]; } return true; }); } if ($$d(this).hasClass('disabled')) { return false; } if (toolButtonClick(showSel)) { options.fn(); } var icon; if (options.icon) { icon = $$d.getSvgIcon(options.icon, true); } else { icon = $$d(options.sel).children().eq(0).clone(); } icon[0].setAttribute('width', shower.width()); icon[0].setAttribute('height', shower.height()); shower.children(':not(.flyout_arrow_horiz)').remove(); shower.append(icon).attr('data-curopt', options.sel); // This sets the current mode return true; }; $$d(this).mouseup(flyoutAction); if (opts.key) { $$d(document).bind('keydown', opts.key[0] + ' shift+' + opts.key[0], flyoutAction); } return true; }); if (def) { shower.attr('data-curopt', btnOpts[def].sel); } else if (!shower.attr('data-curopt')) { // Set first as default shower.attr('data-curopt', btnOpts[0].sel); } var timer; // Clicking the "show" icon should set the current mode shower.mousedown(function (evt) { if (shower.hasClass('disabled')) { return false; } var holder = $$d(holdSel); var pos = $$d(showSel).position(); var l = pos.left + 34; var w = holder.width() * -1; var time = holder.data('shown_popop') ? 200 : 0; timer = setTimeout(function () { // Show corresponding menu if (!shower.data('isLibrary')) { holder.css('left', w).show().animate({ left: l }, 150); } else { holder.css('left', l).show(); } holder.data('shown_popop', true); }, time); evt.preventDefault(); return true; }).mouseup(function (evt) { clearTimeout(timer); var opt = $$d(this).attr('data-curopt'); // Is library and popped up, so do nothing if (shower.data('isLibrary') && $$d(showSel.replace('_show', '')).is(':visible')) { toolButtonClick(showSel, true); return; } if (toolButtonClick(showSel) && flyoutFuncs[opt]) { flyoutFuncs[opt](); } }); // $('#tools_rect').mouseleave(function () { $('#tools_rect').fadeOut(); }); }); setFlyoutTitles(); setFlyoutPositions(); }; /** * @param {string} id * @param {external:jQuery} child * @returns {external:jQuery} */ var makeFlyoutHolder = function makeFlyoutHolder(id, child) { var div = $$d('<div>', { "class": 'tools_flyout', id: id }).appendTo('#svg_editor').append(child); return div; }; /** * @param {string} elemSel * @param {string} listSel * @param {external:jQuery.Function} callback * @param {PlainObject} opts * @param {boolean} opts.dropUp * @param {boolean} opts.seticon * @param {boolean} opts.multiclick * @todo Combine this with `addDropDown` or find other way to optimize. * @returns {void} */ var addAltDropDown = function addAltDropDown(elemSel, listSel, callback, opts) { var button = $$d(elemSel); var dropUp = opts.dropUp; var list = $$d(listSel); if (dropUp) { $$d(elemSel).addClass('dropup'); } list.find('li').bind('mouseup', function () { if (opts.seticon) { setIcon('#cur_' + button[0].id, $$d(this).children()); $$d(this).addClass('current').siblings().removeClass('current'); } for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } callback.apply.apply(callback, [this].concat(args)); }); var onButton = false; $$d(window).mouseup(function (evt) { if (!onButton) { button.removeClass('down'); list.hide(); list.css({ top: 0, left: 0 }); } onButton = false; }); // const height = list.height(); // Currently unused button.bind('mousedown', function () { var off = button.offset(); if (dropUp) { off.top -= list.height(); off.left += 8; } else { off.top += button.height(); } list.offset(off); if (!button.hasClass('down')) { list.show(); onButton = true; } else { // CSS position must be reset for Webkit list.hide(); list.css({ top: 0, left: 0 }); } button.toggleClass('down'); }).hover(function () { onButton = true; }).mouseout(function () { onButton = false; }); if (opts.multiclick) { list.mousedown(function () { onButton = true; }); } }; var extsPreLang = []; /** * @param {external:Window} win * @param {module:svgcanvas.SvgCanvas#event:extension_added} ext * @listens module:svgcanvas.SvgCanvas#event:extension_added * @returns {Promise<void>|void} Resolves to `undefined` */ var extAdded = /*#__PURE__*/function () { var _ref11 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(win, ext) { var cbCalled, resizeDone, lang, prepResize, runCallback, btnSelects, svgicons, fallbackObj, altsObj, placementObj, holders; return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: prepResize = function _prepResize() { if (resizeTimer) { clearTimeout(resizeTimer); resizeTimer = null; } if (!resizeDone) { resizeTimer = setTimeout(function () { resizeDone = true; setIconSize(editor.pref('iconsize')); }, 50); } }; if (ext) { _context6.next = 3; break; } return _context6.abrupt("return", undefined); case 3: cbCalled = false; resizeDone = false; if (!ext.langReady) { _context6.next = 14; break; } if (!editor.langChanged) { _context6.next = 13; break; } // We check for this since the "lang" pref could have been set by storage lang = editor.pref('lang'); _context6.next = 10; return ext.langReady({ lang: lang, uiStrings: uiStrings$1, importLocale: getImportLocale({ defaultLang: lang, defaultName: ext.name }) }); case 10: loadedExtensionNames.push(ext.name); _context6.next = 14; break; case 13: extsPreLang.push(ext); case 14: /** * * @returns {void} */ runCallback = function runCallback() { if (ext.callback && !cbCalled) { cbCalled = true; ext.callback.call(editor); } }; btnSelects = []; /** * @typedef {PlainObject} module:SVGEditor.ContextTool * @property {string} panel The ID of the existing panel to which the tool is being added. Required. * @property {string} id The ID of the actual tool element. Required. * @property {PlainObject<string, external:jQuery.Function>|PlainObject<"change", external:jQuery.Function>} events DOM event names keyed to associated functions. Example: `{change () { alert('Option was changed') } }`. "change" event is one specifically handled for the "button-select" type. Required. * @property {string} title The tooltip text that will appear when the user hovers over the tool. Required. * @property {"tool_button"|"select"|"button-select"|"input"|string} type The type of tool being added. Expected. * @property {PlainObject<string, string>} [options] List of options and their labels for select tools. Example: `{1: 'One', 2: 'Two', all: 'All' }`. Required by "select" tools. * @property {string} [container_id] The ID to be given to the tool's container element. * @property {string} [defval] Default value * @property {string|Integer} [colnum] Added as part of the option list class. * @property {string} [label] Label associated with the tool, visible in the UI * @property {Integer} [size] Value of the "size" attribute of the tool input * @property {module:jQuerySpinButton.SpinButtonConfig} [spindata] When added to a tool of type "input", this tool becomes a "spinner" which allows the number to be in/decreased. */ if (ext.context_tools) { $$d.each(ext.context_tools, function (i, tool) { // Add select tool var contId = tool.container_id ? ' id="' + tool.container_id + '"' : ''; var panel = $$d('#' + tool.panel); // create the panel if it doesn't exist if (!panel.length) { panel = $$d('<div>', { id: tool.panel }).appendTo('#tools_top'); } var html; // TODO: Allow support for other types, or adding to existing tool switch (tool.type) { case 'tool_button': { html = '<div class="tool_button">' + tool.id + '</div>'; var div = $$d(html).appendTo(panel); if (tool.events) { $$d.each(tool.events, function (evt, func) { $$d(div).bind(evt, func); }); } break; } case 'select': { html = '<label' + contId + '>' + '<select id="' + tool.id + '">'; $$d.each(tool.options, function (val, text) { var sel = val === tool.defval ? ' selected' : ''; html += '<option value="' + val + '"' + sel + '>' + text + '</option>'; }); html += '</select></label>'; // Creates the tool, hides & adds it, returns the select element var sel = $$d(html).appendTo(panel).find('select'); $$d.each(tool.events, function (evt, func) { $$d(sel).bind(evt, func); }); break; } case 'button-select': { html = '<div id="' + tool.id + '" class="dropdown toolset" title="' + tool.title + '">' + '<div id="cur_' + tool.id + '" class="icon_label"></div><button></button></div>'; var list = $$d('<ul id="' + tool.id + '_opts"></ul>').appendTo('#option_lists'); if (tool.colnum) { list.addClass('optcols' + tool.colnum); } // Creates the tool, hides & adds it, returns the select element /* const dropdown = */ $$d(html).appendTo(panel).children(); btnSelects.push({ elem: '#' + tool.id, list: '#' + tool.id + '_opts', title: tool.title, callback: tool.events.change, cur: '#cur_' + tool.id }); break; } case 'input': { html = '<label' + contId + '>' + '<span id="' + tool.id + '_label">' + tool.label + ':</span>' + '<input id="' + tool.id + '" title="' + tool.title + '" size="' + (tool.size || '4') + '" value="' + (tool.defval || '') + '" type="text"/></label>'; // Creates the tool, hides & adds it, returns the select element // Add to given tool.panel var inp = $$d(html).appendTo(panel).find('input'); if (tool.spindata) { inp.SpinButton(tool.spindata); } if (tool.events) { $$d.each(tool.events, function (evt, func) { inp.bind(evt, func); }); } break; } } }); } svgicons = ext.svgicons; if (!ext.buttons) { _context6.next = 24; break; } fallbackObj = {}, altsObj = {}, placementObj = {}, holders = {}; /** * @typedef {GenericArray} module:SVGEditor.KeyArray * @property {string} 0 The key to bind (on `keydown`) * @property {boolean} 1 Whether to `preventDefault` on the `keydown` event * @property {boolean} 2 Not apparently in use (NoDisableInInput) */ /** * @typedef {string|module:SVGEditor.KeyArray} module:SVGEditor.Key */ /** * @typedef {PlainObject} module:SVGEditor.Button * @property {string} id A unique identifier for this button. If SVG icons are used, this must match the ID used in the icon file. Required. * @property {"mode_flyout"|"mode"|"context"|"app_menu"} type Type of button. Required. * @property {string} title The tooltip text that will appear when the user hovers over the icon. Required. * @property {PlainObject<string, external:jQuery.Function>|PlainObject<"click", external:jQuery.Function>} events DOM event names with associated functions. Example: `{click () { alert('Button was clicked') } }`. Click is used with `includeWith` and `type` of "mode_flyout" (and "mode"); any events may be added if `list` is not present. Expected. * @property {string} panel The ID of the context panel to be included, if type is "context". Required only if type is "context". * @property {string} icon The file path to the raster version of the icon image source. Required only if no `svgicons` is supplied from [ExtensionInitResponse]{@link module:svgcanvas.ExtensionInitResponse}. * @property {string} [svgicon] If absent, will utilize the button "id"; used to set "placement" on the `svgIcons` call * @property {string} [list] Points to the "id" of a `context_tools` item of type "button-select" into which the button will be added as a panel list item * @property {Integer} [position] The numeric index for placement; defaults to last position (as of the time of extension addition) if not present. For use with {@link http://api.jquery.com/eq/}. * @property {boolean} [isDefault] Whether or not the button is the default. Used with `list`. * @property {PlainObject} [includeWith] Object with flyout menu data * @property {boolean} [includeWith.isDefault] Indicates whether button is default in flyout list or not. * @property {string} includeWith.button jQuery selector of the existing button to be joined. Example: '#tool_line'. Required if `includeWith` is used. * @property {"last"|Integer} [includeWith.position] Position of icon in flyout list; will be added to end if not indicated. Integer is for use with {@link http://api.jquery.com/eq/}. * @property {module:SVGEditor.Key} [key] The key to bind to the button */ // Add buttons given by extension $$d.each(ext.buttons, function (i, /** @type {module:SVGEditor.Button} */ btn) { var id = btn.id; var num = i; // Give button a unique ID while ($$d('#' + id).length) { id = btn.id + '_' + ++num; } var icon; if (!svgicons) { icon = $$d('<img src="' + btn.icon + (btn.title ? '" alt="' + btn.title : '') + '">'); } else { fallbackObj[id] = btn.icon; altsObj[id] = btn.title; var svgicon = btn.svgicon || btn.id; if (btn.type === 'app_menu') { placementObj['#' + id + ' > div'] = svgicon; } else { placementObj['#' + id] = svgicon; } } var cls, parent; // Set button up according to its type switch (btn.type) { case 'mode_flyout': case 'mode': cls = 'tool_button'; parent = '#tools_left'; break; case 'context': cls = 'tool_button'; parent = '#' + btn.panel; // create the panel if it doesn't exist if (!$$d(parent).length) { $$d('<div>', { id: btn.panel }).appendTo('#tools_top'); } break; case 'app_menu': cls = ''; parent = '#main_menu ul'; break; } var flyoutHolder, showBtn, refData, refBtn; var button = $$d(btn.list || btn.type === 'app_menu' ? '<li/>' : '<div/>').attr('id', id).attr('title', btn.title).addClass(cls); if (!btn.includeWith && !btn.list) { if ('position' in btn) { if ($$d(parent).children().eq(btn.position).length) { $$d(parent).children().eq(btn.position).before(button); } else { $$d(parent).children().last().after(button); } } else { button.appendTo(parent); } if (btn.type === 'mode_flyout') { // Add to flyout menu / make flyout menu // const opts = btn.includeWith; // // opts.button, default, position refBtn = $$d(button); flyoutHolder = refBtn.parent(); // Create a flyout menu if there isn't one already var tlsId; if (!refBtn.parent().hasClass('tools_flyout')) { // Create flyout placeholder tlsId = refBtn[0].id.replace('tool_', 'tools_'); showBtn = refBtn.clone().attr('id', tlsId + '_show').append($$d('<div>', { "class": 'flyout_arrow_horiz' })); refBtn.before(showBtn); // Create a flyout div flyoutHolder = makeFlyoutHolder(tlsId, refBtn); flyoutHolder.data('isLibrary', true); showBtn.data('isLibrary', true); } // refData = Actions.getButtonData(opts.button); placementObj['#' + tlsId + '_show'] = btn.id; // TODO: Find way to set the current icon using the iconloader if this is not default // Include data for extension button as well as ref button /* curH = */ holders['#' + flyoutHolder[0].id] = [{ sel: '#' + id, fn: btn.events.click, icon: btn.id, // key: btn.key, isDefault: true }]; // , refData // // // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'} // // const pos = ('position' in opts)?opts.position:'last'; // const len = flyoutHolder.children().length; // // // Add at given position or end // if (!isNaN(pos) && pos >= 0 && pos < len) { // flyoutHolder.children().eq(pos).before(button); // } else { // flyoutHolder.append(button); // curH.reverse(); // } } else if (btn.type === 'app_menu') { button.append('<div>').append(btn.title); } } else if (btn.list) { // Add button to list button.addClass('push_button'); $$d('#' + btn.list + '_opts').append(button); if (btn.isDefault) { $$d('#cur_' + btn.list).append(button.children().clone()); var _svgicon = btn.svgicon || btn.id; placementObj['#cur_' + btn.list] = _svgicon; } } else if (btn.includeWith) { // Add to flyout menu / make flyout menu var opts = btn.includeWith; // opts.button, default, position refBtn = $$d(opts.button); flyoutHolder = refBtn.parent(); // Create a flyout menu if there isn't one already var _tlsId; if (!refBtn.parent().hasClass('tools_flyout')) { // Create flyout placeholder _tlsId = refBtn[0].id.replace('tool_', 'tools_'); showBtn = refBtn.clone().attr('id', _tlsId + '_show').append($$d('<div>', { "class": 'flyout_arrow_horiz' })); refBtn.before(showBtn); // Create a flyout div flyoutHolder = makeFlyoutHolder(_tlsId, refBtn); } refData = Actions.getButtonData(opts.button); if (opts.isDefault) { placementObj['#' + _tlsId + '_show'] = btn.id; } // TODO: Find way to set the current icon using the iconloader if this is not default // Include data for extension button as well as ref button var curH = holders['#' + flyoutHolder[0].id] = [{ sel: '#' + id, fn: btn.events.click, icon: btn.id, key: btn.key, isDefault: Boolean(btn.includeWith && btn.includeWith.isDefault) }, refData]; // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'} var pos = 'position' in opts ? opts.position : 'last'; var len = flyoutHolder.children().length; // Add at given position or end if (!isNaN(pos) && pos >= 0 && pos < len) { flyoutHolder.children().eq(pos).before(button); } else { flyoutHolder.append(button); curH.reverse(); } } if (!svgicons) { button.append(icon); } if (!btn.list) { // Add given events to button $$d.each(btn.events, function (name, func) { if (name === 'click' && btn.type === 'mode') { // `touch.js` changes `touchstart` to `mousedown`, // so we must map extension click events as well if (isTouch() && name === 'click') { name = 'mousedown'; } if (btn.includeWith) { button.bind(name, func); } else { button.bind(name, function () { if (toolButtonClick(button)) { func(); } }); } if (btn.key) { $$d(document).bind('keydown', btn.key, func); if (btn.title) { button.attr('title', btn.title + ' [' + btn.key + ']'); } } } else { button.bind(name, func); } }); } setupFlyouts(holders); }); $$d.each(btnSelects, function () { addAltDropDown(this.elem, this.list, this.callback, { seticon: true }); }); if (!svgicons) { _context6.next = 24; break; } return _context6.abrupt("return", new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new $$d.svgIcons("".concat(curConfig.imgPath).concat(svgicons), { w: 24, h: 24, id_match: false, no_img: !isWebkit(), fallback: fallbackObj, placement: placementObj, callback: function callback(icons) { // Non-ideal hack to make the icon match the current size // if (curPrefs.iconsize && curPrefs.iconsize !== 'm') { if (editor.pref('iconsize') !== 'm') { prepResize(); } runCallback(); resolve(); } }); })); case 24: return _context6.abrupt("return", runCallback()); case 25: case "end": return _context6.stop(); } } }, _callee6); })); return function extAdded(_x4, _x5) { return _ref11.apply(this, arguments); }; }(); /** * @param {string} color * @param {Float} opac * @param {string} type * @returns {module:jGraduate~Paint} */ var getPaint = function getPaint(color, opac, type) { // update the editor's fill paint var opts = { alpha: opac }; if (color.startsWith('url(#')) { var refElem = svgCanvas.getRefElem(color); if (refElem) { refElem = refElem.cloneNode(true); } else { refElem = $$d('#' + type + '_color defs *')[0]; } opts[refElem.tagName] = refElem; } else if (color.startsWith('#')) { opts.solidColor = color.substr(1); } else { opts.solidColor = 'none'; } return new $$d.jGraduate.Paint(opts); }; // $('#text').focus(function () { textBeingEntered = true; }); // $('#text').blur(function () { textBeingEntered = false; }); // bind the selected event to our function that handles updates to the UI svgCanvas.bind('selected', selectedChanged); svgCanvas.bind('transition', elementTransition); svgCanvas.bind('changed', elementChanged); svgCanvas.bind('saved', saveHandler); svgCanvas.bind('exported', exportHandler); svgCanvas.bind('exportedPDF', function (win, data) { if (!data.output) { // Ignore Chrome return; } var exportWindowName = data.exportWindowName; if (exportWindowName) { exportWindow = window.open('', exportWindowName); // A hack to get the window via JSON-able name without opening a new one } if (!exportWindow || exportWindow.closed) { /* await */ $$d.alert(uiStrings$1.notification.popupWindowBlocked); return; } exportWindow.location.href = data.output; }); svgCanvas.bind('zoomed', zoomChanged); svgCanvas.bind('zoomDone', zoomDone); svgCanvas.bind('updateCanvas', /** * @param {external:Window} win * @param {PlainObject} centerInfo * @param {false} centerInfo.center * @param {module:math.XYObject} centerInfo.newCtr * @listens module:svgcanvas.SvgCanvas#event:updateCanvas * @returns {void} */ function (win, _ref12) { var center = _ref12.center, newCtr = _ref12.newCtr; updateCanvas(center, newCtr); }); svgCanvas.bind('contextset', contextChanged); svgCanvas.bind('extension_added', extAdded); svgCanvas.textActions.setInputElem($$d('#text')[0]); var str = '<div class="palette_item" data-rgb="none"></div>'; $$d.each(palette, function (i, item) { str += '<div class="palette_item" style="background-color: ' + item + ';" data-rgb="' + item + '"></div>'; }); $$d('#palette').append(str); // Set up editor background functionality var colorBlocks = ['#FFF', '#888', '#000', 'chessboard']; str = ''; $$d.each(colorBlocks, function (i, e) { if (e === 'chessboard') { str += '<div class="color_block" data-bgcolor="' + e + '" style="background-image:url(data:image/gif;base64,' + 'R0lGODlhEAAQAIAAAP///9bW1iH5BAAAAAAALAAAAAAQABAAAAIfjG+' + 'gq4jM3IFLJgpswNly/XkcBpIiVaInlLJr9FZWAQA7);"></div>'; } else { str += '<div class="color_block" data-bgcolor="' + e + '" style="background-color:' + e + ';"></div>'; } }); $$d('#bg_blocks').append(str); var blocks = $$d('#bg_blocks div'); var curBg = 'cur_background'; blocks.each(function () { var blk = $$d(this); blk.click(function () { blocks.removeClass(curBg); $$d(this).addClass(curBg); }); }); setBackground(editor.pref('bkgd_color'), editor.pref('bkgd_url')); $$d('#image_save_opts input').val([editor.pref('img_save')]); /** * @type {module:jQuerySpinButton.ValueCallback} */ var changeRectRadius = function changeRectRadius(ctl) { svgCanvas.setRectRadius(ctl.value); }; /** * @type {module:jQuerySpinButton.ValueCallback} */ var changeFontSize = function changeFontSize(ctl) { svgCanvas.setFontSize(ctl.value); }; /** * @type {module:jQuerySpinButton.ValueCallback} */ var changeStrokeWidth = function changeStrokeWidth(ctl) { var val = ctl.value; if (val === 0 && selectedElement && ['line', 'polyline'].includes(selectedElement.nodeName)) { val = ctl.value = 1; } svgCanvas.setStrokeWidth(val); }; /** * @type {module:jQuerySpinButton.ValueCallback} */ var changeRotationAngle = function changeRotationAngle(ctl) { svgCanvas.setRotationAngle(ctl.value); $$d('#tool_reorient').toggleClass('disabled', Number.parseInt(ctl.value) === 0); }; /** * @param {external:jQuery.fn.SpinButton} ctl Spin Button * @param {string} [val=ctl.value] * @returns {void} */ var changeOpacity = function changeOpacity(ctl, val) { if (isNullish(val)) { val = ctl.value; } $$d('#group_opacity').val(val); if (!ctl || !ctl.handle) { $$d('#opac_slider').slider('option', 'value', val); } svgCanvas.setOpacity(val / 100); }; /** * @param {external:jQuery.fn.SpinButton} ctl Spin Button * @param {string} [val=ctl.value] * @param {boolean} noUndo * @returns {void} */ var changeBlur = function changeBlur(ctl, val, noUndo) { if (isNullish(val)) { val = ctl.value; } $$d('#blur').val(val); var complete = false; if (!ctl || !ctl.handle) { $$d('#blur_slider').slider('option', 'value', val); complete = true; } if (noUndo) { svgCanvas.setBlurNoUndo(val); } else { svgCanvas.setBlur(val, complete); } }; $$d('#stroke_style').change(function () { svgCanvas.setStrokeAttr('stroke-dasharray', $$d(this).val()); operaRepaint(); }); $$d('#stroke_linejoin').change(function () { svgCanvas.setStrokeAttr('stroke-linejoin', $$d(this).val()); operaRepaint(); }); // Lose focus for select elements when changed (Allows keyboard shortcuts to work better) $$d('select').change(function () { $$d(this).blur(); }); // fired when user wants to move elements to another layer var promptMoveLayerOnce = false; $$d('#selLayerNames').change( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7() { var destLayer, confirmStr, moveToLayer, ok; return regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: destLayer = this.options[this.selectedIndex].value; confirmStr = uiStrings$1.notification.QmoveElemsToLayer.replace('%s', destLayer); /** * @param {boolean} ok * @returns {void} */ moveToLayer = function moveToLayer(ok) { if (!ok) { return; } promptMoveLayerOnce = true; svgCanvas.moveSelectedToLayer(destLayer); svgCanvas.clearSelection(); populateLayers(); }; if (!destLayer) { _context7.next = 14; break; } if (!promptMoveLayerOnce) { _context7.next = 8; break; } moveToLayer(true); _context7.next = 14; break; case 8: _context7.next = 10; return $$d.confirm(confirmStr); case 10: ok = _context7.sent; if (ok) { _context7.next = 13; break; } return _context7.abrupt("return"); case 13: moveToLayer(true); case 14: case "end": return _context7.stop(); } } }, _callee7, this); }))); $$d('#font_family').change(function () { svgCanvas.setFontFamily(this.value); }); $$d('#seg_type').change(function () { svgCanvas.setSegType($$d(this).val()); }); $$d('#text').bind('keyup input', function () { svgCanvas.setTextContent(this.value); }); $$d('#image_url').change(function () { setImageURL(this.value); }); $$d('#link_url').change(function () { if (this.value.length) { svgCanvas.setLinkURL(this.value); } else { svgCanvas.removeHyperlink(); } }); $$d('#g_title').change(function () { svgCanvas.setGroupTitle(this.value); }); $$d('.attr_changer').change(function () { var attr = this.getAttribute('data-attr'); var val = this.value; var valid = isValidUnit(attr, val, selectedElement); if (!valid) { this.value = selectedElement.getAttribute(attr); /* await */ $$d.alert(uiStrings$1.notification.invalidAttrValGiven); return false; } if (attr !== 'id' && attr !== 'class') { if (isNaN(val)) { val = svgCanvas.convertToNum(attr, val); } else if (curConfig.baseUnit !== 'px') { // Convert unitless value to one with given unit var unitData = getTypeMap(); if (selectedElement[attr] || svgCanvas.getMode() === 'pathedit' || attr === 'x' || attr === 'y') { val *= unitData[curConfig.baseUnit]; } } } // if the user is changing the id, then de-select the element first // change the ID, then re-select it with the new ID if (attr === 'id') { var elem = selectedElement; svgCanvas.clearSelection(); elem.id = val; svgCanvas.addToSelection([elem], true); } else { svgCanvas.changeSelectedAttribute(attr, val); } this.blur(); return true; }); // Prevent selection of elements when shift-clicking $$d('#palette').mouseover(function () { var inp = $$d('<input type="hidden">'); $$d(this).append(inp); inp.focus().remove(); }); $$d('.palette_item').mousedown(function (evt) { // shift key or right click for stroke var picker = evt.shiftKey || evt.button === 2 ? 'stroke' : 'fill'; var color = $$d(this).data('rgb'); var paint; // Webkit-based browsers returned 'initial' here for no stroke if (color === 'none' || color === 'transparent' || color === 'initial') { color = 'none'; paint = new $$d.jGraduate.Paint(); } else { paint = new $$d.jGraduate.Paint({ alpha: 100, solidColor: color.substr(1) }); } paintBox[picker].setPaint(paint); svgCanvas.setColor(picker, color); if (color !== 'none' && svgCanvas.getPaintOpacity(picker) !== 1) { svgCanvas.setPaintOpacity(picker, 1.0); } updateToolButtonState(); }).bind('contextmenu', function (e) { e.preventDefault(); }); $$d('#toggle_stroke_tools').on('click', function () { $$d('#tools_bottom').toggleClass('expanded'); }); (function () { var wArea = workarea[0]; var lastX = null, lastY = null, panning = false, keypan = false; $$d('#svgcanvas').bind('mousemove mouseup', function (evt) { if (panning === false) { return true; } wArea.scrollLeft -= evt.clientX - lastX; wArea.scrollTop -= evt.clientY - lastY; lastX = evt.clientX; lastY = evt.clientY; if (evt.type === 'mouseup') { panning = false; } return false; }).mousedown(function (evt) { if (evt.button === 1 || keypan === true) { panning = true; lastX = evt.clientX; lastY = evt.clientY; return false; } return true; }); $$d(window).mouseup(function () { panning = false; }); $$d(document).bind('keydown', 'space', function (evt) { svgCanvas.spaceKey = keypan = true; evt.preventDefault(); }).bind('keyup', 'space', function (evt) { evt.preventDefault(); svgCanvas.spaceKey = keypan = false; }).bind('keydown', 'shift', function (evt) { if (svgCanvas.getMode() === 'zoom') { workarea.css('cursor', zoomOutIcon); } }).bind('keyup', 'shift', function (evt) { if (svgCanvas.getMode() === 'zoom') { workarea.css('cursor', zoomInIcon); } }); /** * @function module:SVGEditor.setPanning * @param {boolean} active * @returns {void} */ editor.setPanning = function (active) { svgCanvas.spaceKey = keypan = active; }; })(); (function () { var button = $$d('#main_icon'); var overlay = $$d('#main_icon span'); var list = $$d('#main_menu'); var onButton = false; var height = 0; var jsHover = true; var setClick = false; /* // Currently unused const hideMenu = function () { list.fadeOut(200); }; */ $$d(window).mouseup(function (evt) { if (!onButton) { button.removeClass('buttondown'); // do not hide if it was the file input as that input needs to be visible // for its change event to fire if (evt.target.tagName !== 'INPUT') { list.fadeOut(200); } else if (!setClick) { setClick = true; $$d(evt.target).click(function () { list.css('margin-left', '-9999px').show(); }); } } onButton = false; }).mousedown(function (evt) { // $('.contextMenu').hide(); var islib = $$d(evt.target).closest('div.tools_flyout, .contextMenu').length; if (!islib) { $$d('.tools_flyout:visible,.contextMenu').fadeOut(250); } }); overlay.bind('mousedown', function () { if (!button.hasClass('buttondown')) { // Margin must be reset in case it was changed before; list.css('margin-left', 0).show(); if (!height) { height = list.height(); } // Using custom animation as slideDown has annoying 'bounce effect' list.css('height', 0).animate({ height: height }, 200); onButton = true; } else { list.fadeOut(200); } button.toggleClass('buttondown buttonup'); }).hover(function () { onButton = true; }).mouseout(function () { onButton = false; }); var listItems = $$d('#main_menu li'); // Check if JS method of hovering needs to be used (Webkit bug) listItems.mouseover(function () { jsHover = $$d(this).css('background-color') === 'rgba(0, 0, 0, 0)'; listItems.unbind('mouseover'); if (jsHover) { listItems.mouseover(function () { this.style.backgroundColor = '#FFC'; }).mouseout(function () { this.style.backgroundColor = 'transparent'; return true; }); } }); })(); // Made public for UI customization. // TODO: Group UI functions into a public editor.ui interface. /** * See {@link http://api.jquery.com/bind/#bind-eventType-eventData-handler}. * @callback module:SVGEditor.DropDownCallback * @param {external:jQuery.Event} ev See {@link http://api.jquery.com/Types/#Event} * @listens external:jQuery.Event * @returns {void|boolean} Calls `preventDefault()` and `stopPropagation()` */ /** * @function module:SVGEditor.addDropDown * @param {Element|string} elem DOM Element or selector * @param {module:SVGEditor.DropDownCallback} callback Mouseup callback * @param {boolean} dropUp * @returns {void} */ editor.addDropDown = function (elem, callback, dropUp) { if (!$$d(elem).length) { return; } // Quit if called on non-existent element var button = $$d(elem).find('button'); var list = $$d(elem).find('ul').attr('id', $$d(elem)[0].id + '-list'); if (dropUp) { $$d(elem).addClass('dropup'); } else { // Move list to place where it can overflow container $$d('#option_lists').append(list); } list.find('li').bind('mouseup', callback); var onButton = false; $$d(window).mouseup(function (evt) { if (!onButton) { button.removeClass('down'); list.hide(); } onButton = false; }); button.bind('mousedown', function () { if (!button.hasClass('down')) { if (!dropUp) { var pos = $$d(elem).position(); list.css({ top: pos.top + 24, left: pos.left - 10 }); } list.show(); onButton = true; } else { list.hide(); } button.toggleClass('down'); }).hover(function () { onButton = true; }).mouseout(function () { onButton = false; }); }; editor.addDropDown('#font_family_dropdown', function () { $$d('#font_family').val($$d(this).text()).change(); }); editor.addDropDown('#opacity_dropdown', function () { if ($$d(this).find('div').length) { return; } var perc = Number.parseInt($$d(this).text().split('%')[0]); changeOpacity(false, perc); }, true); // For slider usage, see: http://jqueryui.com/demos/slider/ $$d('#opac_slider').slider({ start: function start() { $$d('#opacity_dropdown li:not(.special)').hide(); }, stop: function stop() { $$d('#opacity_dropdown li').show(); $$d(window).mouseup(); }, slide: function slide(evt, ui) { changeOpacity(ui); } }); editor.addDropDown('#blur_dropdown', $$d.noop); var slideStart = false; $$d('#blur_slider').slider({ max: 10, step: 0.1, stop: function stop(evt, ui) { slideStart = false; changeBlur(ui); $$d('#blur_dropdown li').show(); $$d(window).mouseup(); }, start: function start() { slideStart = true; }, slide: function slide(evt, ui) { changeBlur(ui, null, slideStart); } }); editor.addDropDown('#zoom_dropdown', function () { var item = $$d(this); var val = item.data('val'); if (val) { zoomChanged(window, val); } else { changeZoom({ value: Number.parseFloat(item.text()) }); } }, true); addAltDropDown('#stroke_linecap', '#linecap_opts', function () { setStrokeOpt(this, true); }, { dropUp: true }); addAltDropDown('#stroke_linejoin', '#linejoin_opts', function () { setStrokeOpt(this, true); }, { dropUp: true }); addAltDropDown('#tool_position', '#position_opts', function () { var letter = this.id.replace('tool_pos', '').charAt(0); svgCanvas.alignSelectedElements(letter, 'page'); }, { multiclick: true }); /* When a flyout icon is selected (if flyout) { - Change the icon - Make pressing the button run its stuff } - Run its stuff When its shortcut key is pressed - If not current in list, do as above , else: - Just run its stuff */ // Unfocus text input when workarea is mousedowned. (function () { var inp; /** * * @returns {void} */ var unfocus = function unfocus() { $$d(inp).blur(); }; $$d('#svg_editor').find('button, select, input:not(#text)').focus(function () { inp = this; uiContext = 'toolbars'; workarea.mousedown(unfocus); }).blur(function () { uiContext = 'canvas'; workarea.unbind('mousedown', unfocus); // Go back to selecting text if in textedit mode if (svgCanvas.getMode() === 'textedit') { $$d('#text').focus(); } }); })(); /** * * @returns {void} */ var clickFHPath = function clickFHPath() { if (toolButtonClick('#tool_fhpath')) { svgCanvas.setMode('fhpath'); } }; /** * * @returns {void} */ var clickLine = function clickLine() { if (toolButtonClick('#tool_line')) { svgCanvas.setMode('line'); } }; /** * * @returns {void} */ var clickSquare = function clickSquare() { if (toolButtonClick('#tool_square')) { svgCanvas.setMode('square'); } }; /** * * @returns {void} */ var clickRect = function clickRect() { if (toolButtonClick('#tool_rect')) { svgCanvas.setMode('rect'); } }; /** * * @returns {void} */ var clickFHRect = function clickFHRect() { if (toolButtonClick('#tool_fhrect')) { svgCanvas.setMode('fhrect'); } }; /** * * @returns {void} */ var clickCircle = function clickCircle() { if (toolButtonClick('#tool_circle')) { svgCanvas.setMode('circle'); } }; /** * * @returns {void} */ var clickEllipse = function clickEllipse() { if (toolButtonClick('#tool_ellipse')) { svgCanvas.setMode('ellipse'); } }; /** * * @returns {void} */ var clickFHEllipse = function clickFHEllipse() { if (toolButtonClick('#tool_fhellipse')) { svgCanvas.setMode('fhellipse'); } }; /** * * @returns {void} */ var clickImage = function clickImage() { if (toolButtonClick('#tool_image')) { svgCanvas.setMode('image'); } }; /** * * @returns {void} */ var clickZoom = function clickZoom() { if (toolButtonClick('#tool_zoom')) { svgCanvas.setMode('zoom'); workarea.css('cursor', zoomInIcon); } }; /** * @param {Float} multiplier * @returns {void} */ var zoomImage = function zoomImage(multiplier) { var res = svgCanvas.getResolution(); multiplier = multiplier ? res.zoom * multiplier : 1; // setResolution(res.w * multiplier, res.h * multiplier, true); $$d('#zoom').val(multiplier * 100); svgCanvas.setZoom(multiplier); zoomDone(); updateCanvas(true); }; /** * * @returns {void} */ var dblclickZoom = function dblclickZoom() { if (toolButtonClick('#tool_zoom')) { zoomImage(); setSelectMode(); } }; /** * * @returns {void} */ var clickText = function clickText() { if (toolButtonClick('#tool_text')) { svgCanvas.setMode('text'); } }; /** * * @returns {void} */ var clickPath = function clickPath() { if (toolButtonClick('#tool_path')) { svgCanvas.setMode('path'); } }; /** * Delete is a contextual tool that only appears in the ribbon if * an element has been selected. * @returns {void} */ var deleteSelected = function deleteSelected() { if (!isNullish(selectedElement) || multiselected) { svgCanvas.deleteSelectedElements(); } }; /** * * @returns {void} */ var cutSelected = function cutSelected() { if (!isNullish(selectedElement) || multiselected) { svgCanvas.cutSelectedElements(); } }; /** * * @returns {void} */ var copySelected = function copySelected() { if (!isNullish(selectedElement) || multiselected) { svgCanvas.copySelectedElements(); } }; /** * * @returns {void} */ var pasteInCenter = function pasteInCenter() { var zoom = svgCanvas.getZoom(); var x = (workarea[0].scrollLeft + workarea.width() / 2) / zoom - svgCanvas.contentW; var y = (workarea[0].scrollTop + workarea.height() / 2) / zoom - svgCanvas.contentH; svgCanvas.pasteElements('point', x, y); }; /** * * @returns {void} */ var moveToTopSelected = function moveToTopSelected() { if (!isNullish(selectedElement)) { svgCanvas.moveToTopSelectedElement(); } }; /** * * @returns {void} */ var moveToBottomSelected = function moveToBottomSelected() { if (!isNullish(selectedElement)) { svgCanvas.moveToBottomSelectedElement(); } }; /** * @param {"Up"|"Down"} dir * @returns {void} */ var moveUpDownSelected = function moveUpDownSelected(dir) { if (!isNullish(selectedElement)) { svgCanvas.moveUpDownSelected(dir); } }; /** * * @returns {void} */ var convertToPath = function convertToPath() { if (!isNullish(selectedElement)) { svgCanvas.convertToPath(); } }; /** * * @returns {void} */ var reorientPath = function reorientPath() { if (!isNullish(selectedElement)) { path.reorient(); } }; /** * * @returns {Promise<void>} Resolves to `undefined` */ var makeHyperlink = /*#__PURE__*/function () { var _ref14 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8() { var url; return regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (!(!isNullish(selectedElement) || multiselected)) { _context8.next = 5; break; } _context8.next = 3; return $$d.prompt(uiStrings$1.notification.enterNewLinkURL, 'http://'); case 3: url = _context8.sent; if (url) { svgCanvas.makeHyperlink(url); } case 5: case "end": return _context8.stop(); } } }, _callee8); })); return function makeHyperlink() { return _ref14.apply(this, arguments); }; }(); /** * @param {Float} dx * @param {Float} dy * @returns {void} */ var moveSelected = function moveSelected(dx, dy) { if (!isNullish(selectedElement) || multiselected) { if (curConfig.gridSnapping) { // Use grid snap value regardless of zoom level var multi = svgCanvas.getZoom() * curConfig.snappingStep; dx *= multi; dy *= multi; } svgCanvas.moveSelectedElements(dx, dy); } }; /** * * @returns {void} */ var linkControlPoints = function linkControlPoints() { $$d('#tool_node_link').toggleClass('push_button_pressed tool_button'); var linked = $$d('#tool_node_link').hasClass('push_button_pressed'); path.linkControlPoints(linked); }; /** * * @returns {void} */ var clonePathNode = function clonePathNode() { if (path.getNodePoint()) { path.clonePathNode(); } }; /** * * @returns {void} */ var deletePathNode = function deletePathNode() { if (path.getNodePoint()) { path.deletePathNode(); } }; /** * * @returns {void} */ var addSubPath = function addSubPath() { var button = $$d('#tool_add_subpath'); var sp = !button.hasClass('push_button_pressed'); button.toggleClass('push_button_pressed tool_button'); path.addSubPath(sp); }; /** * * @returns {void} */ var opencloseSubPath = function opencloseSubPath() { path.opencloseSubPath(); }; /** * * @returns {void} */ var selectNext = function selectNext() { svgCanvas.cycleElement(1); }; /** * * @returns {void} */ var selectPrev = function selectPrev() { svgCanvas.cycleElement(0); }; /** * @param {0|1} cw * @param {Integer} step * @returns {void} */ var rotateSelected = function rotateSelected(cw, step) { if (isNullish(selectedElement) || multiselected) { return; } if (!cw) { step *= -1; } var angle = Number.parseFloat($$d('#angle').val()) + step; svgCanvas.setRotationAngle(angle); updateContextPanel(); }; /** * @fires module:svgcanvas.SvgCanvas#event:ext_onNewDocument * @returns {Promise<void>} Resolves to `undefined` */ var clickClear = /*#__PURE__*/function () { var _ref15 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9() { var _curConfig$dimensions, x, y, ok; return regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _curConfig$dimensions = _slicedToArray(curConfig.dimensions, 2), x = _curConfig$dimensions[0], y = _curConfig$dimensions[1]; _context9.next = 3; return $$d.confirm(uiStrings$1.notification.QwantToClear); case 3: ok = _context9.sent; if (ok) { _context9.next = 6; break; } return _context9.abrupt("return"); case 6: setSelectMode(); svgCanvas.clear(); svgCanvas.setResolution(x, y); updateCanvas(true); zoomImage(); populateLayers(); updateContextPanel(); prepPaints(); svgCanvas.runExtensions('onNewDocument'); case 15: case "end": return _context9.stop(); } } }, _callee9); })); return function clickClear() { return _ref15.apply(this, arguments); }; }(); /** * * @returns {false} */ var clickBold = function clickBold() { svgCanvas.setBold(!svgCanvas.getBold()); updateContextPanel(); return false; }; /** * * @returns {false} */ var clickItalic = function clickItalic() { svgCanvas.setItalic(!svgCanvas.getItalic()); updateContextPanel(); return false; }; /** * * @returns {void} */ var clickSave = function clickSave() { // In the future, more options can be provided here var saveOpts = { images: editor.pref('img_save'), round_digits: 6 }; svgCanvas.save(saveOpts); }; var loadingURL; /** * * @returns {Promise<void>} Resolves to `undefined` */ var clickExport = /*#__PURE__*/function () { var _ref16 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10() { var imgType, exportWindowName, openExportWindow, chrome, quality; return regeneratorRuntime.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: openExportWindow = function _openExportWindow() { var loadingImage = uiStrings$1.notification.loadingImage; if (curConfig.exportWindowType === 'new') { editor.exportWindowCt++; } exportWindowName = curConfig.canvasName + editor.exportWindowCt; var popHTML, popURL; if (loadingURL) { popURL = loadingURL; } else { popHTML = "<!DOCTYPE html><html>\n <head>\n <meta charset=\"utf-8\">\n <title>".concat(loadingImage, "\n \n

").concat(loadingImage, "

\n "); if (typeof URL !== 'undefined' && URL.createObjectURL) { var blob = new Blob([popHTML], { type: 'text/html' }); popURL = URL.createObjectURL(blob); } else { popURL = 'data:text/html;base64;charset=utf-8,' + encode64(popHTML); } loadingURL = popURL; } exportWindow = window.open(popURL, exportWindowName); }; _context10.next = 3; return $$d.select('Select an image type for export: ', [// See http://kangax.github.io/jstests/toDataUrl_mime_type_test/ for a useful list of MIME types and browser support // 'ICO', // Todo: Find a way to preserve transparency in SVG-Edit if not working presently and do full packaging for x-icon; then switch back to position after 'PNG' 'PNG', 'JPEG', 'BMP', 'WEBP', 'PDF'], function () { var sel = $$d(this); if (sel.val() === 'JPEG' || sel.val() === 'WEBP') { if (!$$d('#image-slider').length) { $$d("
")).appendTo(sel.parent()); } } else { $$d('#image-slider').parent().remove(); } }); case 3: imgType = _context10.sent; if (imgType) { _context10.next = 6; break; } return _context10.abrupt("return"); case 6: chrome = isChrome(); if (!(imgType === 'PDF')) { _context10.next = 12; break; } if (!customExportPDF && !chrome) { openExportWindow(); } svgCanvas.exportPDF(exportWindowName); _context10.next = 16; break; case 12: if (!customExportImage) { openExportWindow(); } quality = Number.parseInt($$d('#image-slider').val()) / 100; /* const results = */ _context10.next = 16; return svgCanvas.rasterExport(imgType, quality, exportWindowName); case 16: case "end": return _context10.stop(); } } }, _callee10); })); return function clickExport() { return _ref16.apply(this, arguments); }; }(); /** * By default, svgCanvas.open() is a no-op. It is up to an extension * mechanism (opera widget, etc.) to call `setCustomHandlers()` which * will make it do something. * @returns {void} */ var clickOpen = function clickOpen() { svgCanvas.open(); }; /** * * @returns {void} */ var clickImport = function clickImport() { /* */ }; /** * * @returns {void} */ var clickUndo = function clickUndo() { if (undoMgr.getUndoStackSize() > 0) { undoMgr.undo(); populateLayers(); } }; /** * * @returns {void} */ var clickRedo = function clickRedo() { if (undoMgr.getRedoStackSize() > 0) { undoMgr.redo(); populateLayers(); } }; /** * * @returns {void} */ var clickGroup = function clickGroup() { // group if (multiselected) { svgCanvas.groupSelectedElements(); // ungroup } else if (selectedElement) { svgCanvas.ungroupSelectedElement(); } }; /** * * @returns {void} */ var clickClone = function clickClone() { svgCanvas.cloneSelectedElements(20, 20); }; /** * * @returns {void} */ var clickAlign = function clickAlign() { var letter = this.id.replace('tool_align', '').charAt(0); svgCanvas.alignSelectedElements(letter, $$d('#align_relative_to').val()); }; /** * * @returns {void} */ var clickWireframe = function clickWireframe() { $$d('#tool_wireframe').toggleClass('push_button_pressed tool_button'); workarea.toggleClass('wireframe'); if (supportsNonSS) { return; } var wfRules = $$d('#wireframe_rules'); if (!wfRules.length) { /* wfRules = */ $$d('').appendTo('head'); } else { wfRules.empty(); } updateWireFrame(); }; $$d('#svg_docprops_container, #svg_prefs_container').draggable({ cancel: 'button,fieldset', containment: 'window' }).css('position', 'absolute'); var docprops = false; var preferences = false; /** * * @returns {void} */ var showDocProperties = function showDocProperties() { if (docprops) { return; } docprops = true; // This selects the correct radio button by using the array notation $$d('#image_save_opts input').val([editor.pref('img_save')]); // update resolution option with actual resolution var res = svgCanvas.getResolution(); if (curConfig.baseUnit !== 'px') { res.w = convertUnit(res.w) + curConfig.baseUnit; res.h = convertUnit(res.h) + curConfig.baseUnit; } $$d('#canvas_width').val(res.w); $$d('#canvas_height').val(res.h); $$d('#canvas_title').val(svgCanvas.getDocumentTitle()); $$d('#svg_docprops').show(); }; /** * * @returns {void} */ var showPreferences = function showPreferences() { if (preferences) { return; } preferences = true; $$d('#main_menu').hide(); // Update background color with current one var canvasBg = curPrefs.bkgd_color; var url = editor.pref('bkgd_url'); blocks.each(function () { var blk = $$d(this); var isBg = blk.data('bgcolor') === canvasBg; blk.toggleClass(curBg, isBg); }); if (!canvasBg) { blocks.eq(0).addClass(curBg); } if (url) { $$d('#canvas_bg_url').val(url); } $$d('#grid_snapping_on').prop('checked', curConfig.gridSnapping); $$d('#grid_snapping_step').attr('value', curConfig.snappingStep); $$d('#grid_color').attr('value', curConfig.gridColor); $$d('#svg_prefs').show(); }; /** * * @returns {void} */ var openHomePage = function openHomePage() { window.open(homePage, '_blank'); }; /** * * @returns {void} */ var hideSourceEditor = function hideSourceEditor() { $$d('#svg_source_editor').hide(); editingsource = false; $$d('#svg_source_textarea').blur(); }; /** * * @returns {Promise} Resolves to `undefined` */ var saveSourceEditor = /*#__PURE__*/function () { var _ref17 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11() { var saveChanges, ok; return regeneratorRuntime.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: if (editingsource) { _context11.next = 2; break; } return _context11.abrupt("return"); case 2: saveChanges = function saveChanges() { svgCanvas.clearSelection(); hideSourceEditor(); zoomImage(); populateLayers(); updateTitle(); prepPaints(); }; if (svgCanvas.setSvgString($$d('#svg_source_textarea').val())) { _context11.next = 11; break; } _context11.next = 6; return $$d.confirm(uiStrings$1.notification.QerrorsRevertToSource); case 6: ok = _context11.sent; if (ok) { _context11.next = 9; break; } return _context11.abrupt("return"); case 9: saveChanges(); return _context11.abrupt("return"); case 11: saveChanges(); setSelectMode(); case 13: case "end": return _context11.stop(); } } }, _callee11); })); return function saveSourceEditor() { return _ref17.apply(this, arguments); }; }(); /** * * @returns {void} */ var hideDocProperties = function hideDocProperties() { $$d('#svg_docprops').hide(); $$d('#canvas_width,#canvas_height').removeAttr('disabled'); $$d('#resolution')[0].selectedIndex = 0; $$d('#image_save_opts input').val([editor.pref('img_save')]); docprops = false; }; /** * * @returns {void} */ var hidePreferences = function hidePreferences() { $$d('#svg_prefs').hide(); preferences = false; }; /** * * @returns {boolean} Whether there were problems saving the document properties */ var saveDocProperties = function saveDocProperties() { // set title var newTitle = $$d('#canvas_title').val(); updateTitle(newTitle); svgCanvas.setDocumentTitle(newTitle); // update resolution var width = $$d('#canvas_width'), w = width.val(); var height = $$d('#canvas_height'), h = height.val(); if (w !== 'fit' && !isValidUnit('width', w)) { width.parent().addClass('error'); /* await */ $$d.alert(uiStrings$1.notification.invalidAttrValGiven); return false; } width.parent().removeClass('error'); if (h !== 'fit' && !isValidUnit('height', h)) { height.parent().addClass('error'); /* await */ $$d.alert(uiStrings$1.notification.invalidAttrValGiven); return false; } height.parent().removeClass('error'); if (!svgCanvas.setResolution(w, h)) { /* await */ $$d.alert(uiStrings$1.notification.noContentToFitTo); return false; } // Set image save option editor.pref('img_save', $$d('#image_save_opts :checked').val()); updateCanvas(); hideDocProperties(); return true; }; /** * Save user preferences based on current values in the UI. * @function module:SVGEditor.savePreferences * @returns {Promise} */ var savePreferences = editor.savePreferences = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12() { var color, lang, _yield$editor$putLoca2, langParam, langData; return regeneratorRuntime.wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: // Set background color = $$d('#bg_blocks div.cur_background').data('bgcolor') || '#FFF'; setBackground(color, $$d('#canvas_bg_url').val()); // set language lang = $$d('#lang_select').val(); if (!(lang && lang !== editor.pref('lang'))) { _context12.next = 11; break; } _context12.next = 6; return editor.putLocale(lang, goodLangs); case 6: _yield$editor$putLoca2 = _context12.sent; langParam = _yield$editor$putLoca2.langParam; langData = _yield$editor$putLoca2.langData; _context12.next = 11; return setLang(langParam, langData); case 11: // set icon size setIconSize($$d('#iconsize').val()); // set grid setting curConfig.gridSnapping = $$d('#grid_snapping_on')[0].checked; curConfig.snappingStep = $$d('#grid_snapping_step').val(); curConfig.gridColor = $$d('#grid_color').val(); curConfig.showRulers = $$d('#show_rulers')[0].checked; $$d('#rulers').toggle(curConfig.showRulers); if (curConfig.showRulers) { updateRulers(); } curConfig.baseUnit = $$d('#base_unit').val(); svgCanvas.setConfig(curConfig); updateCanvas(); hidePreferences(); case 22: case "end": return _context12.stop(); } } }, _callee12); })); var resetScrollPos = $$d.noop; /** * * @returns {Promise} Resolves to `undefined` */ var cancelOverlays = /*#__PURE__*/function () { var _ref19 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13() { var ok; return regeneratorRuntime.wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: $$d('#dialog_box').hide(); if (!(!editingsource && !docprops && !preferences)) { _context13.next = 4; break; } if (curContext) { svgCanvas.leaveContext(); } return _context13.abrupt("return"); case 4: if (!editingsource) { _context13.next = 15; break; } if (!(origSource !== $$d('#svg_source_textarea').val())) { _context13.next = 12; break; } _context13.next = 8; return $$d.confirm(uiStrings$1.notification.QignoreSourceChanges); case 8: ok = _context13.sent; if (ok) { hideSourceEditor(); } _context13.next = 13; break; case 12: hideSourceEditor(); case 13: _context13.next = 16; break; case 15: if (docprops) { hideDocProperties(); } else if (preferences) { hidePreferences(); } case 16: resetScrollPos(); case 17: case "end": return _context13.stop(); } } }, _callee13); })); return function cancelOverlays() { return _ref19.apply(this, arguments); }; }(); var winWh = { width: $$d(window).width(), height: $$d(window).height() }; // Fix for Issue 781: Drawing area jumps to top-left corner on window resize (IE9) if (isIE()) { resetScrollPos = function resetScrollPos() { if (workarea[0].scrollLeft === 0 && workarea[0].scrollTop === 0) { workarea[0].scrollLeft = curScrollPos.left; workarea[0].scrollTop = curScrollPos.top; } }; curScrollPos = { left: workarea[0].scrollLeft, top: workarea[0].scrollTop }; $$d(window).resize(resetScrollPos); editor.ready(function () { // TODO: Find better way to detect when to do this to minimize // flickering effect return new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new setTimeout(function () { resetScrollPos(); resolve(); }, 500); }); }); workarea.scroll(function () { curScrollPos = { left: workarea[0].scrollLeft, top: workarea[0].scrollTop }; }); } $$d(window).resize(function (evt) { $$d.each(winWh, function (type, val) { var curval = $$d(window)[type](); workarea[0]['scroll' + (type === 'width' ? 'Left' : 'Top')] -= (curval - val) / 2; winWh[type] = curval; }); setFlyoutPositions(); }); workarea.scroll(function () { // TODO: jQuery's scrollLeft/Top() wouldn't require a null check if ($$d('#ruler_x').length) { $$d('#ruler_x')[0].scrollLeft = workarea[0].scrollLeft; } if ($$d('#ruler_y').length) { $$d('#ruler_y')[0].scrollTop = workarea[0].scrollTop; } }); $$d('#url_notice').click(function () { /* await */ $$d.alert(this.title); }); $$d('#change_image_url').click(promptImgURL); // added these event handlers for all the push buttons so they // behave more like buttons being pressed-in and not images (function () { var toolnames = ['clear', 'open', 'save', 'source', 'delete', 'delete_multi', 'paste', 'clone', 'clone_multi', 'move_top', 'move_bottom']; var curClass = 'tool_button_current'; var allTools = ''; $$d.each(toolnames, function (i, item) { allTools += (i ? ',' : '') + '#tool_' + item; }); $$d(allTools).mousedown(function () { $$d(this).addClass(curClass); }).bind('mousedown mouseout', function () { $$d(this).removeClass(curClass); }); $$d('#tool_undo, #tool_redo').mousedown(function () { if (!$$d(this).hasClass('disabled')) { $$d(this).addClass(curClass); } }).bind('mousedown mouseout', function () { $$d(this).removeClass(curClass); }); })(); // switch modifier key in tooltips if mac // NOTE: This code is not used yet until I can figure out how to successfully bind ctrl/meta // in Opera and Chrome if (isMac() && !window.opera) { var shortcutButtons = ['tool_clear', 'tool_save', 'tool_source', 'tool_undo', 'tool_redo', 'tool_clone']; var _i = shortcutButtons.length; while (_i--) { var button = document.getElementById(shortcutButtons[_i]); if (button) { var title = button.title; var index = title.indexOf('Ctrl+'); button.title = [title.substr(0, index), 'Cmd+', title.substr(index + 5)].join(''); } } } /** * @param {external:jQuery} elem * @todo Go back to the color boxes having white background-color and then setting * background-image to none.png (otherwise partially transparent gradients look weird) * @returns {void} */ var colorPicker = function colorPicker(elem) { var picker = elem.attr('id') === 'stroke_color' ? 'stroke' : 'fill'; // const opacity = (picker == 'stroke' ? $('#stroke_opacity') : $('#fill_opacity')); var title = picker === 'stroke' ? uiStrings$1.ui.pick_stroke_paint_opacity : uiStrings$1.ui.pick_fill_paint_opacity; // let wasNone = false; // Currently unused var pos = elem.offset(); var paint = paintBox[picker].paint; $$d('#color_picker').draggable({ cancel: '.jGraduate_tabs, .jGraduate_colPick, .jGraduate_gradPick, .jPicker', containment: 'window' }).css(curConfig.colorPickerCSS || { left: pos.left - 140, bottom: 40 }).jGraduate({ images: { clientPath: './jgraduate/images/' }, paint: paint, window: { pickerTitle: title }, // images: {clientPath: curConfig.imgPath}, newstop: 'inverse' }, function (p) { paint = new $$d.jGraduate.Paint(p); paintBox[picker].setPaint(paint); svgCanvas.setPaint(picker, paint); $$d('#color_picker').hide(); }, function () { $$d('#color_picker').hide(); }); }; /** * Paint box class. */ var PaintBox = /*#__PURE__*/function () { /** * @param {string|Element|external:jQuery} container * @param {"fill"} type */ function PaintBox(container, type) { _classCallCheck(this, PaintBox); var cur = curConfig[type === 'fill' ? 'initFill' : 'initStroke']; // set up gradients to be used for the buttons var svgdocbox = new DOMParser().parseFromString("\n \n \n "), 'text/xml'); var docElem = svgdocbox.documentElement; docElem = $$d(container)[0].appendChild(document.importNode(docElem, true)); docElem.setAttribute('width', 16.5); this.rect = docElem.firstElementChild; this.defs = docElem.getElementsByTagName('defs')[0]; this.grad = this.defs.firstElementChild; this.paint = new $$d.jGraduate.Paint({ solidColor: cur.color }); this.type = type; } /** * @param {module:jGraduate~Paint} paint * @param {boolean} apply * @returns {void} */ _createClass(PaintBox, [{ key: "setPaint", value: function setPaint(paint, apply) { this.paint = paint; var ptype = paint.type; var opac = paint.alpha / 100; var fillAttr = 'none'; switch (ptype) { case 'solidColor': fillAttr = paint[ptype] !== 'none' ? '#' + paint[ptype] : paint[ptype]; break; case 'linearGradient': case 'radialGradient': { this.grad.remove(); this.grad = this.defs.appendChild(paint[ptype]); var id = this.grad.id = 'gradbox_' + this.type; fillAttr = 'url(#' + id + ')'; break; } } this.rect.setAttribute('fill', fillAttr); this.rect.setAttribute('opacity', opac); if (apply) { svgCanvas.setColor(this.type, this._paintColor, true); svgCanvas.setPaintOpacity(this.type, this._paintOpacity, true); } } /** * @param {boolean} apply * @returns {void} */ }, { key: "update", value: function update(apply) { if (!selectedElement) { return; } var type = this.type; switch (selectedElement.tagName) { case 'use': case 'image': case 'foreignObject': // These elements don't have fill or stroke, so don't change // the current value return; case 'g': case 'a': { var childs = selectedElement.getElementsByTagName('*'); var gPaint = null; for (var _i2 = 0, len = childs.length; _i2 < len; _i2++) { var elem = childs[_i2]; var p = elem.getAttribute(type); if (_i2 === 0) { gPaint = p; } else if (gPaint !== p) { gPaint = null; break; } } if (gPaint === null) { // No common color, don't update anything this._paintColor = null; return; } this._paintColor = gPaint; this._paintOpacity = 1; break; } default: { this._paintOpacity = Number.parseFloat(selectedElement.getAttribute(type + '-opacity')); if (Number.isNaN(this._paintOpacity)) { this._paintOpacity = 1.0; } var defColor = type === 'fill' ? 'black' : 'none'; this._paintColor = selectedElement.getAttribute(type) || defColor; } } if (apply) { svgCanvas.setColor(type, this._paintColor, true); svgCanvas.setPaintOpacity(type, this._paintOpacity, true); } this._paintOpacity *= 100; var paint = getPaint(this._paintColor, this._paintOpacity, type); // update the rect inside #fill_color/#stroke_color this.setPaint(paint); } /** * @returns {void} */ }, { key: "prep", value: function prep() { var ptype = this.paint.type; switch (ptype) { case 'linearGradient': case 'radialGradient': { var paint = new $$d.jGraduate.Paint({ copy: this.paint }); svgCanvas.setPaint(this.type, paint); break; } } } }]); return PaintBox; }(); PaintBox.ctr = 0; paintBox.fill = new PaintBox('#fill_color', 'fill'); paintBox.stroke = new PaintBox('#stroke_color', 'stroke'); $$d('#stroke_width').val(curConfig.initStroke.width); $$d('#group_opacity').val(curConfig.initOpacity * 100); // Use this SVG elem to test vectorEffect support var testEl = paintBox.fill.rect.cloneNode(false); testEl.setAttribute('style', 'vector-effect:non-scaling-stroke'); var supportsNonSS = testEl.style.vectorEffect === 'non-scaling-stroke'; testEl.removeAttribute('style'); var svgdocbox = paintBox.fill.rect.ownerDocument; // Use this to test support for blur element. Seems to work to test support in Webkit var blurTest = svgdocbox.createElementNS(NS.SVG, 'feGaussianBlur'); if (blurTest.stdDeviationX === undefined) { $$d('#tool_blur').hide(); } $$d(blurTest).remove(); // Test for zoom icon support (function () { var pre = '-' + uaPrefix.toLowerCase() + '-zoom-'; var zoom = pre + 'in'; workarea.css('cursor', zoom); if (workarea.css('cursor') === zoom) { zoomInIcon = zoom; zoomOutIcon = pre + 'out'; } workarea.css('cursor', 'auto'); })(); // Test for embedImage support (use timeout to not interfere with page load) setTimeout(function () { svgCanvas.embedImage('images/logo.png', function (datauri) { if (!datauri) { // Disable option $$d('#image_save_opts [value=embed]').attr('disabled', 'disabled'); $$d('#image_save_opts input').val(['ref']); editor.pref('img_save', 'ref'); $$d('#image_opt_embed').css('color', '#666').attr('title', uiStrings$1.notification.featNotSupported); } }); }, 1000); $$d('#fill_color, #tool_fill .icon_label').click(function () { colorPicker($$d('#fill_color')); updateToolButtonState(); }); $$d('#stroke_color, #tool_stroke .icon_label').click(function () { colorPicker($$d('#stroke_color')); updateToolButtonState(); }); $$d('#group_opacityLabel').click(function () { $$d('#opacity_dropdown button').mousedown(); $$d(window).mouseup(); }); $$d('#zoomLabel').click(function () { $$d('#zoom_dropdown button').mousedown(); $$d(window).mouseup(); }); $$d('#tool_move_top').mousedown(function (evt) { $$d('#tools_stacking').show(); evt.preventDefault(); }); $$d('.layer_button').mousedown(function () { $$d(this).addClass('layer_buttonpressed'); }).mouseout(function () { $$d(this).removeClass('layer_buttonpressed'); }).mouseup(function () { $$d(this).removeClass('layer_buttonpressed'); }); $$d('.push_button').mousedown(function () { if (!$$d(this).hasClass('disabled')) { $$d(this).addClass('push_button_pressed').removeClass('push_button'); } }).mouseout(function () { $$d(this).removeClass('push_button_pressed').addClass('push_button'); }).mouseup(function () { $$d(this).removeClass('push_button_pressed').addClass('push_button'); }); // ask for a layer name $$d('#layer_new').click( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14() { var uniqName, i, newName; return regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: i = svgCanvas.getCurrentDrawing().getNumLayers(); do { uniqName = uiStrings$1.layers.layer + ' ' + ++i; } while (svgCanvas.getCurrentDrawing().hasLayer(uniqName)); _context14.next = 4; return $$d.prompt(uiStrings$1.notification.enterUniqueLayerName, uniqName); case 4: newName = _context14.sent; if (newName) { _context14.next = 7; break; } return _context14.abrupt("return"); case 7: if (!svgCanvas.getCurrentDrawing().hasLayer(newName)) { _context14.next = 10; break; } /* await */ $$d.alert(uiStrings$1.notification.dupeLayerName); return _context14.abrupt("return"); case 10: svgCanvas.createLayer(newName); updateContextPanel(); populateLayers(); case 13: case "end": return _context14.stop(); } } }, _callee14); }))); /** * * @returns {void} */ function deleteLayer() { if (svgCanvas.deleteCurrentLayer()) { updateContextPanel(); populateLayers(); // This matches what SvgCanvas does // TODO: make this behavior less brittle (svg-editor should get which // layer is selected from the canvas and then select that one in the UI) $$d('#layerlist tr.layer').removeClass('layersel'); $$d('#layerlist tr.layer:first').addClass('layersel'); } } /** * * @returns {Promise} */ function cloneLayer() { return _cloneLayer.apply(this, arguments); } /** * * @returns {void} */ function _cloneLayer() { _cloneLayer = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee20() { var name, newName; return regeneratorRuntime.wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: name = svgCanvas.getCurrentDrawing().getCurrentLayerName() + ' copy'; _context20.next = 3; return $$d.prompt(uiStrings$1.notification.enterUniqueLayerName, name); case 3: newName = _context20.sent; if (newName) { _context20.next = 6; break; } return _context20.abrupt("return"); case 6: if (!svgCanvas.getCurrentDrawing().hasLayer(newName)) { _context20.next = 9; break; } /* await */ $$d.alert(uiStrings$1.notification.dupeLayerName); return _context20.abrupt("return"); case 9: svgCanvas.cloneLayer(newName); updateContextPanel(); populateLayers(); case 12: case "end": return _context20.stop(); } } }, _callee20); })); return _cloneLayer.apply(this, arguments); } function mergeLayer() { if ($$d('#layerlist tr.layersel').index() === svgCanvas.getCurrentDrawing().getNumLayers() - 1) { return; } svgCanvas.mergeLayer(); updateContextPanel(); populateLayers(); } /** * @param {Integer} pos * @returns {void} */ function moveLayer(pos) { var total = svgCanvas.getCurrentDrawing().getNumLayers(); var curIndex = $$d('#layerlist tr.layersel').index(); if (curIndex > 0 || curIndex < total - 1) { curIndex += pos; svgCanvas.setCurrentLayerPosition(total - curIndex - 1); populateLayers(); } } $$d('#layer_delete').click(deleteLayer); $$d('#layer_up').click(function () { moveLayer(-1); }); $$d('#layer_down').click(function () { moveLayer(1); }); $$d('#layer_rename').click( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee15() { var oldName, newName; return regeneratorRuntime.wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: // const curIndex = $('#layerlist tr.layersel').prevAll().length; // Currently unused oldName = $$d('#layerlist tr.layersel td.layername').text(); _context15.next = 3; return $$d.prompt(uiStrings$1.notification.enterNewLayerName, ''); case 3: newName = _context15.sent; if (newName) { _context15.next = 6; break; } return _context15.abrupt("return"); case 6: if (!(oldName === newName || svgCanvas.getCurrentDrawing().hasLayer(newName))) { _context15.next = 9; break; } /* await */ $$d.alert(uiStrings$1.notification.layerHasThatName); return _context15.abrupt("return"); case 9: svgCanvas.renameCurrentLayer(newName); populateLayers(); case 11: case "end": return _context15.stop(); } } }, _callee15); }))); var SIDEPANEL_MAXWIDTH = 300; var SIDEPANEL_OPENWIDTH = 150; var sidedrag = -1, sidedragging = false, allowmove = false; /** * @param {Float} delta * @fires module:svgcanvas.SvgCanvas#event:ext_workareaResized * @returns {void} */ var changeSidePanelWidth = function changeSidePanelWidth(delta) { var rulerX = $$d('#ruler_x'); $$d('#sidepanels').width('+=' + delta); $$d('#layerpanel').width('+=' + delta); rulerX.css('right', Number.parseInt(rulerX.css('right')) + delta); workarea.css('right', Number.parseInt(workarea.css('right')) + delta); svgCanvas.runExtensions('workareaResized'); }; /** * @param {Event} evt * @returns {void} */ var resizeSidePanel = function resizeSidePanel(evt) { if (!allowmove) { return; } if (sidedrag === -1) { return; } sidedragging = true; var deltaX = sidedrag - evt.pageX; var sideWidth = $$d('#sidepanels').width(); if (sideWidth + deltaX > SIDEPANEL_MAXWIDTH) { deltaX = SIDEPANEL_MAXWIDTH - sideWidth; // sideWidth = SIDEPANEL_MAXWIDTH; } else if (sideWidth + deltaX < 2) { deltaX = 2 - sideWidth; // sideWidth = 2; } if (deltaX === 0) { return; } sidedrag -= deltaX; changeSidePanelWidth(deltaX); }; /** * If width is non-zero, then fully close it; otherwise fully open it. * @param {boolean} close Forces the side panel closed * @returns {void} */ var toggleSidePanel = function toggleSidePanel(close) { var dpr = window.devicePixelRatio || 1; var w = $$d('#sidepanels').width(); var isOpened = (dpr < 1 ? w : w / dpr) > 2; var zoomAdjustedSidepanelWidth = (dpr < 1 ? 1 : dpr) * SIDEPANEL_OPENWIDTH; var deltaX = (isOpened || close ? 0 : zoomAdjustedSidepanelWidth) - w; changeSidePanelWidth(deltaX); }; $$d('#sidepanel_handle').mousedown(function (evt) { sidedrag = evt.pageX; $$d(window).mousemove(resizeSidePanel); allowmove = false; // Silly hack for Chrome, which always runs mousemove right after mousedown setTimeout(function () { allowmove = true; }, 20); }).mouseup(function (evt) { if (!sidedragging) { toggleSidePanel(); } sidedrag = -1; sidedragging = false; }); $$d(window).mouseup(function () { sidedrag = -1; sidedragging = false; $$d('#svg_editor').unbind('mousemove', resizeSidePanel); }); populateLayers(); // function changeResolution (x,y) { // const {zoom} = svgCanvas.getResolution(); // setResolution(x * zoom, y * zoom); // } var centerCanvas = function centerCanvas() { // this centers the canvas vertically in the workarea (horizontal handled in CSS) workarea.css('line-height', workarea.height() + 'px'); }; $$d(window).bind('load resize', centerCanvas); /** * @type {module:jQuerySpinButton.StepCallback} */ function stepFontSize(elem, step) { var origVal = Number(elem.value); var sugVal = origVal + step; var increasing = sugVal >= origVal; if (step === 0) { return origVal; } if (origVal >= 24) { if (increasing) { return Math.round(origVal * 1.1); } return Math.round(origVal / 1.1); } if (origVal <= 1) { if (increasing) { return origVal * 2; } return origVal / 2; } return sugVal; } /** * @type {module:jQuerySpinButton.StepCallback} */ function stepZoom(elem, step) { var origVal = Number(elem.value); if (origVal === 0) { return 100; } var sugVal = origVal + step; if (step === 0) { return origVal; } if (origVal >= 100) { return sugVal; } if (sugVal >= origVal) { return origVal * 2; } return origVal / 2; } // function setResolution (w, h, center) { // updateCanvas(); // // w -= 0; h -= 0; // // $('#svgcanvas').css({width: w, height: h}); // // $('#canvas_width').val(w); // // $('#canvas_height').val(h); // // // // if (center) { // // const wArea = workarea; // // const scrollY = h/2 - wArea.height()/2; // // const scrollX = w/2 - wArea.width()/2; // // wArea[0].scrollTop = scrollY; // // wArea[0].scrollLeft = scrollX; // // } // } $$d('#resolution').change(function () { var wh = $$d('#canvas_width,#canvas_height'); if (!this.selectedIndex) { if ($$d('#canvas_width').val() === 'fit') { wh.removeAttr('disabled').val(100); } } else if (this.value === 'content') { wh.val('fit').attr('disabled', 'disabled'); } else { var dims = this.value.split('x'); $$d('#canvas_width').val(dims[0]); $$d('#canvas_height').val(dims[1]); wh.removeAttr('disabled'); } }); // Prevent browser from erroneously repopulating fields $$d('input,select').attr('autocomplete', 'off'); var dialogSelectors = ['#tool_source_cancel', '#tool_docprops_cancel', '#tool_prefs_cancel', '.overlay']; /* eslint-disable jsdoc/require-property */ /** * Associate all button actions as well as non-button keyboard shortcuts. * @namespace {PlainObject} module:SVGEditor~Actions */ var Actions = function () { /* eslint-enable jsdoc/require-property */ /** * @typedef {PlainObject} module:SVGEditor.ToolButton * @property {string} sel The CSS selector for the tool * @property {external:jQuery.Function} fn A handler to be attached to the `evt` * @property {string} evt The event for which the `fn` listener will be added * @property {module:SVGEditor.Key} [key] [key, preventDefault, NoDisableInInput] * @property {string} [parent] Selector * @property {boolean} [hidekey] Whether to show key value in title * @property {string} [icon] The button ID * @property {boolean} isDefault For flyout holders */ /** * * @name module:SVGEditor~ToolButtons * @type {module:SVGEditor.ToolButton[]} */ var toolButtons = [{ sel: '#tool_select', fn: clickSelect, evt: 'click', key: ['V', true] }, { sel: '#tool_fhpath', fn: clickFHPath, evt: 'click', key: ['Q', true] }, { sel: '#tool_line', fn: clickLine, evt: 'click', key: ['L', true], parent: '#tools_line', prepend: true }, { sel: '#tool_rect', fn: clickRect, evt: 'mouseup', key: ['R', true], parent: '#tools_rect', icon: 'rect' }, { sel: '#tool_square', fn: clickSquare, evt: 'mouseup', parent: '#tools_rect', icon: 'square' }, { sel: '#tool_fhrect', fn: clickFHRect, evt: 'mouseup', parent: '#tools_rect', icon: 'fh_rect' }, { sel: '#tool_ellipse', fn: clickEllipse, evt: 'mouseup', key: ['E', true], parent: '#tools_ellipse', icon: 'ellipse' }, { sel: '#tool_circle', fn: clickCircle, evt: 'mouseup', parent: '#tools_ellipse', icon: 'circle' }, { sel: '#tool_fhellipse', fn: clickFHEllipse, evt: 'mouseup', parent: '#tools_ellipse', icon: 'fh_ellipse' }, { sel: '#tool_path', fn: clickPath, evt: 'click', key: ['P', true] }, { sel: '#tool_text', fn: clickText, evt: 'click', key: ['T', true] }, { sel: '#tool_image', fn: clickImage, evt: 'mouseup' }, { sel: '#tool_zoom', fn: clickZoom, evt: 'mouseup', key: ['Z', true] }, { sel: '#tool_clear', fn: clickClear, evt: 'mouseup', key: ['N', true] }, { sel: '#tool_save', fn: function fn() { if (editingsource) { saveSourceEditor(); } else { clickSave(); } }, evt: 'mouseup', key: ['S', true] }, { sel: '#tool_export', fn: clickExport, evt: 'mouseup' }, { sel: '#tool_open', fn: clickOpen, evt: 'mouseup', key: ['O', true] }, { sel: '#tool_import', fn: clickImport, evt: 'mouseup' }, { sel: '#tool_source', fn: showSourceEditor, evt: 'click', key: ['U', true] }, { sel: '#tool_wireframe', fn: clickWireframe, evt: 'click', key: ['F', true] }, { key: ['esc', false, false], fn: function fn() { if (dialogSelectors.every(function (sel) { return $$d(sel + ':hidden').length; })) { svgCanvas.clearSelection(); } }, hidekey: true }, { sel: dialogSelectors.join(','), fn: cancelOverlays, evt: 'click', key: ['esc', false, false], hidekey: true }, { sel: '#tool_source_save', fn: saveSourceEditor, evt: 'click' }, { sel: '#tool_docprops_save', fn: saveDocProperties, evt: 'click' }, { sel: '#tool_docprops', fn: showDocProperties, evt: 'click' }, { sel: '#tool_prefs_save', fn: savePreferences, evt: 'click' }, { sel: '#tool_editor_prefs', fn: showPreferences, evt: 'click' }, { sel: '#tool_editor_homepage', fn: openHomePage, evt: 'click' }, { sel: '#tool_open', fn: function fn() { window.dispatchEvent(new CustomEvent('openImage')); }, evt: 'click' }, { sel: '#tool_import', fn: function fn() { window.dispatchEvent(new CustomEvent('importImage')); }, evt: 'click' }, { sel: '#tool_delete,#tool_delete_multi', fn: deleteSelected, evt: 'click', key: ['del/backspace', true] }, { sel: '#tool_reorient', fn: reorientPath, evt: 'click' }, { sel: '#tool_node_link', fn: linkControlPoints, evt: 'click' }, { sel: '#tool_node_clone', fn: clonePathNode, evt: 'click' }, { sel: '#tool_node_delete', fn: deletePathNode, evt: 'click' }, { sel: '#tool_openclose_path', fn: opencloseSubPath, evt: 'click' }, { sel: '#tool_add_subpath', fn: addSubPath, evt: 'click' }, { sel: '#tool_move_top', fn: moveToTopSelected, evt: 'click', key: 'ctrl+shift+]' }, { sel: '#tool_move_bottom', fn: moveToBottomSelected, evt: 'click', key: 'ctrl+shift+[' }, { sel: '#tool_topath', fn: convertToPath, evt: 'click' }, { sel: '#tool_make_link,#tool_make_link_multi', fn: makeHyperlink, evt: 'click' }, { sel: '#tool_undo', fn: clickUndo, evt: 'click' }, { sel: '#tool_redo', fn: clickRedo, evt: 'click' }, { sel: '#tool_clone,#tool_clone_multi', fn: clickClone, evt: 'click', key: ['D', true] }, { sel: '#tool_group_elements', fn: clickGroup, evt: 'click', key: ['G', true] }, { sel: '#tool_ungroup', fn: clickGroup, evt: 'click' }, { sel: '#tool_unlink_use', fn: clickGroup, evt: 'click' }, { sel: '[id^=tool_align]', fn: clickAlign, evt: 'click' }, // these two lines are required to make Opera work properly with the flyout mechanism // {sel: '#tools_rect_show', fn: clickRect, evt: 'click'}, // {sel: '#tools_ellipse_show', fn: clickEllipse, evt: 'click'}, { sel: '#tool_bold', fn: clickBold, evt: 'mousedown' }, { sel: '#tool_italic', fn: clickItalic, evt: 'mousedown' }, { sel: '#sidepanel_handle', fn: toggleSidePanel, key: ['X'] }, { sel: '#copy_save_done', fn: cancelOverlays, evt: 'click' }, // Shortcuts not associated with buttons { key: 'ctrl+left', fn: function fn() { rotateSelected(0, 1); } }, { key: 'ctrl+right', fn: function fn() { rotateSelected(1, 1); } }, { key: 'ctrl+shift+left', fn: function fn() { rotateSelected(0, 5); } }, { key: 'ctrl+shift+right', fn: function fn() { rotateSelected(1, 5); } }, { key: 'shift+O', fn: selectPrev }, { key: 'shift+P', fn: selectNext }, { key: [modKey + 'up', true], fn: function fn() { zoomImage(2); } }, { key: [modKey + 'down', true], fn: function fn() { zoomImage(0.5); } }, { key: [modKey + ']', true], fn: function fn() { moveUpDownSelected('Up'); } }, { key: [modKey + '[', true], fn: function fn() { moveUpDownSelected('Down'); } }, { key: ['up', true], fn: function fn() { moveSelected(0, -1); } }, { key: ['down', true], fn: function fn() { moveSelected(0, 1); } }, { key: ['left', true], fn: function fn() { moveSelected(-1, 0); } }, { key: ['right', true], fn: function fn() { moveSelected(1, 0); } }, { key: 'shift+up', fn: function fn() { moveSelected(0, -10); } }, { key: 'shift+down', fn: function fn() { moveSelected(0, 10); } }, { key: 'shift+left', fn: function fn() { moveSelected(-10, 0); } }, { key: 'shift+right', fn: function fn() { moveSelected(10, 0); } }, { key: ['alt+up', true], fn: function fn() { svgCanvas.cloneSelectedElements(0, -1); } }, { key: ['alt+down', true], fn: function fn() { svgCanvas.cloneSelectedElements(0, 1); } }, { key: ['alt+left', true], fn: function fn() { svgCanvas.cloneSelectedElements(-1, 0); } }, { key: ['alt+right', true], fn: function fn() { svgCanvas.cloneSelectedElements(1, 0); } }, { key: ['alt+shift+up', true], fn: function fn() { svgCanvas.cloneSelectedElements(0, -10); } }, { key: ['alt+shift+down', true], fn: function fn() { svgCanvas.cloneSelectedElements(0, 10); } }, { key: ['alt+shift+left', true], fn: function fn() { svgCanvas.cloneSelectedElements(-10, 0); } }, { key: ['alt+shift+right', true], fn: function fn() { svgCanvas.cloneSelectedElements(10, 0); } }, { key: 'a', fn: function fn() { svgCanvas.selectAllInCurrentLayer(); } }, { key: modKey + 'a', fn: function fn() { svgCanvas.selectAllInCurrentLayer(); } }, // Standard shortcuts { key: modKey + 'z', fn: clickUndo }, { key: modKey + 'shift+z', fn: clickRedo }, { key: modKey + 'y', fn: clickRedo }, { key: modKey + 'x', fn: cutSelected }, { key: modKey + 'c', fn: copySelected }, { key: modKey + 'v', fn: pasteInCenter }]; // Tooltips not directly associated with a single function var keyAssocs = { '4/Shift+4': '#tools_rect_show', '5/Shift+5': '#tools_ellipse_show' }; return { /** @lends module:SVGEditor~Actions */ /** * @returns {void} */ setAll: function setAll() { var flyouts = {}; var keyHandler = {}; // will contain the action for each pressed key toolButtons.forEach(function (opts) { // Bind function to button var btn; if (opts.sel) { btn = $q$1(opts.sel); if (btn === null) { return true; } // Skip if markup does not exist if (opts.evt) { // `touch.js` changes `touchstart` to `mousedown`, // so we must map tool button click events as well if (isTouch() && opts.evt === 'click') { opts.evt = 'mousedown'; } btn.addEventListener(opts.evt, opts.fn); } // Add to parent flyout menu, if able to be displayed if (opts.parent && $$d(opts.parent + '_show').length) { var fH = $$d(opts.parent); if (!fH.length) { fH = makeFlyoutHolder(opts.parent.substr(1)); } if (opts.prepend) { btn.style.margin = 'initial'; } fH[opts.prepend ? 'prepend' : 'append'](btn); if (!Array.isArray(flyouts[opts.parent])) { flyouts[opts.parent] = []; } flyouts[opts.parent].push(opts); } } // Bind function to shortcut key if (opts.key) { // Set shortcut based on options var keyval = opts.key; var pd = false; if (Array.isArray(opts.key)) { keyval = opts.key[0]; if (opts.key.length > 1) { pd = opts.key[1]; } } keyval = String(keyval); var fn = opts.fn; keyval.split('/').forEach(function (key) { keyHandler[key] = { fn: fn, pd: pd }; }); // Put shortcut in title if (opts.sel && !opts.hidekey && btn.title) { var newTitle = "".concat(btn.title.split('[')[0], " (").concat(keyval, ")"); keyAssocs[keyval] = opts.sel; // Disregard for menu items if (btn.closest('#main_menu') === null) { btn.title = newTitle; } } } return true; }); // register the keydown event document.addEventListener('keydown', function (e) { // only track keyboard shortcuts for the body containing the SVG-Editor if (e.target.nodeName !== 'BODY') return; // normalize key var key = "".concat(e.metaKey ? 'meta+' : '').concat(e.ctrlKey ? 'ctrl+' : '').concat(e.key.toLowerCase()); // return if no shortcut defined for this key if (!keyHandler[key]) return; // launch associated handler and preventDefault if necessary keyHandler[key].fn(); if (keyHandler[key].pd) { e.preventDefault(); } }); // Setup flyouts setupFlyouts(flyouts); // Misc additional actions // Make 'return' keypress trigger the change event $$d('.attr_changer, #image_url').bind('keydown', 'return', function (evt) { $$d(this).change(); evt.preventDefault(); }); $$d(window).bind('keydown', 'tab', function (e) { if (uiContext === 'canvas') { e.preventDefault(); selectNext(); } }).bind('keydown', 'shift+tab', function (e) { if (uiContext === 'canvas') { e.preventDefault(); selectPrev(); } }); $$d('#tool_zoom').dblclick(dblclickZoom); }, /** * @returns {void} */ setTitles: function setTitles() { $$d.each(keyAssocs, function (keyval, sel) { var menu = $$d(sel).parents('#main_menu').length; $$d(sel).each(function () { var t; if (menu) { t = $$d(this).text().split(' [')[0]; } else { t = this.title.split(' [')[0]; } var keyStr = ''; // Shift+Up $$d.each(keyval.split('/'), function (i, key) { var modBits = key.split('+'); var mod = ''; if (modBits.length > 1) { mod = modBits[0] + '+'; key = modBits[1]; } keyStr += (i ? '/' : '') + mod + (uiStrings$1['key_' + key] || key); }); if (menu) { this.lastChild.textContent = t + ' [' + keyStr + ']'; } else { this.title = t + ' [' + keyStr + ']'; } }); }); }, /** * @param {string} sel Selector to match * @returns {module:SVGEditor.ToolButton} */ getButtonData: function getButtonData(sel) { return Object.values(toolButtons).find(function (btn) { return btn.sel === sel; }); } }; }(); // Select given tool editor.ready(function () { var tool; var itool = curConfig.initTool, container = $$d('#tools_left, #svg_editor .tools_flyout'), preTool = container.find('#tool_' + itool), regTool = container.find('#' + itool); if (preTool.length) { tool = preTool; } else if (regTool.length) { tool = regTool; } else { tool = $$d('#tool_select'); } tool.click().mouseup(); if (curConfig.wireframe) { $$d('#tool_wireframe').click(); } if (curConfig.showlayers) { toggleSidePanel(); } $$d('#rulers').toggle(Boolean(curConfig.showRulers)); if (curConfig.showRulers) { $$d('#show_rulers')[0].checked = true; } if (curConfig.baseUnit) { $$d('#base_unit').val(curConfig.baseUnit); } if (curConfig.gridSnapping) { $$d('#grid_snapping_on')[0].checked = true; } if (curConfig.snappingStep) { $$d('#grid_snapping_step').val(curConfig.snappingStep); } if (curConfig.gridColor) { $$d('#grid_color').val(curConfig.gridColor); } }); // init SpinButtons $$d('#rect_rx').SpinButton({ min: 0, max: 1000, stateObj: stateObj, callback: changeRectRadius }); $$d('#stroke_width').SpinButton({ min: 0, max: 99, smallStep: 0.1, stateObj: stateObj, callback: changeStrokeWidth }); $$d('#angle').SpinButton({ min: -180, max: 180, step: 5, stateObj: stateObj, callback: changeRotationAngle }); $$d('#font_size').SpinButton({ min: 0.001, stepfunc: stepFontSize, stateObj: stateObj, callback: changeFontSize }); $$d('#group_opacity').SpinButton({ min: 0, max: 100, step: 5, stateObj: stateObj, callback: changeOpacity }); $$d('#blur').SpinButton({ min: 0, max: 10, step: 0.1, stateObj: stateObj, callback: changeBlur }); $$d('#zoom').SpinButton({ min: 0.001, max: 10000, step: 50, stepfunc: stepZoom, stateObj: stateObj, callback: changeZoom // Set default zoom }).val(svgCanvas.getZoom() * 100); $$d('#workarea').contextMenu({ menu: 'cmenu_canvas', inSpeed: 0 }, function (action, el, pos) { switch (action) { case 'delete': deleteSelected(); break; case 'cut': cutSelected(); break; case 'copy': copySelected(); break; case 'paste': svgCanvas.pasteElements(); break; case 'paste_in_place': svgCanvas.pasteElements('in_place'); break; case 'group': case 'group_elements': svgCanvas.groupSelectedElements(); break; case 'ungroup': svgCanvas.ungroupSelectedElement(); break; case 'move_front': moveToTopSelected(); break; case 'move_up': moveUpDownSelected('Up'); break; case 'move_down': moveUpDownSelected('Down'); break; case 'move_back': moveToBottomSelected(); break; default: if (hasCustomHandler(action)) { getCustomHandler(action).call(); } break; } }); /** * Implements {@see module:jQueryContextMenu.jQueryContextMenuListener}. * @param {"dupe"|"delete"|"merge_down"|"merge_all"} action * @param {external:jQuery} el * @param {{x: Float, y: Float, docX: Float, docY: Float}} pos * @returns {void} */ var lmenuFunc = function lmenuFunc(action, el, pos) { switch (action) { case 'dupe': /* await */ cloneLayer(); break; case 'delete': deleteLayer(); break; case 'merge_down': mergeLayer(); break; case 'merge_all': svgCanvas.mergeAllLayers(); updateContextPanel(); populateLayers(); break; } }; $$d('#layerlist').contextMenu({ menu: 'cmenu_layers', inSpeed: 0 }, lmenuFunc); $$d('#layer_moreopts').contextMenu({ menu: 'cmenu_layers', inSpeed: 0, allowLeft: true }, lmenuFunc); $$d('.contextMenu li').mousedown(function (ev) { ev.preventDefault(); }); $$d('#cmenu_canvas li').disableContextMenu(); canvMenu.enableContextMenuItems('#delete,#cut,#copy'); /** * @returns {void} */ function enableOrDisableClipboard() { var svgeditClipboard; try { svgeditClipboard = localStorage.getItem('svgedit_clipboard'); } catch (err) {} canvMenu[(svgeditClipboard ? 'en' : 'dis') + 'ableContextMenuItems']('#paste,#paste_in_place'); } enableOrDisableClipboard(); window.addEventListener('storage', function (e) { if (e.key !== 'svgedit_clipboard') { return; } enableOrDisableClipboard(); }); window.addEventListener('beforeunload', function (e) { // Suppress warning if page is empty if (undoMgr.getUndoStackSize() === 0) { editor.showSaveWarning = false; } // showSaveWarning is set to 'false' when the page is saved. if (!curConfig.no_save_warning && editor.showSaveWarning) { // Browser already asks question about closing the page e.returnValue = uiStrings$1.notification.unsavedChanges; // Firefox needs this when beforeunload set by addEventListener (even though message is not used) return uiStrings$1.notification.unsavedChanges; } return true; }); /** * Expose the `uiStrings`. * @function module:SVGEditor.canvas.getUIStrings * @returns {module:SVGEditor.uiStrings} */ editor.canvas.getUIStrings = function () { return uiStrings$1; }; /** * @function module:SVGEditor.openPrep * @returns {boolean|Promise} Resolves to boolean indicating `true` if there were no changes * and `false` after the user confirms. */ editor.openPrep = function () { $$d('#main_menu').hide(); if (undoMgr.getUndoStackSize() === 0) { return true; } return $$d.confirm(uiStrings$1.notification.QwantToOpen); }; /** * * @param {Event} e * @returns {void} */ function onDragEnter(e) { e.stopPropagation(); e.preventDefault(); // and indicator should be displayed here, such as "drop files here" } /** * * @param {Event} e * @returns {void} */ function onDragOver(e) { e.stopPropagation(); e.preventDefault(); } /** * * @param {Event} e * @returns {void} */ function onDragLeave(e) { e.stopPropagation(); e.preventDefault(); // hypothetical indicator should be removed here } // Use HTML5 File API: http://www.w3.org/TR/FileAPI/ // if browser has HTML5 File API support, then we will show the open menu item // and provide a file input to click. When that change event fires, it will // get the text contents of the file and send it to the canvas if (window.FileReader) { /** * @param {Event} e * @returns {void} */ var importImage = function importImage(e) { $$d.process_cancel(uiStrings$1.notification.loadingImage); e.stopPropagation(); e.preventDefault(); $$d('#main_menu').hide(); var file = e.type === 'drop' ? e.dataTransfer.files[0] : this.files[0]; if (!file) { $$d('#dialog_box').hide(); return; } /* if (file.type === 'application/pdf') { // Todo: Handle PDF imports } else */ if (!file.type.includes('image')) { return; } // Detected an image // svg handling var reader; if (file.type.includes('svg')) { reader = new FileReader(); reader.onloadend = function (ev) { var newElement = svgCanvas.importSvgString(ev.target.result, true); svgCanvas.ungroupSelectedElement(); svgCanvas.ungroupSelectedElement(); svgCanvas.groupSelectedElements(); svgCanvas.alignSelectedElements('m', 'page'); svgCanvas.alignSelectedElements('c', 'page'); // highlight imported element, otherwise we get strange empty selectbox svgCanvas.selectOnly([newElement]); $$d('#dialog_box').hide(); }; reader.readAsText(file); } else { // bitmap handling reader = new FileReader(); reader.onloadend = function (_ref22) { var result = _ref22.target.result; /** * Insert the new image until we know its dimensions. * @param {Float} width * @param {Float} height * @returns {void} */ var insertNewImage = function insertNewImage(width, height) { var newImage = svgCanvas.addSVGElementFromJson({ element: 'image', attr: { x: 0, y: 0, width: width, height: height, id: svgCanvas.getNextId(), style: 'pointer-events:inherit' } }); svgCanvas.setHref(newImage, result); svgCanvas.selectOnly([newImage]); svgCanvas.alignSelectedElements('m', 'page'); svgCanvas.alignSelectedElements('c', 'page'); updateContextPanel(); $$d('#dialog_box').hide(); }; // create dummy img so we know the default dimensions var imgWidth = 100; var imgHeight = 100; var img = new Image(); img.style.opacity = 0; img.addEventListener('load', function () { imgWidth = img.offsetWidth || img.naturalWidth || img.width; imgHeight = img.offsetHeight || img.naturalHeight || img.height; insertNewImage(imgWidth, imgHeight); }); img.src = result; }; reader.readAsDataURL(file); } }; workarea[0].addEventListener('dragenter', onDragEnter); workarea[0].addEventListener('dragover', onDragOver); workarea[0].addEventListener('dragleave', onDragLeave); workarea[0].addEventListener('drop', importImage); var open = $$d('').change( /*#__PURE__*/function () { var _ref23 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee17(e) { var ok, reader; return regeneratorRuntime.wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: _context17.next = 2; return editor.openPrep(); case 2: ok = _context17.sent; if (ok) { _context17.next = 5; break; } return _context17.abrupt("return"); case 5: svgCanvas.clear(); if (this.files.length === 1) { $$d.process_cancel(uiStrings$1.notification.loadingImage); reader = new FileReader(); reader.onloadend = /*#__PURE__*/function () { var _ref25 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee16(_ref24) { var target; return regeneratorRuntime.wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: target = _ref24.target; _context16.next = 3; return loadSvgString(target.result); case 3: updateCanvas(); case 4: case "end": return _context16.stop(); } } }, _callee16); })); return function (_x7) { return _ref25.apply(this, arguments); }; }(); reader.readAsText(this.files[0]); } case 7: case "end": return _context17.stop(); } } }, _callee17, this); })); return function (_x6) { return _ref23.apply(this, arguments); }; }()); $$d('#tool_open').show(); $$d(window).on('openImage', function () { return open.click(); }); var imgImport = $$d('').change(importImage); $$d('#tool_import').show(); $$d(window).on('importImage', function () { return imgImport.click(); }); } updateCanvas(true); // const revnums = 'svg-editor.js ($Rev$) '; // revnums += svgCanvas.getVersion(); // $('#copyright')[0].setAttribute('title', revnums); var loadedExtensionNames = []; /** * @function module:SVGEditor.setLang * @param {string} lang The language code * @param {module:locale.LocaleStrings} allStrings See {@tutorial LocaleDocs} * @fires module:svgcanvas.SvgCanvas#event:ext_langReady * @fires module:svgcanvas.SvgCanvas#event:ext_langChanged * @returns {Promise} A Promise which resolves to `undefined` */ var setLang = editor.setLang = /*#__PURE__*/function () { var _ref26 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee18(lang, allStrings) { var oldLayerName, renameLayer, elems; return regeneratorRuntime.wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: editor.langChanged = true; editor.pref('lang', lang); $$d('#lang_select').val(lang); if (allStrings) { _context18.next = 5; break; } return _context18.abrupt("return"); case 5: // Todo: Remove `allStrings.lang` property in locale in // favor of just `lang`? document.documentElement.lang = allStrings.lang; // lang; // Todo: Add proper RTL Support! // Todo: Use RTL detection instead and take out of locales? // document.documentElement.dir = allStrings.dir; $$d.extend(uiStrings$1, allStrings); // const notif = allStrings.notification; // Currently unused // $.extend will only replace the given strings oldLayerName = $$d('#layerlist tr.layersel td.layername').text(); renameLayer = oldLayerName === uiStrings$1.common.layer + ' 1'; svgCanvas.setUiStrings(allStrings); Actions.setTitles(); if (renameLayer) { svgCanvas.renameCurrentLayer(uiStrings$1.common.layer + ' 1'); populateLayers(); } // In case extensions loaded before the locale, now we execute a callback on them if (!extsPreLang.length) { _context18.next = 18; break; } _context18.next = 15; return Promise.all(extsPreLang.map(function (ext) { loadedExtensionNames.push(ext.name); return ext.langReady({ lang: lang, uiStrings: uiStrings$1, importLocale: getImportLocale({ defaultLang: lang, defaultName: ext.name }) }); })); case 15: extsPreLang.length = 0; _context18.next = 19; break; case 18: loadedExtensionNames.forEach(function (loadedExtensionName) { svgCanvas.runExtension(loadedExtensionName, 'langReady', /** @type {module:svgcanvas.SvgCanvas#event:ext_langReady} */ { lang: lang, uiStrings: uiStrings$1, importLocale: getImportLocale({ defaultLang: lang, defaultName: loadedExtensionName }) }); }); case 19: svgCanvas.runExtensions('langChanged', /** @type {module:svgcanvas.SvgCanvas#event:ext_langChanged} */ lang); // Update flyout tooltips setFlyoutTitles(); // Copy title for certain tool elements elems = { '#stroke_color': '#tool_stroke .icon_label, #tool_stroke .color_block', '#fill_color': '#tool_fill label, #tool_fill .color_block', '#linejoin_miter': '#cur_linejoin', '#linecap_butt': '#cur_linecap' }; $$d.each(elems, function (source, dest) { $$d(dest).attr('title', $$d(source)[0].title); }); // Copy alignment titles $$d('#multiselected_panel div[id^=tool_align]').each(function () { $$d('#tool_pos' + this.id.substr(10))[0].title = this.title; }); case 24: case "end": return _context18.stop(); } } }, _callee18); })); return function (_x8, _x9) { return _ref26.apply(this, arguments); }; }(); init$7( /** * @implements {module:locale.LocaleEditorInit} */ { /** * Gets an array of results from extensions with a `addLangData` method, * returning an object with a `data` property set to its locales (to be * merged with regular locales). * @param {string} langParam * @fires module:svgcanvas.SvgCanvas#event:ext_addLangData * @todo Can we forego this in favor of `langReady` (or forego `langReady`)? * @returns {module:locale.AddLangExtensionLocaleData[]} */ addLangData: function addLangData(langParam) { return svgCanvas.runExtensions('addLangData', /** * @function * @type {module:svgcanvas.ExtensionVarBuilder} * @param {string} name * @returns {module:svgcanvas.SvgCanvas#event:ext_addLangData} */ function (name) { // We pass in a function as we don't know the extension name here when defining this `addLangData` method return { lang: langParam, importLocale: getImportLocale({ defaultLang: langParam, defaultName: name }) }; }, true); }, curConfig: curConfig }); // Load extensions // Bit of a hack to run extensions in local Opera/IE9 if (document.location.protocol === 'file:') { setTimeout(extAndLocaleFunc, 100); } else { // Returns a promise (if we wanted to fire 'extensions-loaded' event, // potentially useful to hide interface as some extension locales // are only available after this) extAndLocaleFunc(); } }; /** * @callback module:SVGEditor.ReadyCallback * @returns {Promise|void} */ /** * Queues a callback to be invoked when the editor is ready (or * to be invoked immediately if it is already ready--i.e., * if `runCallbacks` has been run). * @function module:SVGEditor.ready * @param {module:SVGEditor.ReadyCallback} cb Callback to be queued to invoke * @returns {Promise} Resolves when all callbacks, including the supplied have resolved */ editor.ready = function (cb) { // eslint-disable-line promise/prefer-await-to-callbacks return new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new if (isReady) { resolve(cb()); // eslint-disable-line node/callback-return, promise/prefer-await-to-callbacks return; } callbacks.push([cb, resolve, reject]); }); }; /** * Invokes the callbacks previous set by `svgEditor.ready` * @function module:SVGEditor.runCallbacks * @returns {Promise} Resolves to `undefined` if all callbacks succeeded and rejects otherwise */ editor.runCallbacks = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee21() { return regeneratorRuntime.wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: _context21.prev = 0; _context21.next = 3; return Promise.all(callbacks.map(function (_ref29) { var _ref30 = _slicedToArray(_ref29, 1), cb = _ref30[0]; return cb(); // eslint-disable-line promise/prefer-await-to-callbacks })); case 3: _context21.next = 9; break; case 5: _context21.prev = 5; _context21.t0 = _context21["catch"](0); callbacks.forEach(function (_ref31) { var _ref32 = _slicedToArray(_ref31, 3), reject = _ref32[2]; reject(); }); throw _context21.t0; case 9: callbacks.forEach(function (_ref33) { var _ref34 = _slicedToArray(_ref33, 2), resolve = _ref34[1]; resolve(); }); isReady = true; case 11: case "end": return _context21.stop(); } } }, _callee21, null, [[0, 5]]); })); /** * @function module:SVGEditor.loadFromString * @param {string} str The SVG string to load * @param {PlainObject} [opts={}] * @param {boolean} [opts.noAlert=false] Option to avoid alert to user and instead get rejected promise * @returns {Promise} */ editor.loadFromString = function (str) { var _ref35 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, noAlert = _ref35.noAlert; return editor.ready( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee22() { return regeneratorRuntime.wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: _context22.prev = 0; _context22.next = 3; return loadSvgString(str, { noAlert: noAlert }); case 3: _context22.next = 9; break; case 5: _context22.prev = 5; _context22.t0 = _context22["catch"](0); if (!noAlert) { _context22.next = 9; break; } throw _context22.t0; case 9: case "end": return _context22.stop(); } } }, _callee22, null, [[0, 5]]); }))); }; /** * Not presently in use. * @function module:SVGEditor.disableUI * @param {PlainObject} featList * @returns {void} */ editor.disableUI = function (featList) {// $(function () { // $('#tool_wireframe, #tool_image, #main_button, #tool_source, #sidepanels').remove(); // $('#tools_top').css('left', 5); // }); }; /** * @callback module:SVGEditor.URLLoadCallback * @param {boolean} success * @returns {void} */ /** * @function module:SVGEditor.loadFromURL * @param {string} url URL from which to load an SVG string via Ajax * @param {PlainObject} [opts={}] May contain properties: `cache`, `callback` * @param {boolean} [opts.cache] * @param {boolean} [opts.noAlert] * @returns {Promise} Resolves to `undefined` or rejects upon bad loading of * the SVG (or upon failure to parse the loaded string) when `noAlert` is * enabled */ editor.loadFromURL = function (url) { var _ref37 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, cache = _ref37.cache, noAlert = _ref37.noAlert; return editor.ready(function () { return new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new $$d.ajax({ url: url, dataType: 'text', cache: Boolean(cache), beforeSend: function beforeSend() { $$d.process_cancel(uiStrings$1.notification.loadingImage); }, success: function success(str) { resolve(loadSvgString(str, { noAlert: noAlert })); }, error: function error(xhr, stat, err) { if (xhr.status !== 404 && xhr.responseText) { resolve(loadSvgString(xhr.responseText, { noAlert: noAlert })); return; } if (noAlert) { reject(new Error('URLLoadFail')); return; } $$d.alert(uiStrings$1.notification.URLLoadFail + ': \n' + err); resolve(); }, complete: function complete() { $$d('#dialog_box').hide(); } }); }); }); }; /** * @function module:SVGEditor.loadFromDataURI * @param {string} str The Data URI to base64-decode (if relevant) and load * @param {PlainObject} [opts={}] * @param {boolean} [opts.noAlert] * @returns {Promise} Resolves to `undefined` and rejects if loading SVG string fails and `noAlert` is enabled */ editor.loadFromDataURI = function (str) { var _ref38 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, noAlert = _ref38.noAlert; return editor.ready(function () { var base64 = false; var pre = str.match(/^data:image\/svg\+xml;base64,/); if (pre) { base64 = true; } else { pre = str.match(/^data:image\/svg\+xml(?:;|;utf8)?,/); } if (pre) { pre = pre[0]; } var src = str.slice(pre.length); return loadSvgString(base64 ? decode64(src) : decodeURIComponent(src), { noAlert: noAlert }); }); }; /** * @function module:SVGEditor.addExtension * @param {string} name Used internally; no need for i18n. * @param {module:svgcanvas.ExtensionInitCallback} init Config to be invoked on this module * @param {module:svgcanvas.ExtensionInitArgs} initArgs * @throws {Error} If called too early * @returns {Promise} Resolves to `undefined` */ editor.addExtension = function (name, init, initArgs) { // Note that we don't want this on editor.ready since some extensions // may want to run before then (like server_opensave). // $(function () { if (!svgCanvas) { throw new Error('Extension added too early'); } return svgCanvas.addExtension.call(this, name, init, initArgs); // }); }; // Defer injection to wait out initial menu processing. This probably goes // away once all context menu behavior is brought to context menu. editor.ready(function () { injectExtendedContextMenuItemsIntoDom(); }); var extensionsAdded = false; var messageQueue = []; /** * @param {PlainObject} info * @param {any} info.data * @param {string} info.origin * @fires module:svgcanvas.SvgCanvas#event:message * @returns {void} */ var messageListener = function messageListener(_ref39) { var data = _ref39.data, origin = _ref39.origin; // eslint-disable-line no-shadow // console.log('data, origin, extensionsAdded', data, origin, extensionsAdded); var messageObj = { data: data, origin: origin }; if (!extensionsAdded) { messageQueue.push(messageObj); } else { // Extensions can handle messages at this stage with their own // canvas `message` listeners svgCanvas.call('message', messageObj); } }; window.addEventListener('message', messageListener); // Run init once DOM is loaded // jQuery(editor.init); _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee23() { return regeneratorRuntime.wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: _context23.prev = 0; _context23.next = 3; return Promise.resolve(); case 3: editor.init(); _context23.next = 9; break; case 6: _context23.prev = 6; _context23.t0 = _context23["catch"](0); console.error(_context23.t0); // eslint-disable-line no-console case 9: case "end": return _context23.stop(); } } }, _callee23, null, [[0, 6]]); }))(); editor.setConfig({ /* To override the ability for URLs to set URL-based SVG content, uncomment the following: */ // preventURLContentLoading: true, /* To override the ability for URLs to set other configuration (including extension config), uncomment the following: */ // preventAllURLConfig: true, /* To override the ability for URLs to set their own extensions, uncomment the following (note that if `setConfig()` is used in extension code, it will still be additive to extensions, however): */ // lockExtensions: true, }); editor.setConfig({ /* Provide default values here which differ from that of the editor but which the URL can override */ }, { allowInitialUserOverride: true }); // EXTENSION CONFIG editor.setConfig({ extensions: [// 'ext-overview_window.js', 'ext-markers.js', 'ext-connector.js', // 'ext-eyedropper.js', 'ext-shapes.js', 'ext-imagelib.js', // 'ext-grid.js', 'ext-polygon.js', 'ext-star.js', 'ext-panning.js', // 'ext-storage.js' ], // noDefaultExtensions can only be meaningfully used in // `svgedit-config-es.js` or in the URL noDefaultExtensions: false }); // OTHER CONFIG editor.setConfig({// canvasName: 'default', // canvas_expansion: 3, // initFill: { // color: 'FF0000', // solid red // opacity: 1 // }, // initStroke: { // width: 5, // color: '000000', // solid black // opacity: 1 // }, // initOpacity: 1, // colorPickerCSS: null, // initTool: 'select', // exportWindowType: 'new', // 'same' // wireframe: false, // showlayers: false, // no_save_warning: false, // PATH CONFIGURATION // imgPath: 'images/', // extPath: 'extensions/', /* Uncomment the following to allow at least same domain (embedded) access, including `file:///` access. Setting as `['*']` would allow any domain to access but would be unsafe to data privacy and integrity. */ // May be 'null' (as a string) when used as a `file:///` URL // allowedOrigins: [location.origin || 'null'], // DOCUMENT PROPERTIES // dimensions: [640, 480], // EDITOR OPTIONS // gridSnapping: false, // gridColor: '#000', // baseUnit: 'px', // snappingStep: 10, // showRulers: true, // EXTENSION-RELATED (GRID) // showGrid: false, // Set by ext-grid.js // EXTENSION-RELATED (STORAGE) // Some interaction with `ext-storage.js`; prevent even the loading of // previously saved local storage // noStorageOnLoad: false, // Some interaction with `ext-storage.js`; strongly discouraged from // modification as it bypasses user privacy by preventing them from // choosing whether to keep local storage or not // forceStorage: false, // Used by `ext-storage.js`; empty any prior storage if the user // declines to store // emptyStorageOnDecline: true, }); // PREF CHANGES /* setConfig() can also be used to set preferences in addition to configuration (see defaultPrefs in svg-editor.js for a list of possible settings), but at least if you are using ext-storage.js to store preferences, it will probably be better to let your users control these. As with configuration, one may use allowInitialUserOverride, but in the case of preferences, any previously stored preferences will also thereby be enabled to override this setting (and at a higher priority than any URL preference setting overrides). Failing to use allowInitialUserOverride will ensure preferences are hard-coded here regardless of URL or prior user storage setting. */ editor.setConfig({// Set dynamically within locale.js if not previously set // lang: '', // Will default to 's' if the window height is smaller than the minimum // height and 'm' otherwise // iconsize: '', /** * When showing the preferences dialog, svg-editor.js currently relies * on `curPrefs` instead of `svgEditor.pref`, so allowing an override for * `bkgd_color` means that this value won't have priority over block * auto-detection as far as determining which color shows initially * in the preferences dialog (though it can be changed and saved). */ // bkgd_color: '#FFF', // bkgd_url: '', // img_save: 'embed', // Only shows in UI as far as alert notices // save_notice_done: false, // export_notice_done: false }); editor.setConfig({// Indicate pref settings here if you wish to allow user storage or URL // settings to be able to override your default preferences (unless // other config options have already explicitly prevented one or the // other) }, { allowInitialUserOverride: true }); var html2canvas = createCommonjsModule(function (module, exports) { /*! * html2canvas 1.0.0-rc.7 * Copyright (c) 2020 Niklas von Hertzen * Released under MIT License */ (function (global, factory) { module.exports = factory() ; })(commonjsGlobal, function () { /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var _extendStatics = function extendStatics(d, b) { _extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) d[p] = b[p]; } }; return _extendStatics(d, b); }; function __extends(d, b) { _extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var _assign = function __assign() { _assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } } return t; }; return _assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function sent() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) { try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var Bounds = /** @class */ function () { function Bounds(x, y, w, h) { this.left = x; this.top = y; this.width = w; this.height = h; } Bounds.prototype.add = function (x, y, w, h) { return new Bounds(this.left + x, this.top + y, this.width + w, this.height + h); }; Bounds.fromClientRect = function (clientRect) { return new Bounds(clientRect.left, clientRect.top, clientRect.width, clientRect.height); }; return Bounds; }(); var parseBounds = function parseBounds(node) { return Bounds.fromClientRect(node.getBoundingClientRect()); }; var parseDocumentSize = function parseDocumentSize(document) { var body = document.body; var documentElement = document.documentElement; if (!body || !documentElement) { throw new Error("Unable to get document size"); } var width = Math.max(Math.max(body.scrollWidth, documentElement.scrollWidth), Math.max(body.offsetWidth, documentElement.offsetWidth), Math.max(body.clientWidth, documentElement.clientWidth)); var height = Math.max(Math.max(body.scrollHeight, documentElement.scrollHeight), Math.max(body.offsetHeight, documentElement.offsetHeight), Math.max(body.clientHeight, documentElement.clientHeight)); return new Bounds(0, 0, width, height); }; /* * css-line-break 1.1.1 * Copyright (c) 2019 Niklas von Hertzen * Released under MIT License */ var toCodePoints = function toCodePoints(str) { var codePoints = []; var i = 0; var length = str.length; while (i < length) { var value = str.charCodeAt(i++); if (value >= 0xd800 && value <= 0xdbff && i < length) { var extra = str.charCodeAt(i++); if ((extra & 0xfc00) === 0xdc00) { codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000); } else { codePoints.push(value); i--; } } else { codePoints.push(value); } } return codePoints; }; var fromCodePoint = function fromCodePoint() { var codePoints = []; for (var _i = 0; _i < arguments.length; _i++) { codePoints[_i] = arguments[_i]; } if (String.fromCodePoint) { return String.fromCodePoint.apply(String, codePoints); } var length = codePoints.length; if (!length) { return ''; } var codeUnits = []; var index = -1; var result = ''; while (++index < length) { var codePoint = codePoints[index]; if (codePoint <= 0xffff) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; codeUnits.push((codePoint >> 10) + 0xd800, codePoint % 0x400 + 0xdc00); } if (index + 1 === length || codeUnits.length > 0x4000) { result += String.fromCharCode.apply(String, codeUnits); codeUnits.length = 0; } } return result; }; var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index. var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } var decode = function decode(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === '=') { bufferLength--; if (base64[base64.length - 2] === '=') { bufferLength--; } } var buffer = typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint8Array.prototype.slice !== 'undefined' ? new ArrayBuffer(bufferLength) : new Array(bufferLength); var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = lookup[base64.charCodeAt(i)]; encoded2 = lookup[base64.charCodeAt(i + 1)]; encoded3 = lookup[base64.charCodeAt(i + 2)]; encoded4 = lookup[base64.charCodeAt(i + 3)]; bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; }; var polyUint16Array = function polyUint16Array(buffer) { var length = buffer.length; var bytes = []; for (var i = 0; i < length; i += 2) { bytes.push(buffer[i + 1] << 8 | buffer[i]); } return bytes; }; var polyUint32Array = function polyUint32Array(buffer) { var length = buffer.length; var bytes = []; for (var i = 0; i < length; i += 4) { bytes.push(buffer[i + 3] << 24 | buffer[i + 2] << 16 | buffer[i + 1] << 8 | buffer[i]); } return bytes; }; /** Shift size for getting the index-2 table offset. */ var UTRIE2_SHIFT_2 = 5; /** Shift size for getting the index-1 table offset. */ var UTRIE2_SHIFT_1 = 6 + 5; /** * Shift size for shifting left the index array values. * Increases possible data size with 16-bit index values at the cost * of compactability. * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY. */ var UTRIE2_INDEX_SHIFT = 2; /** * Difference between the two shift sizes, * for getting an index-1 offset from an index-2 offset. 6=11-5 */ var UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2; /** * The part of the index-2 table for U+D800..U+DBFF stores values for * lead surrogate code _units_ not code _points_. * Values for lead surrogate code _points_ are indexed with this portion of the table. * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.) */ var UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2; /** Number of entries in a data block. 32=0x20 */ var UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2; /** Mask for getting the lower bits for the in-data-block offset. */ var UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1; var UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2; /** Count the lengths of both BMP pieces. 2080=0x820 */ var UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH; /** * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820. * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2. */ var UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH; var UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */ /** * The index-1 table, only used for supplementary code points, at offset 2112=0x840. * Variable length, for code points up to highStart, where the last single-value range starts. * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1. * (For 0x100000 supplementary code points U+10000..U+10ffff.) * * The part of the index-2 table for supplementary code points starts * after this index-1 table. * * Both the index-1 table and the following part of the index-2 table * are omitted completely if there is only BMP data. */ var UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH; /** * Number of index-1 entries for the BMP. 32=0x20 * This part of the index-1 table is omitted from the serialized form. */ var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1; /** Number of entries in an index-2 block. 64=0x40 */ var UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2; /** Mask for getting the lower bits for the in-index-2-block offset. */ var UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1; var slice16 = function slice16(view, start, end) { if (view.slice) { return view.slice(start, end); } return new Uint16Array(Array.prototype.slice.call(view, start, end)); }; var slice32 = function slice32(view, start, end) { if (view.slice) { return view.slice(start, end); } return new Uint32Array(Array.prototype.slice.call(view, start, end)); }; var createTrieFromBase64 = function createTrieFromBase64(base64) { var buffer = decode(base64); var view32 = Array.isArray(buffer) ? polyUint32Array(buffer) : new Uint32Array(buffer); var view16 = Array.isArray(buffer) ? polyUint16Array(buffer) : new Uint16Array(buffer); var headerLength = 24; var index = slice16(view16, headerLength / 2, view32[4] / 2); var data = view32[5] === 2 ? slice16(view16, (headerLength + view32[4]) / 2) : slice32(view32, Math.ceil((headerLength + view32[4]) / 4)); return new Trie(view32[0], view32[1], view32[2], view32[3], index, data); }; var Trie = /** @class */ function () { function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) { this.initialValue = initialValue; this.errorValue = errorValue; this.highStart = highStart; this.highValueIndex = highValueIndex; this.index = index; this.data = data; } /** * Get the value for a code point as stored in the Trie. * * @param codePoint the code point * @return the value */ Trie.prototype.get = function (codePoint) { var ix; if (codePoint >= 0) { if (codePoint < 0x0d800 || codePoint > 0x0dbff && codePoint <= 0x0ffff) { // Ordinary BMP code point, excluding leading surrogates. // BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index. // 16 bit data is stored in the index array itself. ix = this.index[codePoint >> UTRIE2_SHIFT_2]; ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); return this.data[ix]; } if (codePoint <= 0xffff) { // Lead Surrogate Code Point. A Separate index section is stored for // lead surrogate code units and code points. // The main index has the code unit data. // For this function, we need the code point data. // Note: this expression could be refactored for slightly improved efficiency, but // surrogate code points will be so rare in practice that it's not worth it. ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + (codePoint - 0xd800 >> UTRIE2_SHIFT_2)]; ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); return this.data[ix]; } if (codePoint < this.highStart) { // Supplemental code point, use two-level lookup. ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1); ix = this.index[ix]; ix += codePoint >> UTRIE2_SHIFT_2 & UTRIE2_INDEX_2_MASK; ix = this.index[ix]; ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); return this.data[ix]; } if (codePoint <= 0x10ffff) { return this.data[this.highValueIndex]; } } // Fall through. The code point is outside of the legal range of 0..0x10ffff. return this.errorValue; }; return Trie; }(); var base64 = 'KwAAAAAAAAAACA4AIDoAAPAfAAACAAAAAAAIABAAGABAAEgAUABYAF4AZgBeAGYAYABoAHAAeABeAGYAfACEAIAAiACQAJgAoACoAK0AtQC9AMUAXgBmAF4AZgBeAGYAzQDVAF4AZgDRANkA3gDmAOwA9AD8AAQBDAEUARoBIgGAAIgAJwEvATcBPwFFAU0BTAFUAVwBZAFsAXMBewGDATAAiwGTAZsBogGkAawBtAG8AcIBygHSAdoB4AHoAfAB+AH+AQYCDgIWAv4BHgImAi4CNgI+AkUCTQJTAlsCYwJrAnECeQKBAk0CiQKRApkCoQKoArACuALAAsQCzAIwANQC3ALkAjAA7AL0AvwCAQMJAxADGAMwACADJgMuAzYDPgOAAEYDSgNSA1IDUgNaA1oDYANiA2IDgACAAGoDgAByA3YDfgOAAIQDgACKA5IDmgOAAIAAogOqA4AAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAK8DtwOAAIAAvwPHA88D1wPfAyAD5wPsA/QD/AOAAIAABAQMBBIEgAAWBB4EJgQuBDMEIAM7BEEEXgBJBCADUQRZBGEEaQQwADAAcQQ+AXkEgQSJBJEEgACYBIAAoASoBK8EtwQwAL8ExQSAAIAAgACAAIAAgACgAM0EXgBeAF4AXgBeAF4AXgBeANUEXgDZBOEEXgDpBPEE+QQBBQkFEQUZBSEFKQUxBTUFPQVFBUwFVAVcBV4AYwVeAGsFcwV7BYMFiwWSBV4AmgWgBacFXgBeAF4AXgBeAKsFXgCyBbEFugW7BcIFwgXIBcIFwgXQBdQF3AXkBesF8wX7BQMGCwYTBhsGIwYrBjMGOwZeAD8GRwZNBl4AVAZbBl4AXgBeAF4AXgBeAF4AXgBeAF4AXgBeAGMGXgBqBnEGXgBeAF4AXgBeAF4AXgBeAF4AXgB5BoAG4wSGBo4GkwaAAIADHgR5AF4AXgBeAJsGgABGA4AAowarBrMGswagALsGwwbLBjAA0wbaBtoG3QbaBtoG2gbaBtoG2gblBusG8wb7BgMHCwcTBxsHCwcjBysHMAc1BzUHOgdCB9oGSgdSB1oHYAfaBloHaAfaBlIH2gbaBtoG2gbaBtoG2gbaBjUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHbQdeAF4ANQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQd1B30HNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B4MH2gaKB68EgACAAIAAgACAAIAAgACAAI8HlwdeAJ8HpweAAIAArwe3B14AXgC/B8UHygcwANAH2AfgB4AA6AfwBz4B+AcACFwBCAgPCBcIogEYAR8IJwiAAC8INwg/CCADRwhPCFcIXwhnCEoDGgSAAIAAgABvCHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIhAiLCI4IMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAANQc1BzUHNQc1BzUHNQc1BzUHNQc1B54INQc1B6II2gaqCLIIugiAAIAAvgjGCIAAgACAAIAAgACAAIAAgACAAIAAywiHAYAA0wiAANkI3QjlCO0I9Aj8CIAAgACAAAIJCgkSCRoJIgknCTYHLwk3CZYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiAAIAAAAFAAXgBeAGAAcABeAHwAQACQAKAArQC9AJ4AXgBeAE0A3gBRAN4A7AD8AMwBGgEAAKcBNwEFAUwBXAF4QkhCmEKnArcCgAHHAsABz4LAAcABwAHAAd+C6ABoAG+C/4LAAcABwAHAAc+DF4MAAcAB54M3gweDV4Nng3eDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEeDqABVg6WDqABoQ6gAaABoAHXDvcONw/3DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DncPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB7cPPwlGCU4JMACAAIAAgABWCV4JYQmAAGkJcAl4CXwJgAkwADAAMAAwAIgJgACLCZMJgACZCZ8JowmrCYAAswkwAF4AXgB8AIAAuwkABMMJyQmAAM4JgADVCTAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAqwYWBNkIMAAwADAAMADdCeAJ6AnuCR4E9gkwAP4JBQoNCjAAMACAABUK0wiAAB0KJAosCjQKgAAwADwKQwqAAEsKvQmdCVMKWwowADAAgACAALcEMACAAGMKgABrCjAAMAAwADAAMAAwADAAMAAwADAAMAAeBDAAMAAwADAAMAAwADAAMAAwADAAMAAwAIkEPQFzCnoKiQSCCooKkAqJBJgKoAqkCokEGAGsCrQKvArBCjAAMADJCtEKFQHZCuEK/gHpCvEKMAAwADAAMACAAIwE+QowAIAAPwEBCzAAMAAwADAAMACAAAkLEQswAIAAPwEZCyELgAAOCCkLMAAxCzkLMAAwADAAMAAwADAAXgBeAEELMAAwADAAMAAwADAAMAAwAEkLTQtVC4AAXAtkC4AAiQkwADAAMAAwADAAMAAwADAAbAtxC3kLgAuFC4sLMAAwAJMLlwufCzAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAApwswADAAMACAAIAAgACvC4AAgACAAIAAgACAALcLMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAvwuAAMcLgACAAIAAgACAAIAAyguAAIAAgACAAIAA0QswADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAANkLgACAAIAA4AswADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACJCR4E6AswADAAhwHwC4AA+AsADAgMEAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMACAAIAAGAwdDCUMMAAwAC0MNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQw1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHPQwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADUHNQc1BzUHNQc1BzUHNQc2BzAAMAA5DDUHNQc1BzUHNQc1BzUHNQc1BzUHNQdFDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAATQxSDFoMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAF4AXgBeAF4AXgBeAF4AYgxeAGoMXgBxDHkMfwxeAIUMXgBeAI0MMAAwADAAMAAwAF4AXgCVDJ0MMAAwADAAMABeAF4ApQxeAKsMswy7DF4Awgy9DMoMXgBeAF4AXgBeAF4AXgBeAF4AXgDRDNkMeQBqCeAM3Ax8AOYM7Az0DPgMXgBeAF4AXgBeAF4AXgBeAF4AXgBeAF4AXgBeAF4AXgCgAAANoAAHDQ4NFg0wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAeDSYNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAC4NMABeAF4ANg0wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAD4NRg1ODVYNXg1mDTAAbQ0wADAAMAAwADAAMAAwADAA2gbaBtoG2gbaBtoG2gbaBnUNeg3CBYANwgWFDdoGjA3aBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gaUDZwNpA2oDdoG2gawDbcNvw3HDdoG2gbPDdYN3A3fDeYN2gbsDfMN2gbaBvoN/g3aBgYODg7aBl4AXgBeABYOXgBeACUG2gYeDl4AJA5eACwO2w3aBtoGMQ45DtoG2gbaBtoGQQ7aBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gZJDjUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B1EO2gY1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQdZDjUHNQc1BzUHNQc1B2EONQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHaA41BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B3AO2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gY1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B2EO2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gZJDtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBkkOeA6gAKAAoAAwADAAMAAwAKAAoACgAKAAoACgAKAAgA4wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAD//wQABAAEAAQABAAEAAQABAAEAA0AAwABAAEAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAKABMAFwAeABsAGgAeABcAFgASAB4AGwAYAA8AGAAcAEsASwBLAEsASwBLAEsASwBLAEsAGAAYAB4AHgAeABMAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAFgAbABIAHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYADQARAB4ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkAFgAaABsAGwAbAB4AHQAdAB4ATwAXAB4ADQAeAB4AGgAbAE8ATwAOAFAAHQAdAB0ATwBPABcATwBPAE8AFgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwArAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAAQABAANAA0ASwBLAEsASwBLAEsASwBLAEsASwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUAArACsABABQAAQABAAEAAQABAAEAAQAKwArAAQABAArACsABAAEAAQAUAArACsAKwArACsAKwArACsABAArACsAKwArAFAAUAArAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAGgAaAFAAUABQAFAAUABMAB4AGwBQAB4AKwArACsABAAEAAQAKwBQAFAAUABQAFAAUAArACsAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUAArAFAAUAArACsABAArAAQABAAEAAQABAArACsAKwArAAQABAArACsABAAEAAQAKwArACsABAArACsAKwArACsAKwArAFAAUABQAFAAKwBQACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwAEAAQAUABQAFAABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUAArACsABABQAAQABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQAKwArAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwAeABsAKwArACsAKwArACsAKwBQAAQABAAEAAQABAAEACsABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwArAAQABAArACsABAAEAAQAKwArACsAKwArACsAKwArAAQABAArACsAKwArAFAAUAArAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwAeAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwAEAFAAKwBQAFAAUABQAFAAUAArACsAKwBQAFAAUAArAFAAUABQAFAAKwArACsAUABQACsAUAArAFAAUAArACsAKwBQAFAAKwArACsAUABQAFAAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQAKwArACsABAAEAAQAKwAEAAQABAAEACsAKwBQACsAKwArACsAKwArAAQAKwArACsAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAB4AHgAeAB4AHgAeABsAHgArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABAArACsAKwArACsAKwArAAQABAArAFAAUABQACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAB4AUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABAArACsAKwArACsAKwArAAQABAArACsAKwArACsAKwArAFAAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwArAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAKwBcAFwAKwBcACsAKwBcACsAKwArACsAKwArAFwAXABcAFwAKwBcAFwAXABcAFwAXABcACsAXABcAFwAKwBcACsAXAArACsAXABcACsAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgArACoAKgBcACsAKwBcAFwAXABcAFwAKwBcACsAKgAqACoAKgAqACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAFwAXABcAFwAUAAOAA4ADgAOAB4ADgAOAAkADgAOAA0ACQATABMAEwATABMACQAeABMAHgAeAB4ABAAEAB4AHgAeAB4AHgAeAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUAANAAQAHgAEAB4ABAAWABEAFgARAAQABABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAAQABAAEAAQABAANAAQABABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsADQANAB4AHgAeAB4AHgAeAAQAHgAeAB4AHgAeAB4AKwAeAB4ADgAOAA0ADgAeAB4AHgAeAB4ACQAJACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgAeAB4AHgBcAFwAXABcAFwAXAAqACoAKgAqAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAKgAqACoAKgAqACoAKgBcAFwAXAAqACoAKgAqAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAXAAqAEsASwBLAEsASwBLAEsASwBLAEsAKgAqACoAKgAqACoAUABQAFAAUABQAFAAKwBQACsAKwArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQACsAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwAEAAQABAAeAA0AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAEQArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAADQANAA0AUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAA0ADQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoADQANABUAXAANAB4ADQAbAFwAKgArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAB4AHgATABMADQANAA4AHgATABMAHgAEAAQABAAJACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAUABQAFAAUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwAeACsAKwArABMAEwBLAEsASwBLAEsASwBLAEsASwBLAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwBcAFwAXABcAFwAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcACsAKwArACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwAeAB4AXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgArACsABABLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKgAqACoAKgAqACoAKgBcACoAKgAqACoAKgAqACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAUABQAFAAUABQAFAAUAArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4ADQANAA0ADQAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAHgAeAB4AHgBQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwANAA0ADQANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwBQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsABAAEAAQAHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAABABQAFAAUABQAAQABAAEAFAAUAAEAAQABAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAKwBQACsAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAKwArAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAKwAeAB4AHgAeAB4AHgAeAA4AHgArAA0ADQANAA0ADQANAA0ACQANAA0ADQAIAAQACwAEAAQADQAJAA0ADQAMAB0AHQAeABcAFwAWABcAFwAXABYAFwAdAB0AHgAeABQAFAAUAA0AAQABAAQABAAEAAQABAAJABoAGgAaABoAGgAaABoAGgAeABcAFwAdABUAFQAeAB4AHgAeAB4AHgAYABYAEQAVABUAFQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgANAB4ADQANAA0ADQAeAA0ADQANAAcAHgAeAB4AHgArAAQABAAEAAQABAAEAAQABAAEAAQAUABQACsAKwBPAFAAUABQAFAAUAAeAB4AHgAWABEATwBQAE8ATwBPAE8AUABQAFAAUABQAB4AHgAeABYAEQArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAGwAbABsAGwAbABsAGwAaABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAaABsAGwAbABsAGgAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgBQABoAHgAdAB4AUAAeABoAHgAeAB4AHgAeAB4AHgAeAB4ATwAeAFAAGwAeAB4AUABQAFAAUABQAB4AHgAeAB0AHQAeAFAAHgBQAB4AUAAeAFAATwBQAFAAHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AUABQAFAAUABPAE8AUABQAFAAUABQAE8AUABQAE8AUABPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAE8ATwBPAE8ATwBPAE8ATwBPAE8AUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAATwAeAB4AKwArACsAKwAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB0AHQAeAB4AHgAdAB0AHgAeAB0AHgAeAB4AHQAeAB0AGwAbAB4AHQAeAB4AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB0AHgAdAB4AHQAdAB0AHQAdAB0AHgAdAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAdAB0AHQAdAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAlACUAHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBQAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB0AHQAeAB4AHgAeAB0AHQAdAB4AHgAdAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB0AHQAeAB4AHQAeAB4AHgAeAB0AHQAeAB4AHgAeACUAJQAdAB0AJQAeACUAJQAlACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAHgAeAB4AHgAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHQAdAB0AHgAdACUAHQAdAB4AHQAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHQAdAB0AHQAlAB4AJQAlACUAHQAlACUAHQAdAB0AJQAlAB0AHQAlAB0AHQAlACUAJQAeAB0AHgAeAB4AHgAdAB0AJQAdAB0AHQAdAB0AHQAlACUAJQAlACUAHQAlACUAIAAlAB0AHQAlACUAJQAlACUAJQAlACUAHgAeAB4AJQAlACAAIAAgACAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeABcAFwAXABcAFwAXAB4AEwATACUAHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwArACUAJQBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAKwArACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAE8ATwBPAE8ATwBPAE8ATwAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeACsAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUAArACsAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQBQAFAAUABQACsAKwArACsAUABQAFAAUABQAFAAUABQAA0AUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQACsAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgBQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAABAAEAAQAKwAEAAQAKwArACsAKwArAAQABAAEAAQAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsABAAEAAQAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsADQANAA0ADQANAA0ADQANAB4AKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AUABQAFAAUABQAFAAUABQAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAUABQAFAAUABQAA0ADQANAA0ADQANABQAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwANAA0ADQANAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAeAAQABAAEAB4AKwArAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLACsADQArAB4AKwArAAQABAAEAAQAUABQAB4AUAArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwAEAAQABAAEAAQABAAEAAQABAAOAA0ADQATABMAHgAeAB4ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0AUABQAFAAUAAEAAQAKwArAAQADQANAB4AUAArACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXABcAA0ADQANACoASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUAArACsAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANACsADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEcARwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQACsAKwAeAAQABAANAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAEAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUAArACsAUAArACsAUABQACsAKwBQAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AKwArAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAeAB4ADQANAA0ADQAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAArAAQABAArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAEAAQABAAEAAQABAAEACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAFgAWAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAKwBQACsAKwArACsAKwArAFAAKwArACsAKwBQACsAUAArAFAAKwBQAFAAUAArAFAAUAArAFAAKwArAFAAKwBQACsAUAArAFAAKwBQACsAUABQACsAUAArACsAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAUABQAFAAUAArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUAArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAlACUAJQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeACUAJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeACUAJQAlACUAJQAeACUAJQAlACUAJQAgACAAIAAlACUAIAAlACUAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIQAhACEAIQAhACUAJQAgACAAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACAAIAAlACUAJQAlACAAJQAgACAAIAAgACAAIAAgACAAIAAlACUAJQAgACUAJQAlACUAIAAgACAAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeACUAHgAlAB4AJQAlACUAJQAlACAAJQAlACUAJQAeACUAHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAIAAgACAAJQAlACUAIAAgACAAIAAgAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFwAXABcAFQAVABUAHgAeAB4AHgAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACAAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAlACAAIAAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsA'; /* @flow */ var LETTER_NUMBER_MODIFIER = 50; // Non-tailorable Line Breaking Classes var BK = 1; // Cause a line break (after) var CR = 2; // Cause a line break (after), except between CR and LF var LF = 3; // Cause a line break (after) var CM = 4; // Prohibit a line break between the character and the preceding character var NL = 5; // Cause a line break (after) var WJ = 7; // Prohibit line breaks before and after var ZW = 8; // Provide a break opportunity var GL = 9; // Prohibit line breaks before and after var SP = 10; // Enable indirect line breaks var ZWJ = 11; // Prohibit line breaks within joiner sequences // Break Opportunities var B2 = 12; // Provide a line break opportunity before and after the character var BA = 13; // Generally provide a line break opportunity after the character var BB = 14; // Generally provide a line break opportunity before the character var HY = 15; // Provide a line break opportunity after the character, except in numeric context var CB = 16; // Provide a line break opportunity contingent on additional information // Characters Prohibiting Certain Breaks var CL = 17; // Prohibit line breaks before var CP = 18; // Prohibit line breaks before var EX = 19; // Prohibit line breaks before var IN = 20; // Allow only indirect line breaks between pairs var NS = 21; // Allow only indirect line breaks before var OP = 22; // Prohibit line breaks after var QU = 23; // Act like they are both opening and closing // Numeric Context var IS = 24; // Prevent breaks after any and before numeric var NU = 25; // Form numeric expressions for line breaking purposes var PO = 26; // Do not break following a numeric expression var PR = 27; // Do not break in front of a numeric expression var SY = 28; // Prevent a break before; and allow a break after // Other Characters var AI = 29; // Act like AL when the resolvedEAW is N; otherwise; act as ID var AL = 30; // Are alphabetic characters or symbols that are used with alphabetic characters var CJ = 31; // Treat as NS or ID for strict or normal breaking. var EB = 32; // Do not break from following Emoji Modifier var EM = 33; // Do not break from preceding Emoji Base var H2 = 34; // Form Korean syllable blocks var H3 = 35; // Form Korean syllable blocks var HL = 36; // Do not break around a following hyphen; otherwise act as Alphabetic var ID = 37; // Break before or after; except in some numeric context var JL = 38; // Form Korean syllable blocks var JV = 39; // Form Korean syllable blocks var JT = 40; // Form Korean syllable blocks var RI = 41; // Keep pairs together. For pairs; break before and after other classes var SA = 42; // Provide a line break opportunity contingent on additional, language-specific context analysis var XX = 43; // Have as yet unknown line breaking behavior or unassigned code positions var BREAK_MANDATORY = '!'; var BREAK_NOT_ALLOWED = '×'; var BREAK_ALLOWED = '÷'; var UnicodeTrie = createTrieFromBase64(base64); var ALPHABETICS = [AL, HL]; var HARD_LINE_BREAKS = [BK, CR, LF, NL]; var SPACE = [SP, ZW]; var PREFIX_POSTFIX = [PR, PO]; var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE); var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3]; var HYPHEN = [HY, BA]; var codePointsToCharacterClasses = function codePointsToCharacterClasses(codePoints, lineBreak) { if (lineBreak === void 0) { lineBreak = 'strict'; } var types = []; var indicies = []; var categories = []; codePoints.forEach(function (codePoint, index) { var classType = UnicodeTrie.get(codePoint); if (classType > LETTER_NUMBER_MODIFIER) { categories.push(true); classType -= LETTER_NUMBER_MODIFIER; } else { categories.push(false); } if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) { // U+2010, – U+2013, 〜 U+301C, ゠ U+30A0 if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) { indicies.push(index); return types.push(CB); } } if (classType === CM || classType === ZWJ) { // LB10 Treat any remaining combining mark or ZWJ as AL. if (index === 0) { indicies.push(index); return types.push(AL); } // LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of // the base character in all of the following rules. Treat ZWJ as if it were CM. var prev = types[index - 1]; if (LINE_BREAKS.indexOf(prev) === -1) { indicies.push(indicies[index - 1]); return types.push(prev); } indicies.push(index); return types.push(AL); } indicies.push(index); if (classType === CJ) { return types.push(lineBreak === 'strict' ? NS : ID); } if (classType === SA) { return types.push(AL); } if (classType === AI) { return types.push(AL); } // For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL // and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised // to take into account the actual line breaking properties for these characters. if (classType === XX) { if (codePoint >= 0x20000 && codePoint <= 0x2fffd || codePoint >= 0x30000 && codePoint <= 0x3fffd) { return types.push(ID); } else { return types.push(AL); } } types.push(classType); }); return [indicies, types, categories]; }; var isAdjacentWithSpaceIgnored = function isAdjacentWithSpaceIgnored(a, b, currentIndex, classTypes) { var current = classTypes[currentIndex]; if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) { var i = currentIndex; while (i <= classTypes.length) { i++; var next = classTypes[i]; if (next === b) { return true; } if (next !== SP) { break; } } } if (current === SP) { var i = currentIndex; while (i > 0) { i--; var prev = classTypes[i]; if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) { var n = currentIndex; while (n <= classTypes.length) { n++; var next = classTypes[n]; if (next === b) { return true; } if (next !== SP) { break; } } } if (prev !== SP) { break; } } } return false; }; var previousNonSpaceClassType = function previousNonSpaceClassType(currentIndex, classTypes) { var i = currentIndex; while (i >= 0) { var type = classTypes[i]; if (type === SP) { i--; } else { return type; } } return 0; }; var _lineBreakAtIndex = function _lineBreakAtIndex(codePoints, classTypes, indicies, index, forbiddenBreaks) { if (indicies[index] === 0) { return BREAK_NOT_ALLOWED; } var currentIndex = index - 1; if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) { return BREAK_NOT_ALLOWED; } var beforeIndex = currentIndex - 1; var afterIndex = currentIndex + 1; var current = classTypes[currentIndex]; // LB4 Always break after hard line breaks. // LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks. var before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0; var next = classTypes[afterIndex]; if (current === CR && next === LF) { return BREAK_NOT_ALLOWED; } if (HARD_LINE_BREAKS.indexOf(current) !== -1) { return BREAK_MANDATORY; } // LB6 Do not break before hard line breaks. if (HARD_LINE_BREAKS.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB7 Do not break before spaces or zero width space. if (SPACE.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB8 Break before any character following a zero-width space, even if one or more spaces intervene. if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) { return BREAK_ALLOWED; } // LB8a Do not break between a zero width joiner and an ideograph, emoji base or emoji modifier. if (UnicodeTrie.get(codePoints[currentIndex]) === ZWJ && (next === ID || next === EB || next === EM)) { return BREAK_NOT_ALLOWED; } // LB11 Do not break before or after Word joiner and related characters. if (current === WJ || next === WJ) { return BREAK_NOT_ALLOWED; } // LB12 Do not break after NBSP and related characters. if (current === GL) { return BREAK_NOT_ALLOWED; } // LB12a Do not break before NBSP and related characters, except after spaces and hyphens. if ([SP, BA, HY].indexOf(current) === -1 && next === GL) { return BREAK_NOT_ALLOWED; } // LB13 Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces. if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB14 Do not break after ‘[’, even after spaces. if (previousNonSpaceClassType(currentIndex, classTypes) === OP) { return BREAK_NOT_ALLOWED; } // LB15 Do not break within ‘”[’, even with intervening spaces. if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) { return BREAK_NOT_ALLOWED; } // LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces. if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) { return BREAK_NOT_ALLOWED; } // LB17 Do not break within ‘——’, even with intervening spaces. if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) { return BREAK_NOT_ALLOWED; } // LB18 Break after spaces. if (current === SP) { return BREAK_ALLOWED; } // LB19 Do not break before or after quotation marks, such as ‘ ” ’. if (current === QU || next === QU) { return BREAK_NOT_ALLOWED; } // LB20 Break before and after unresolved CB. if (next === CB || current === CB) { return BREAK_ALLOWED; } // LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents. if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) { return BREAK_NOT_ALLOWED; } // LB21a Don't break after Hebrew + Hyphen. if (before === HL && HYPHEN.indexOf(current) !== -1) { return BREAK_NOT_ALLOWED; } // LB21b Don’t break between Solidus and Hebrew letters. if (current === SY && next === HL) { return BREAK_NOT_ALLOWED; } // LB22 Do not break between two ellipses, or between letters, numbers or exclamations and ellipsis. if (next === IN && ALPHABETICS.concat(IN, EX, NU, ID, EB, EM).indexOf(current) !== -1) { return BREAK_NOT_ALLOWED; } // LB23 Do not break between digits and letters. if (ALPHABETICS.indexOf(next) !== -1 && current === NU || ALPHABETICS.indexOf(current) !== -1 && next === NU) { return BREAK_NOT_ALLOWED; } // LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes. if (current === PR && [ID, EB, EM].indexOf(next) !== -1 || [ID, EB, EM].indexOf(current) !== -1 && next === PO) { return BREAK_NOT_ALLOWED; } // LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix. if (ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1 || PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB25 Do not break between the following pairs of classes relevant to numbers: if ( // (PR | PO) × ( OP | HY )? NU [PR, PO].indexOf(current) !== -1 && (next === NU || [OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU) || // ( OP | HY ) × NU [OP, HY].indexOf(current) !== -1 && next === NU || // NU × (NU | SY | IS) current === NU && [NU, SY, IS].indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP) if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) { var prevIndex = currentIndex; while (prevIndex >= 0) { var type = classTypes[prevIndex]; if (type === NU) { return BREAK_NOT_ALLOWED; } else if ([SY, IS].indexOf(type) !== -1) { prevIndex--; } else { break; } } } // NU (NU | SY | IS)* (CL | CP)? × (PO | PR)) if ([PR, PO].indexOf(next) !== -1) { var prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex; while (prevIndex >= 0) { var type = classTypes[prevIndex]; if (type === NU) { return BREAK_NOT_ALLOWED; } else if ([SY, IS].indexOf(type) !== -1) { prevIndex--; } else { break; } } } // LB26 Do not break a Korean syllable. if (JL === current && [JL, JV, H2, H3].indexOf(next) !== -1 || [JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1 || [JT, H3].indexOf(current) !== -1 && next === JT) { return BREAK_NOT_ALLOWED; } // LB27 Treat a Korean Syllable Block the same as ID. if (KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1 || KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR) { return BREAK_NOT_ALLOWED; } // LB28 Do not break between alphabetics (“at”). if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB29 Do not break between numeric punctuation and alphabetics (“e.g.”). if (current === IS && ALPHABETICS.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses. if (ALPHABETICS.concat(NU).indexOf(current) !== -1 && next === OP || ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP) { return BREAK_NOT_ALLOWED; } // LB30a Break between two regional indicator symbols if and only if there are an even number of regional // indicators preceding the position of the break. if (current === RI && next === RI) { var i = indicies[currentIndex]; var count = 1; while (i > 0) { i--; if (classTypes[i] === RI) { count++; } else { break; } } if (count % 2 !== 0) { return BREAK_NOT_ALLOWED; } } // LB30b Do not break between an emoji base and an emoji modifier. if (current === EB && next === EM) { return BREAK_NOT_ALLOWED; } return BREAK_ALLOWED; }; var cssFormattedClasses = function cssFormattedClasses(codePoints, options) { if (!options) { options = { lineBreak: 'normal', wordBreak: 'normal' }; } var _a = codePointsToCharacterClasses(codePoints, options.lineBreak), indicies = _a[0], classTypes = _a[1], isLetterNumber = _a[2]; if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') { classTypes = classTypes.map(function (type) { return [NU, AL, SA].indexOf(type) !== -1 ? ID : type; }); } var forbiddenBreakpoints = options.wordBreak === 'keep-all' ? isLetterNumber.map(function (letterNumber, i) { return letterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff; }) : undefined; return [indicies, classTypes, forbiddenBreakpoints]; }; var Break = /** @class */ function () { function Break(codePoints, lineBreak, start, end) { this.codePoints = codePoints; this.required = lineBreak === BREAK_MANDATORY; this.start = start; this.end = end; } Break.prototype.slice = function () { return fromCodePoint.apply(void 0, this.codePoints.slice(this.start, this.end)); }; return Break; }(); var LineBreaker = function LineBreaker(str, options) { var codePoints = toCodePoints(str); var _a = cssFormattedClasses(codePoints, options), indicies = _a[0], classTypes = _a[1], forbiddenBreakpoints = _a[2]; var length = codePoints.length; var lastEnd = 0; var nextIndex = 0; return { next: function next() { if (nextIndex >= length) { return { done: true, value: null }; } var lineBreak = BREAK_NOT_ALLOWED; while (nextIndex < length && (lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) === BREAK_NOT_ALLOWED) {} if (lineBreak !== BREAK_NOT_ALLOWED || nextIndex === length) { var value = new Break(codePoints, lineBreak, lastEnd, nextIndex); lastEnd = nextIndex; return { value: value, done: false }; } return { done: true, value: null }; } }; }; // https://www.w3.org/TR/css-syntax-3 var TokenType; (function (TokenType) { TokenType[TokenType["STRING_TOKEN"] = 0] = "STRING_TOKEN"; TokenType[TokenType["BAD_STRING_TOKEN"] = 1] = "BAD_STRING_TOKEN"; TokenType[TokenType["LEFT_PARENTHESIS_TOKEN"] = 2] = "LEFT_PARENTHESIS_TOKEN"; TokenType[TokenType["RIGHT_PARENTHESIS_TOKEN"] = 3] = "RIGHT_PARENTHESIS_TOKEN"; TokenType[TokenType["COMMA_TOKEN"] = 4] = "COMMA_TOKEN"; TokenType[TokenType["HASH_TOKEN"] = 5] = "HASH_TOKEN"; TokenType[TokenType["DELIM_TOKEN"] = 6] = "DELIM_TOKEN"; TokenType[TokenType["AT_KEYWORD_TOKEN"] = 7] = "AT_KEYWORD_TOKEN"; TokenType[TokenType["PREFIX_MATCH_TOKEN"] = 8] = "PREFIX_MATCH_TOKEN"; TokenType[TokenType["DASH_MATCH_TOKEN"] = 9] = "DASH_MATCH_TOKEN"; TokenType[TokenType["INCLUDE_MATCH_TOKEN"] = 10] = "INCLUDE_MATCH_TOKEN"; TokenType[TokenType["LEFT_CURLY_BRACKET_TOKEN"] = 11] = "LEFT_CURLY_BRACKET_TOKEN"; TokenType[TokenType["RIGHT_CURLY_BRACKET_TOKEN"] = 12] = "RIGHT_CURLY_BRACKET_TOKEN"; TokenType[TokenType["SUFFIX_MATCH_TOKEN"] = 13] = "SUFFIX_MATCH_TOKEN"; TokenType[TokenType["SUBSTRING_MATCH_TOKEN"] = 14] = "SUBSTRING_MATCH_TOKEN"; TokenType[TokenType["DIMENSION_TOKEN"] = 15] = "DIMENSION_TOKEN"; TokenType[TokenType["PERCENTAGE_TOKEN"] = 16] = "PERCENTAGE_TOKEN"; TokenType[TokenType["NUMBER_TOKEN"] = 17] = "NUMBER_TOKEN"; TokenType[TokenType["FUNCTION"] = 18] = "FUNCTION"; TokenType[TokenType["FUNCTION_TOKEN"] = 19] = "FUNCTION_TOKEN"; TokenType[TokenType["IDENT_TOKEN"] = 20] = "IDENT_TOKEN"; TokenType[TokenType["COLUMN_TOKEN"] = 21] = "COLUMN_TOKEN"; TokenType[TokenType["URL_TOKEN"] = 22] = "URL_TOKEN"; TokenType[TokenType["BAD_URL_TOKEN"] = 23] = "BAD_URL_TOKEN"; TokenType[TokenType["CDC_TOKEN"] = 24] = "CDC_TOKEN"; TokenType[TokenType["CDO_TOKEN"] = 25] = "CDO_TOKEN"; TokenType[TokenType["COLON_TOKEN"] = 26] = "COLON_TOKEN"; TokenType[TokenType["SEMICOLON_TOKEN"] = 27] = "SEMICOLON_TOKEN"; TokenType[TokenType["LEFT_SQUARE_BRACKET_TOKEN"] = 28] = "LEFT_SQUARE_BRACKET_TOKEN"; TokenType[TokenType["RIGHT_SQUARE_BRACKET_TOKEN"] = 29] = "RIGHT_SQUARE_BRACKET_TOKEN"; TokenType[TokenType["UNICODE_RANGE_TOKEN"] = 30] = "UNICODE_RANGE_TOKEN"; TokenType[TokenType["WHITESPACE_TOKEN"] = 31] = "WHITESPACE_TOKEN"; TokenType[TokenType["EOF_TOKEN"] = 32] = "EOF_TOKEN"; })(TokenType || (TokenType = {})); var FLAG_UNRESTRICTED = 1 << 0; var FLAG_ID = 1 << 1; var FLAG_INTEGER = 1 << 2; var FLAG_NUMBER = 1 << 3; var LINE_FEED = 0x000a; var SOLIDUS = 0x002f; var REVERSE_SOLIDUS = 0x005c; var CHARACTER_TABULATION = 0x0009; var SPACE$1 = 0x0020; var QUOTATION_MARK = 0x0022; var EQUALS_SIGN = 0x003d; var NUMBER_SIGN = 0x0023; var DOLLAR_SIGN = 0x0024; var PERCENTAGE_SIGN = 0x0025; var APOSTROPHE = 0x0027; var LEFT_PARENTHESIS = 0x0028; var RIGHT_PARENTHESIS = 0x0029; var LOW_LINE = 0x005f; var HYPHEN_MINUS = 0x002d; var EXCLAMATION_MARK = 0x0021; var LESS_THAN_SIGN = 0x003c; var GREATER_THAN_SIGN = 0x003e; var COMMERCIAL_AT = 0x0040; var LEFT_SQUARE_BRACKET = 0x005b; var RIGHT_SQUARE_BRACKET = 0x005d; var CIRCUMFLEX_ACCENT = 0x003d; var LEFT_CURLY_BRACKET = 0x007b; var QUESTION_MARK = 0x003f; var RIGHT_CURLY_BRACKET = 0x007d; var VERTICAL_LINE = 0x007c; var TILDE = 0x007e; var CONTROL = 0x0080; var REPLACEMENT_CHARACTER = 0xfffd; var ASTERISK = 0x002a; var PLUS_SIGN = 0x002b; var COMMA = 0x002c; var COLON = 0x003a; var SEMICOLON = 0x003b; var FULL_STOP = 0x002e; var NULL = 0x0000; var BACKSPACE = 0x0008; var LINE_TABULATION = 0x000b; var SHIFT_OUT = 0x000e; var INFORMATION_SEPARATOR_ONE = 0x001f; var DELETE = 0x007f; var EOF = -1; var ZERO = 0x0030; var a = 0x0061; var e = 0x0065; var f = 0x0066; var u = 0x0075; var z = 0x007a; var A = 0x0041; var E = 0x0045; var F = 0x0046; var U = 0x0055; var Z = 0x005a; var isDigit = function isDigit(codePoint) { return codePoint >= ZERO && codePoint <= 0x0039; }; var isSurrogateCodePoint = function isSurrogateCodePoint(codePoint) { return codePoint >= 0xd800 && codePoint <= 0xdfff; }; var isHex = function isHex(codePoint) { return isDigit(codePoint) || codePoint >= A && codePoint <= F || codePoint >= a && codePoint <= f; }; var isLowerCaseLetter = function isLowerCaseLetter(codePoint) { return codePoint >= a && codePoint <= z; }; var isUpperCaseLetter = function isUpperCaseLetter(codePoint) { return codePoint >= A && codePoint <= Z; }; var isLetter = function isLetter(codePoint) { return isLowerCaseLetter(codePoint) || isUpperCaseLetter(codePoint); }; var isNonASCIICodePoint = function isNonASCIICodePoint(codePoint) { return codePoint >= CONTROL; }; var isWhiteSpace = function isWhiteSpace(codePoint) { return codePoint === LINE_FEED || codePoint === CHARACTER_TABULATION || codePoint === SPACE$1; }; var isNameStartCodePoint = function isNameStartCodePoint(codePoint) { return isLetter(codePoint) || isNonASCIICodePoint(codePoint) || codePoint === LOW_LINE; }; var isNameCodePoint = function isNameCodePoint(codePoint) { return isNameStartCodePoint(codePoint) || isDigit(codePoint) || codePoint === HYPHEN_MINUS; }; var isNonPrintableCodePoint = function isNonPrintableCodePoint(codePoint) { return codePoint >= NULL && codePoint <= BACKSPACE || codePoint === LINE_TABULATION || codePoint >= SHIFT_OUT && codePoint <= INFORMATION_SEPARATOR_ONE || codePoint === DELETE; }; var isValidEscape = function isValidEscape(c1, c2) { if (c1 !== REVERSE_SOLIDUS) { return false; } return c2 !== LINE_FEED; }; var isIdentifierStart = function isIdentifierStart(c1, c2, c3) { if (c1 === HYPHEN_MINUS) { return isNameStartCodePoint(c2) || isValidEscape(c2, c3); } else if (isNameStartCodePoint(c1)) { return true; } else if (c1 === REVERSE_SOLIDUS && isValidEscape(c1, c2)) { return true; } return false; }; var isNumberStart = function isNumberStart(c1, c2, c3) { if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) { if (isDigit(c2)) { return true; } return c2 === FULL_STOP && isDigit(c3); } if (c1 === FULL_STOP) { return isDigit(c2); } return isDigit(c1); }; var stringToNumber = function stringToNumber(codePoints) { var c = 0; var sign = 1; if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) { if (codePoints[c] === HYPHEN_MINUS) { sign = -1; } c++; } var integers = []; while (isDigit(codePoints[c])) { integers.push(codePoints[c++]); } var _int = integers.length ? parseInt(fromCodePoint.apply(void 0, integers), 10) : 0; if (codePoints[c] === FULL_STOP) { c++; } var fraction = []; while (isDigit(codePoints[c])) { fraction.push(codePoints[c++]); } var fracd = fraction.length; var frac = fracd ? parseInt(fromCodePoint.apply(void 0, fraction), 10) : 0; if (codePoints[c] === E || codePoints[c] === e) { c++; } var expsign = 1; if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) { if (codePoints[c] === HYPHEN_MINUS) { expsign = -1; } c++; } var exponent = []; while (isDigit(codePoints[c])) { exponent.push(codePoints[c++]); } var exp = exponent.length ? parseInt(fromCodePoint.apply(void 0, exponent), 10) : 0; return sign * (_int + frac * Math.pow(10, -fracd)) * Math.pow(10, expsign * exp); }; var LEFT_PARENTHESIS_TOKEN = { type: TokenType.LEFT_PARENTHESIS_TOKEN }; var RIGHT_PARENTHESIS_TOKEN = { type: TokenType.RIGHT_PARENTHESIS_TOKEN }; var COMMA_TOKEN = { type: TokenType.COMMA_TOKEN }; var SUFFIX_MATCH_TOKEN = { type: TokenType.SUFFIX_MATCH_TOKEN }; var PREFIX_MATCH_TOKEN = { type: TokenType.PREFIX_MATCH_TOKEN }; var COLUMN_TOKEN = { type: TokenType.COLUMN_TOKEN }; var DASH_MATCH_TOKEN = { type: TokenType.DASH_MATCH_TOKEN }; var INCLUDE_MATCH_TOKEN = { type: TokenType.INCLUDE_MATCH_TOKEN }; var LEFT_CURLY_BRACKET_TOKEN = { type: TokenType.LEFT_CURLY_BRACKET_TOKEN }; var RIGHT_CURLY_BRACKET_TOKEN = { type: TokenType.RIGHT_CURLY_BRACKET_TOKEN }; var SUBSTRING_MATCH_TOKEN = { type: TokenType.SUBSTRING_MATCH_TOKEN }; var BAD_URL_TOKEN = { type: TokenType.BAD_URL_TOKEN }; var BAD_STRING_TOKEN = { type: TokenType.BAD_STRING_TOKEN }; var CDO_TOKEN = { type: TokenType.CDO_TOKEN }; var CDC_TOKEN = { type: TokenType.CDC_TOKEN }; var COLON_TOKEN = { type: TokenType.COLON_TOKEN }; var SEMICOLON_TOKEN = { type: TokenType.SEMICOLON_TOKEN }; var LEFT_SQUARE_BRACKET_TOKEN = { type: TokenType.LEFT_SQUARE_BRACKET_TOKEN }; var RIGHT_SQUARE_BRACKET_TOKEN = { type: TokenType.RIGHT_SQUARE_BRACKET_TOKEN }; var WHITESPACE_TOKEN = { type: TokenType.WHITESPACE_TOKEN }; var EOF_TOKEN = { type: TokenType.EOF_TOKEN }; var Tokenizer = /** @class */ function () { function Tokenizer() { this._value = []; } Tokenizer.prototype.write = function (chunk) { this._value = this._value.concat(toCodePoints(chunk)); }; Tokenizer.prototype.read = function () { var tokens = []; var token = this.consumeToken(); while (token !== EOF_TOKEN) { tokens.push(token); token = this.consumeToken(); } return tokens; }; Tokenizer.prototype.consumeToken = function () { var codePoint = this.consumeCodePoint(); switch (codePoint) { case QUOTATION_MARK: return this.consumeStringToken(QUOTATION_MARK); case NUMBER_SIGN: var c1 = this.peekCodePoint(0); var c2 = this.peekCodePoint(1); var c3 = this.peekCodePoint(2); if (isNameCodePoint(c1) || isValidEscape(c2, c3)) { var flags = isIdentifierStart(c1, c2, c3) ? FLAG_ID : FLAG_UNRESTRICTED; var value = this.consumeName(); return { type: TokenType.HASH_TOKEN, value: value, flags: flags }; } break; case DOLLAR_SIGN: if (this.peekCodePoint(0) === EQUALS_SIGN) { this.consumeCodePoint(); return SUFFIX_MATCH_TOKEN; } break; case APOSTROPHE: return this.consumeStringToken(APOSTROPHE); case LEFT_PARENTHESIS: return LEFT_PARENTHESIS_TOKEN; case RIGHT_PARENTHESIS: return RIGHT_PARENTHESIS_TOKEN; case ASTERISK: if (this.peekCodePoint(0) === EQUALS_SIGN) { this.consumeCodePoint(); return SUBSTRING_MATCH_TOKEN; } break; case PLUS_SIGN: if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) { this.reconsumeCodePoint(codePoint); return this.consumeNumericToken(); } break; case COMMA: return COMMA_TOKEN; case HYPHEN_MINUS: var e1 = codePoint; var e2 = this.peekCodePoint(0); var e3 = this.peekCodePoint(1); if (isNumberStart(e1, e2, e3)) { this.reconsumeCodePoint(codePoint); return this.consumeNumericToken(); } if (isIdentifierStart(e1, e2, e3)) { this.reconsumeCodePoint(codePoint); return this.consumeIdentLikeToken(); } if (e2 === HYPHEN_MINUS && e3 === GREATER_THAN_SIGN) { this.consumeCodePoint(); this.consumeCodePoint(); return CDC_TOKEN; } break; case FULL_STOP: if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) { this.reconsumeCodePoint(codePoint); return this.consumeNumericToken(); } break; case SOLIDUS: if (this.peekCodePoint(0) === ASTERISK) { this.consumeCodePoint(); while (true) { var c = this.consumeCodePoint(); if (c === ASTERISK) { c = this.consumeCodePoint(); if (c === SOLIDUS) { return this.consumeToken(); } } if (c === EOF) { return this.consumeToken(); } } } break; case COLON: return COLON_TOKEN; case SEMICOLON: return SEMICOLON_TOKEN; case LESS_THAN_SIGN: if (this.peekCodePoint(0) === EXCLAMATION_MARK && this.peekCodePoint(1) === HYPHEN_MINUS && this.peekCodePoint(2) === HYPHEN_MINUS) { this.consumeCodePoint(); this.consumeCodePoint(); return CDO_TOKEN; } break; case COMMERCIAL_AT: var a1 = this.peekCodePoint(0); var a2 = this.peekCodePoint(1); var a3 = this.peekCodePoint(2); if (isIdentifierStart(a1, a2, a3)) { var value = this.consumeName(); return { type: TokenType.AT_KEYWORD_TOKEN, value: value }; } break; case LEFT_SQUARE_BRACKET: return LEFT_SQUARE_BRACKET_TOKEN; case REVERSE_SOLIDUS: if (isValidEscape(codePoint, this.peekCodePoint(0))) { this.reconsumeCodePoint(codePoint); return this.consumeIdentLikeToken(); } break; case RIGHT_SQUARE_BRACKET: return RIGHT_SQUARE_BRACKET_TOKEN; case CIRCUMFLEX_ACCENT: if (this.peekCodePoint(0) === EQUALS_SIGN) { this.consumeCodePoint(); return PREFIX_MATCH_TOKEN; } break; case LEFT_CURLY_BRACKET: return LEFT_CURLY_BRACKET_TOKEN; case RIGHT_CURLY_BRACKET: return RIGHT_CURLY_BRACKET_TOKEN; case u: case U: var u1 = this.peekCodePoint(0); var u2 = this.peekCodePoint(1); if (u1 === PLUS_SIGN && (isHex(u2) || u2 === QUESTION_MARK)) { this.consumeCodePoint(); this.consumeUnicodeRangeToken(); } this.reconsumeCodePoint(codePoint); return this.consumeIdentLikeToken(); case VERTICAL_LINE: if (this.peekCodePoint(0) === EQUALS_SIGN) { this.consumeCodePoint(); return DASH_MATCH_TOKEN; } if (this.peekCodePoint(0) === VERTICAL_LINE) { this.consumeCodePoint(); return COLUMN_TOKEN; } break; case TILDE: if (this.peekCodePoint(0) === EQUALS_SIGN) { this.consumeCodePoint(); return INCLUDE_MATCH_TOKEN; } break; case EOF: return EOF_TOKEN; } if (isWhiteSpace(codePoint)) { this.consumeWhiteSpace(); return WHITESPACE_TOKEN; } if (isDigit(codePoint)) { this.reconsumeCodePoint(codePoint); return this.consumeNumericToken(); } if (isNameStartCodePoint(codePoint)) { this.reconsumeCodePoint(codePoint); return this.consumeIdentLikeToken(); } return { type: TokenType.DELIM_TOKEN, value: fromCodePoint(codePoint) }; }; Tokenizer.prototype.consumeCodePoint = function () { var value = this._value.shift(); return typeof value === 'undefined' ? -1 : value; }; Tokenizer.prototype.reconsumeCodePoint = function (codePoint) { this._value.unshift(codePoint); }; Tokenizer.prototype.peekCodePoint = function (delta) { if (delta >= this._value.length) { return -1; } return this._value[delta]; }; Tokenizer.prototype.consumeUnicodeRangeToken = function () { var digits = []; var codePoint = this.consumeCodePoint(); while (isHex(codePoint) && digits.length < 6) { digits.push(codePoint); codePoint = this.consumeCodePoint(); } var questionMarks = false; while (codePoint === QUESTION_MARK && digits.length < 6) { digits.push(codePoint); codePoint = this.consumeCodePoint(); questionMarks = true; } if (questionMarks) { var start_1 = parseInt(fromCodePoint.apply(void 0, digits.map(function (digit) { return digit === QUESTION_MARK ? ZERO : digit; })), 16); var end = parseInt(fromCodePoint.apply(void 0, digits.map(function (digit) { return digit === QUESTION_MARK ? F : digit; })), 16); return { type: TokenType.UNICODE_RANGE_TOKEN, start: start_1, end: end }; } var start = parseInt(fromCodePoint.apply(void 0, digits), 16); if (this.peekCodePoint(0) === HYPHEN_MINUS && isHex(this.peekCodePoint(1))) { this.consumeCodePoint(); codePoint = this.consumeCodePoint(); var endDigits = []; while (isHex(codePoint) && endDigits.length < 6) { endDigits.push(codePoint); codePoint = this.consumeCodePoint(); } var end = parseInt(fromCodePoint.apply(void 0, endDigits), 16); return { type: TokenType.UNICODE_RANGE_TOKEN, start: start, end: end }; } else { return { type: TokenType.UNICODE_RANGE_TOKEN, start: start, end: start }; } }; Tokenizer.prototype.consumeIdentLikeToken = function () { var value = this.consumeName(); if (value.toLowerCase() === 'url' && this.peekCodePoint(0) === LEFT_PARENTHESIS) { this.consumeCodePoint(); return this.consumeUrlToken(); } else if (this.peekCodePoint(0) === LEFT_PARENTHESIS) { this.consumeCodePoint(); return { type: TokenType.FUNCTION_TOKEN, value: value }; } return { type: TokenType.IDENT_TOKEN, value: value }; }; Tokenizer.prototype.consumeUrlToken = function () { var value = []; this.consumeWhiteSpace(); if (this.peekCodePoint(0) === EOF) { return { type: TokenType.URL_TOKEN, value: '' }; } var next = this.peekCodePoint(0); if (next === APOSTROPHE || next === QUOTATION_MARK) { var stringToken = this.consumeStringToken(this.consumeCodePoint()); if (stringToken.type === TokenType.STRING_TOKEN) { this.consumeWhiteSpace(); if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) { this.consumeCodePoint(); return { type: TokenType.URL_TOKEN, value: stringToken.value }; } } this.consumeBadUrlRemnants(); return BAD_URL_TOKEN; } while (true) { var codePoint = this.consumeCodePoint(); if (codePoint === EOF || codePoint === RIGHT_PARENTHESIS) { return { type: TokenType.URL_TOKEN, value: fromCodePoint.apply(void 0, value) }; } else if (isWhiteSpace(codePoint)) { this.consumeWhiteSpace(); if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) { this.consumeCodePoint(); return { type: TokenType.URL_TOKEN, value: fromCodePoint.apply(void 0, value) }; } this.consumeBadUrlRemnants(); return BAD_URL_TOKEN; } else if (codePoint === QUOTATION_MARK || codePoint === APOSTROPHE || codePoint === LEFT_PARENTHESIS || isNonPrintableCodePoint(codePoint)) { this.consumeBadUrlRemnants(); return BAD_URL_TOKEN; } else if (codePoint === REVERSE_SOLIDUS) { if (isValidEscape(codePoint, this.peekCodePoint(0))) { value.push(this.consumeEscapedCodePoint()); } else { this.consumeBadUrlRemnants(); return BAD_URL_TOKEN; } } else { value.push(codePoint); } } }; Tokenizer.prototype.consumeWhiteSpace = function () { while (isWhiteSpace(this.peekCodePoint(0))) { this.consumeCodePoint(); } }; Tokenizer.prototype.consumeBadUrlRemnants = function () { while (true) { var codePoint = this.consumeCodePoint(); if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) { return; } if (isValidEscape(codePoint, this.peekCodePoint(0))) { this.consumeEscapedCodePoint(); } } }; Tokenizer.prototype.consumeStringSlice = function (count) { var SLICE_STACK_SIZE = 60000; var value = ''; while (count > 0) { var amount = Math.min(SLICE_STACK_SIZE, count); value += fromCodePoint.apply(void 0, this._value.splice(0, amount)); count -= amount; } this._value.shift(); return value; }; Tokenizer.prototype.consumeStringToken = function (endingCodePoint) { var value = ''; var i = 0; do { var codePoint = this._value[i]; if (codePoint === EOF || codePoint === undefined || codePoint === endingCodePoint) { value += this.consumeStringSlice(i); return { type: TokenType.STRING_TOKEN, value: value }; } if (codePoint === LINE_FEED) { this._value.splice(0, i); return BAD_STRING_TOKEN; } if (codePoint === REVERSE_SOLIDUS) { var next = this._value[i + 1]; if (next !== EOF && next !== undefined) { if (next === LINE_FEED) { value += this.consumeStringSlice(i); i = -1; this._value.shift(); } else if (isValidEscape(codePoint, next)) { value += this.consumeStringSlice(i); value += fromCodePoint(this.consumeEscapedCodePoint()); i = -1; } } } i++; } while (true); }; Tokenizer.prototype.consumeNumber = function () { var repr = []; var type = FLAG_INTEGER; var c1 = this.peekCodePoint(0); if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) { repr.push(this.consumeCodePoint()); } while (isDigit(this.peekCodePoint(0))) { repr.push(this.consumeCodePoint()); } c1 = this.peekCodePoint(0); var c2 = this.peekCodePoint(1); if (c1 === FULL_STOP && isDigit(c2)) { repr.push(this.consumeCodePoint(), this.consumeCodePoint()); type = FLAG_NUMBER; while (isDigit(this.peekCodePoint(0))) { repr.push(this.consumeCodePoint()); } } c1 = this.peekCodePoint(0); c2 = this.peekCodePoint(1); var c3 = this.peekCodePoint(2); if ((c1 === E || c1 === e) && ((c2 === PLUS_SIGN || c2 === HYPHEN_MINUS) && isDigit(c3) || isDigit(c2))) { repr.push(this.consumeCodePoint(), this.consumeCodePoint()); type = FLAG_NUMBER; while (isDigit(this.peekCodePoint(0))) { repr.push(this.consumeCodePoint()); } } return [stringToNumber(repr), type]; }; Tokenizer.prototype.consumeNumericToken = function () { var _a = this.consumeNumber(), number = _a[0], flags = _a[1]; var c1 = this.peekCodePoint(0); var c2 = this.peekCodePoint(1); var c3 = this.peekCodePoint(2); if (isIdentifierStart(c1, c2, c3)) { var unit = this.consumeName(); return { type: TokenType.DIMENSION_TOKEN, number: number, flags: flags, unit: unit }; } if (c1 === PERCENTAGE_SIGN) { this.consumeCodePoint(); return { type: TokenType.PERCENTAGE_TOKEN, number: number, flags: flags }; } return { type: TokenType.NUMBER_TOKEN, number: number, flags: flags }; }; Tokenizer.prototype.consumeEscapedCodePoint = function () { var codePoint = this.consumeCodePoint(); if (isHex(codePoint)) { var hex = fromCodePoint(codePoint); while (isHex(this.peekCodePoint(0)) && hex.length < 6) { hex += fromCodePoint(this.consumeCodePoint()); } if (isWhiteSpace(this.peekCodePoint(0))) { this.consumeCodePoint(); } var hexCodePoint = parseInt(hex, 16); if (hexCodePoint === 0 || isSurrogateCodePoint(hexCodePoint) || hexCodePoint > 0x10ffff) { return REPLACEMENT_CHARACTER; } return hexCodePoint; } if (codePoint === EOF) { return REPLACEMENT_CHARACTER; } return codePoint; }; Tokenizer.prototype.consumeName = function () { var result = ''; while (true) { var codePoint = this.consumeCodePoint(); if (isNameCodePoint(codePoint)) { result += fromCodePoint(codePoint); } else if (isValidEscape(codePoint, this.peekCodePoint(0))) { result += fromCodePoint(this.consumeEscapedCodePoint()); } else { this.reconsumeCodePoint(codePoint); return result; } } }; return Tokenizer; }(); var Parser = /** @class */ function () { function Parser(tokens) { this._tokens = tokens; } Parser.create = function (value) { var tokenizer = new Tokenizer(); tokenizer.write(value); return new Parser(tokenizer.read()); }; Parser.parseValue = function (value) { return Parser.create(value).parseComponentValue(); }; Parser.parseValues = function (value) { return Parser.create(value).parseComponentValues(); }; Parser.prototype.parseComponentValue = function () { var token = this.consumeToken(); while (token.type === TokenType.WHITESPACE_TOKEN) { token = this.consumeToken(); } if (token.type === TokenType.EOF_TOKEN) { throw new SyntaxError("Error parsing CSS component value, unexpected EOF"); } this.reconsumeToken(token); var value = this.consumeComponentValue(); do { token = this.consumeToken(); } while (token.type === TokenType.WHITESPACE_TOKEN); if (token.type === TokenType.EOF_TOKEN) { return value; } throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one"); }; Parser.prototype.parseComponentValues = function () { var values = []; while (true) { var value = this.consumeComponentValue(); if (value.type === TokenType.EOF_TOKEN) { return values; } values.push(value); values.push(); } }; Parser.prototype.consumeComponentValue = function () { var token = this.consumeToken(); switch (token.type) { case TokenType.LEFT_CURLY_BRACKET_TOKEN: case TokenType.LEFT_SQUARE_BRACKET_TOKEN: case TokenType.LEFT_PARENTHESIS_TOKEN: return this.consumeSimpleBlock(token.type); case TokenType.FUNCTION_TOKEN: return this.consumeFunction(token); } return token; }; Parser.prototype.consumeSimpleBlock = function (type) { var block = { type: type, values: [] }; var token = this.consumeToken(); while (true) { if (token.type === TokenType.EOF_TOKEN || isEndingTokenFor(token, type)) { return block; } this.reconsumeToken(token); block.values.push(this.consumeComponentValue()); token = this.consumeToken(); } }; Parser.prototype.consumeFunction = function (functionToken) { var cssFunction = { name: functionToken.value, values: [], type: TokenType.FUNCTION }; while (true) { var token = this.consumeToken(); if (token.type === TokenType.EOF_TOKEN || token.type === TokenType.RIGHT_PARENTHESIS_TOKEN) { return cssFunction; } this.reconsumeToken(token); cssFunction.values.push(this.consumeComponentValue()); } }; Parser.prototype.consumeToken = function () { var token = this._tokens.shift(); return typeof token === 'undefined' ? EOF_TOKEN : token; }; Parser.prototype.reconsumeToken = function (token) { this._tokens.unshift(token); }; return Parser; }(); var isDimensionToken = function isDimensionToken(token) { return token.type === TokenType.DIMENSION_TOKEN; }; var isNumberToken = function isNumberToken(token) { return token.type === TokenType.NUMBER_TOKEN; }; var isIdentToken = function isIdentToken(token) { return token.type === TokenType.IDENT_TOKEN; }; var isStringToken = function isStringToken(token) { return token.type === TokenType.STRING_TOKEN; }; var isIdentWithValue = function isIdentWithValue(token, value) { return isIdentToken(token) && token.value === value; }; var nonWhiteSpace = function nonWhiteSpace(token) { return token.type !== TokenType.WHITESPACE_TOKEN; }; var nonFunctionArgSeparator = function nonFunctionArgSeparator(token) { return token.type !== TokenType.WHITESPACE_TOKEN && token.type !== TokenType.COMMA_TOKEN; }; var parseFunctionArgs = function parseFunctionArgs(tokens) { var args = []; var arg = []; tokens.forEach(function (token) { if (token.type === TokenType.COMMA_TOKEN) { if (arg.length === 0) { throw new Error("Error parsing function args, zero tokens for arg"); } args.push(arg); arg = []; return; } if (token.type !== TokenType.WHITESPACE_TOKEN) { arg.push(token); } }); if (arg.length) { args.push(arg); } return args; }; var isEndingTokenFor = function isEndingTokenFor(token, type) { if (type === TokenType.LEFT_CURLY_BRACKET_TOKEN && token.type === TokenType.RIGHT_CURLY_BRACKET_TOKEN) { return true; } if (type === TokenType.LEFT_SQUARE_BRACKET_TOKEN && token.type === TokenType.RIGHT_SQUARE_BRACKET_TOKEN) { return true; } return type === TokenType.LEFT_PARENTHESIS_TOKEN && token.type === TokenType.RIGHT_PARENTHESIS_TOKEN; }; var isLength = function isLength(token) { return token.type === TokenType.NUMBER_TOKEN || token.type === TokenType.DIMENSION_TOKEN; }; var isLengthPercentage = function isLengthPercentage(token) { return token.type === TokenType.PERCENTAGE_TOKEN || isLength(token); }; var parseLengthPercentageTuple = function parseLengthPercentageTuple(tokens) { return tokens.length > 1 ? [tokens[0], tokens[1]] : [tokens[0]]; }; var ZERO_LENGTH = { type: TokenType.NUMBER_TOKEN, number: 0, flags: FLAG_INTEGER }; var FIFTY_PERCENT = { type: TokenType.PERCENTAGE_TOKEN, number: 50, flags: FLAG_INTEGER }; var HUNDRED_PERCENT = { type: TokenType.PERCENTAGE_TOKEN, number: 100, flags: FLAG_INTEGER }; var getAbsoluteValueForTuple = function getAbsoluteValueForTuple(tuple, width, height) { var x = tuple[0], y = tuple[1]; return [getAbsoluteValue(x, width), getAbsoluteValue(typeof y !== 'undefined' ? y : x, height)]; }; var getAbsoluteValue = function getAbsoluteValue(token, parent) { if (token.type === TokenType.PERCENTAGE_TOKEN) { return token.number / 100 * parent; } if (isDimensionToken(token)) { switch (token.unit) { case 'rem': case 'em': return 16 * token.number; // TODO use correct font-size case 'px': default: return token.number; } } return token.number; }; var DEG = 'deg'; var GRAD = 'grad'; var RAD = 'rad'; var TURN = 'turn'; var angle = { name: 'angle', parse: function parse(value) { if (value.type === TokenType.DIMENSION_TOKEN) { switch (value.unit) { case DEG: return Math.PI * value.number / 180; case GRAD: return Math.PI / 200 * value.number; case RAD: return value.number; case TURN: return Math.PI * 2 * value.number; } } throw new Error("Unsupported angle type"); } }; var isAngle = function isAngle(value) { if (value.type === TokenType.DIMENSION_TOKEN) { if (value.unit === DEG || value.unit === GRAD || value.unit === RAD || value.unit === TURN) { return true; } } return false; }; var parseNamedSide = function parseNamedSide(tokens) { var sideOrCorner = tokens.filter(isIdentToken).map(function (ident) { return ident.value; }).join(' '); switch (sideOrCorner) { case 'to bottom right': case 'to right bottom': case 'left top': case 'top left': return [ZERO_LENGTH, ZERO_LENGTH]; case 'to top': case 'bottom': return deg(0); case 'to bottom left': case 'to left bottom': case 'right top': case 'top right': return [ZERO_LENGTH, HUNDRED_PERCENT]; case 'to right': case 'left': return deg(90); case 'to top left': case 'to left top': case 'right bottom': case 'bottom right': return [HUNDRED_PERCENT, HUNDRED_PERCENT]; case 'to bottom': case 'top': return deg(180); case 'to top right': case 'to right top': case 'left bottom': case 'bottom left': return [HUNDRED_PERCENT, ZERO_LENGTH]; case 'to left': case 'right': return deg(270); } return 0; }; var deg = function deg(_deg) { return Math.PI * _deg / 180; }; var color = { name: 'color', parse: function parse(value) { if (value.type === TokenType.FUNCTION) { var colorFunction = SUPPORTED_COLOR_FUNCTIONS[value.name]; if (typeof colorFunction === 'undefined') { throw new Error("Attempting to parse an unsupported color function \"" + value.name + "\""); } return colorFunction(value.values); } if (value.type === TokenType.HASH_TOKEN) { if (value.value.length === 3) { var r = value.value.substring(0, 1); var g = value.value.substring(1, 2); var b = value.value.substring(2, 3); return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), 1); } if (value.value.length === 4) { var r = value.value.substring(0, 1); var g = value.value.substring(1, 2); var b = value.value.substring(2, 3); var a = value.value.substring(3, 4); return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), parseInt(a + a, 16) / 255); } if (value.value.length === 6) { var r = value.value.substring(0, 2); var g = value.value.substring(2, 4); var b = value.value.substring(4, 6); return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1); } if (value.value.length === 8) { var r = value.value.substring(0, 2); var g = value.value.substring(2, 4); var b = value.value.substring(4, 6); var a = value.value.substring(6, 8); return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), parseInt(a, 16) / 255); } } if (value.type === TokenType.IDENT_TOKEN) { var namedColor = COLORS[value.value.toUpperCase()]; if (typeof namedColor !== 'undefined') { return namedColor; } } return COLORS.TRANSPARENT; } }; var isTransparent = function isTransparent(color) { return (0xff & color) === 0; }; var asString = function asString(color) { var alpha = 0xff & color; var blue = 0xff & color >> 8; var green = 0xff & color >> 16; var red = 0xff & color >> 24; return alpha < 255 ? "rgba(" + red + "," + green + "," + blue + "," + alpha / 255 + ")" : "rgb(" + red + "," + green + "," + blue + ")"; }; var pack = function pack(r, g, b, a) { return (r << 24 | g << 16 | b << 8 | Math.round(a * 255) << 0) >>> 0; }; var getTokenColorValue = function getTokenColorValue(token, i) { if (token.type === TokenType.NUMBER_TOKEN) { return token.number; } if (token.type === TokenType.PERCENTAGE_TOKEN) { var max = i === 3 ? 1 : 255; return i === 3 ? token.number / 100 * max : Math.round(token.number / 100 * max); } return 0; }; var rgb = function rgb(args) { var tokens = args.filter(nonFunctionArgSeparator); if (tokens.length === 3) { var _a = tokens.map(getTokenColorValue), r = _a[0], g = _a[1], b = _a[2]; return pack(r, g, b, 1); } if (tokens.length === 4) { var _b = tokens.map(getTokenColorValue), r = _b[0], g = _b[1], b = _b[2], a = _b[3]; return pack(r, g, b, a); } return 0; }; function hue2rgb(t1, t2, hue) { if (hue < 0) { hue += 1; } if (hue >= 1) { hue -= 1; } if (hue < 1 / 6) { return (t2 - t1) * hue * 6 + t1; } else if (hue < 1 / 2) { return t2; } else if (hue < 2 / 3) { return (t2 - t1) * 6 * (2 / 3 - hue) + t1; } else { return t1; } } var hsl = function hsl(args) { var tokens = args.filter(nonFunctionArgSeparator); var hue = tokens[0], saturation = tokens[1], lightness = tokens[2], alpha = tokens[3]; var h = (hue.type === TokenType.NUMBER_TOKEN ? deg(hue.number) : angle.parse(hue)) / (Math.PI * 2); var s = isLengthPercentage(saturation) ? saturation.number / 100 : 0; var l = isLengthPercentage(lightness) ? lightness.number / 100 : 0; var a = typeof alpha !== 'undefined' && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1; if (s === 0) { return pack(l * 255, l * 255, l * 255, 1); } var t2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var t1 = l * 2 - t2; var r = hue2rgb(t1, t2, h + 1 / 3); var g = hue2rgb(t1, t2, h); var b = hue2rgb(t1, t2, h - 1 / 3); return pack(r * 255, g * 255, b * 255, a); }; var SUPPORTED_COLOR_FUNCTIONS = { hsl: hsl, hsla: hsl, rgb: rgb, rgba: rgb }; var COLORS = { ALICEBLUE: 0xf0f8ffff, ANTIQUEWHITE: 0xfaebd7ff, AQUA: 0x00ffffff, AQUAMARINE: 0x7fffd4ff, AZURE: 0xf0ffffff, BEIGE: 0xf5f5dcff, BISQUE: 0xffe4c4ff, BLACK: 0x000000ff, BLANCHEDALMOND: 0xffebcdff, BLUE: 0x0000ffff, BLUEVIOLET: 0x8a2be2ff, BROWN: 0xa52a2aff, BURLYWOOD: 0xdeb887ff, CADETBLUE: 0x5f9ea0ff, CHARTREUSE: 0x7fff00ff, CHOCOLATE: 0xd2691eff, CORAL: 0xff7f50ff, CORNFLOWERBLUE: 0x6495edff, CORNSILK: 0xfff8dcff, CRIMSON: 0xdc143cff, CYAN: 0x00ffffff, DARKBLUE: 0x00008bff, DARKCYAN: 0x008b8bff, DARKGOLDENROD: 0xb886bbff, DARKGRAY: 0xa9a9a9ff, DARKGREEN: 0x006400ff, DARKGREY: 0xa9a9a9ff, DARKKHAKI: 0xbdb76bff, DARKMAGENTA: 0x8b008bff, DARKOLIVEGREEN: 0x556b2fff, DARKORANGE: 0xff8c00ff, DARKORCHID: 0x9932ccff, DARKRED: 0x8b0000ff, DARKSALMON: 0xe9967aff, DARKSEAGREEN: 0x8fbc8fff, DARKSLATEBLUE: 0x483d8bff, DARKSLATEGRAY: 0x2f4f4fff, DARKSLATEGREY: 0x2f4f4fff, DARKTURQUOISE: 0x00ced1ff, DARKVIOLET: 0x9400d3ff, DEEPPINK: 0xff1493ff, DEEPSKYBLUE: 0x00bfffff, DIMGRAY: 0x696969ff, DIMGREY: 0x696969ff, DODGERBLUE: 0x1e90ffff, FIREBRICK: 0xb22222ff, FLORALWHITE: 0xfffaf0ff, FORESTGREEN: 0x228b22ff, FUCHSIA: 0xff00ffff, GAINSBORO: 0xdcdcdcff, GHOSTWHITE: 0xf8f8ffff, GOLD: 0xffd700ff, GOLDENROD: 0xdaa520ff, GRAY: 0x808080ff, GREEN: 0x008000ff, GREENYELLOW: 0xadff2fff, GREY: 0x808080ff, HONEYDEW: 0xf0fff0ff, HOTPINK: 0xff69b4ff, INDIANRED: 0xcd5c5cff, INDIGO: 0x4b0082ff, IVORY: 0xfffff0ff, KHAKI: 0xf0e68cff, LAVENDER: 0xe6e6faff, LAVENDERBLUSH: 0xfff0f5ff, LAWNGREEN: 0x7cfc00ff, LEMONCHIFFON: 0xfffacdff, LIGHTBLUE: 0xadd8e6ff, LIGHTCORAL: 0xf08080ff, LIGHTCYAN: 0xe0ffffff, LIGHTGOLDENRODYELLOW: 0xfafad2ff, LIGHTGRAY: 0xd3d3d3ff, LIGHTGREEN: 0x90ee90ff, LIGHTGREY: 0xd3d3d3ff, LIGHTPINK: 0xffb6c1ff, LIGHTSALMON: 0xffa07aff, LIGHTSEAGREEN: 0x20b2aaff, LIGHTSKYBLUE: 0x87cefaff, LIGHTSLATEGRAY: 0x778899ff, LIGHTSLATEGREY: 0x778899ff, LIGHTSTEELBLUE: 0xb0c4deff, LIGHTYELLOW: 0xffffe0ff, LIME: 0x00ff00ff, LIMEGREEN: 0x32cd32ff, LINEN: 0xfaf0e6ff, MAGENTA: 0xff00ffff, MAROON: 0x800000ff, MEDIUMAQUAMARINE: 0x66cdaaff, MEDIUMBLUE: 0x0000cdff, MEDIUMORCHID: 0xba55d3ff, MEDIUMPURPLE: 0x9370dbff, MEDIUMSEAGREEN: 0x3cb371ff, MEDIUMSLATEBLUE: 0x7b68eeff, MEDIUMSPRINGGREEN: 0x00fa9aff, MEDIUMTURQUOISE: 0x48d1ccff, MEDIUMVIOLETRED: 0xc71585ff, MIDNIGHTBLUE: 0x191970ff, MINTCREAM: 0xf5fffaff, MISTYROSE: 0xffe4e1ff, MOCCASIN: 0xffe4b5ff, NAVAJOWHITE: 0xffdeadff, NAVY: 0x000080ff, OLDLACE: 0xfdf5e6ff, OLIVE: 0x808000ff, OLIVEDRAB: 0x6b8e23ff, ORANGE: 0xffa500ff, ORANGERED: 0xff4500ff, ORCHID: 0xda70d6ff, PALEGOLDENROD: 0xeee8aaff, PALEGREEN: 0x98fb98ff, PALETURQUOISE: 0xafeeeeff, PALEVIOLETRED: 0xdb7093ff, PAPAYAWHIP: 0xffefd5ff, PEACHPUFF: 0xffdab9ff, PERU: 0xcd853fff, PINK: 0xffc0cbff, PLUM: 0xdda0ddff, POWDERBLUE: 0xb0e0e6ff, PURPLE: 0x800080ff, REBECCAPURPLE: 0x663399ff, RED: 0xff0000ff, ROSYBROWN: 0xbc8f8fff, ROYALBLUE: 0x4169e1ff, SADDLEBROWN: 0x8b4513ff, SALMON: 0xfa8072ff, SANDYBROWN: 0xf4a460ff, SEAGREEN: 0x2e8b57ff, SEASHELL: 0xfff5eeff, SIENNA: 0xa0522dff, SILVER: 0xc0c0c0ff, SKYBLUE: 0x87ceebff, SLATEBLUE: 0x6a5acdff, SLATEGRAY: 0x708090ff, SLATEGREY: 0x708090ff, SNOW: 0xfffafaff, SPRINGGREEN: 0x00ff7fff, STEELBLUE: 0x4682b4ff, TAN: 0xd2b48cff, TEAL: 0x008080ff, THISTLE: 0xd8bfd8ff, TOMATO: 0xff6347ff, TRANSPARENT: 0x00000000, TURQUOISE: 0x40e0d0ff, VIOLET: 0xee82eeff, WHEAT: 0xf5deb3ff, WHITE: 0xffffffff, WHITESMOKE: 0xf5f5f5ff, YELLOW: 0xffff00ff, YELLOWGREEN: 0x9acd32ff }; var PropertyDescriptorParsingType; (function (PropertyDescriptorParsingType) { PropertyDescriptorParsingType[PropertyDescriptorParsingType["VALUE"] = 0] = "VALUE"; PropertyDescriptorParsingType[PropertyDescriptorParsingType["LIST"] = 1] = "LIST"; PropertyDescriptorParsingType[PropertyDescriptorParsingType["IDENT_VALUE"] = 2] = "IDENT_VALUE"; PropertyDescriptorParsingType[PropertyDescriptorParsingType["TYPE_VALUE"] = 3] = "TYPE_VALUE"; PropertyDescriptorParsingType[PropertyDescriptorParsingType["TOKEN_VALUE"] = 4] = "TOKEN_VALUE"; })(PropertyDescriptorParsingType || (PropertyDescriptorParsingType = {})); var BACKGROUND_CLIP; (function (BACKGROUND_CLIP) { BACKGROUND_CLIP[BACKGROUND_CLIP["BORDER_BOX"] = 0] = "BORDER_BOX"; BACKGROUND_CLIP[BACKGROUND_CLIP["PADDING_BOX"] = 1] = "PADDING_BOX"; BACKGROUND_CLIP[BACKGROUND_CLIP["CONTENT_BOX"] = 2] = "CONTENT_BOX"; })(BACKGROUND_CLIP || (BACKGROUND_CLIP = {})); var backgroundClip = { name: 'background-clip', initialValue: 'border-box', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return tokens.map(function (token) { if (isIdentToken(token)) { switch (token.value) { case 'padding-box': return BACKGROUND_CLIP.PADDING_BOX; case 'content-box': return BACKGROUND_CLIP.CONTENT_BOX; } } return BACKGROUND_CLIP.BORDER_BOX; }); } }; var backgroundColor = { name: "background-color", initialValue: 'transparent', prefix: false, type: PropertyDescriptorParsingType.TYPE_VALUE, format: 'color' }; var parseColorStop = function parseColorStop(args) { var color$1 = color.parse(args[0]); var stop = args[1]; return stop && isLengthPercentage(stop) ? { color: color$1, stop: stop } : { color: color$1, stop: null }; }; var processColorStops = function processColorStops(stops, lineLength) { var first = stops[0]; var last = stops[stops.length - 1]; if (first.stop === null) { first.stop = ZERO_LENGTH; } if (last.stop === null) { last.stop = HUNDRED_PERCENT; } var processStops = []; var previous = 0; for (var i = 0; i < stops.length; i++) { var stop_1 = stops[i].stop; if (stop_1 !== null) { var absoluteValue = getAbsoluteValue(stop_1, lineLength); if (absoluteValue > previous) { processStops.push(absoluteValue); } else { processStops.push(previous); } previous = absoluteValue; } else { processStops.push(null); } } var gapBegin = null; for (var i = 0; i < processStops.length; i++) { var stop_2 = processStops[i]; if (stop_2 === null) { if (gapBegin === null) { gapBegin = i; } } else if (gapBegin !== null) { var gapLength = i - gapBegin; var beforeGap = processStops[gapBegin - 1]; var gapValue = (stop_2 - beforeGap) / (gapLength + 1); for (var g = 1; g <= gapLength; g++) { processStops[gapBegin + g - 1] = gapValue * g; } gapBegin = null; } } return stops.map(function (_a, i) { var color = _a.color; return { color: color, stop: Math.max(Math.min(1, processStops[i] / lineLength), 0) }; }); }; var getAngleFromCorner = function getAngleFromCorner(corner, width, height) { var centerX = width / 2; var centerY = height / 2; var x = getAbsoluteValue(corner[0], width) - centerX; var y = centerY - getAbsoluteValue(corner[1], height); return (Math.atan2(y, x) + Math.PI * 2) % (Math.PI * 2); }; var calculateGradientDirection = function calculateGradientDirection(angle, width, height) { var radian = typeof angle === 'number' ? angle : getAngleFromCorner(angle, width, height); var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian)); var halfWidth = width / 2; var halfHeight = height / 2; var halfLineLength = lineLength / 2; var yDiff = Math.sin(radian - Math.PI / 2) * halfLineLength; var xDiff = Math.cos(radian - Math.PI / 2) * halfLineLength; return [lineLength, halfWidth - xDiff, halfWidth + xDiff, halfHeight - yDiff, halfHeight + yDiff]; }; var distance = function distance(a, b) { return Math.sqrt(a * a + b * b); }; var findCorner = function findCorner(width, height, x, y, closest) { var corners = [[0, 0], [0, height], [width, 0], [width, height]]; return corners.reduce(function (stat, corner) { var cx = corner[0], cy = corner[1]; var d = distance(x - cx, y - cy); if (closest ? d < stat.optimumDistance : d > stat.optimumDistance) { return { optimumCorner: corner, optimumDistance: d }; } return stat; }, { optimumDistance: closest ? Infinity : -Infinity, optimumCorner: null }).optimumCorner; }; var calculateRadius = function calculateRadius(gradient, x, y, width, height) { var rx = 0; var ry = 0; switch (gradient.size) { case CSSRadialExtent.CLOSEST_SIDE: // The ending shape is sized so that that it exactly meets the side of the gradient box closest to the gradient’s center. // If the shape is an ellipse, it exactly meets the closest side in each dimension. if (gradient.shape === CSSRadialShape.CIRCLE) { rx = ry = Math.min(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height)); } else if (gradient.shape === CSSRadialShape.ELLIPSE) { rx = Math.min(Math.abs(x), Math.abs(x - width)); ry = Math.min(Math.abs(y), Math.abs(y - height)); } break; case CSSRadialExtent.CLOSEST_CORNER: // The ending shape is sized so that that it passes through the corner of the gradient box closest to the gradient’s center. // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified. if (gradient.shape === CSSRadialShape.CIRCLE) { rx = ry = Math.min(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height)); } else if (gradient.shape === CSSRadialShape.ELLIPSE) { // Compute the ratio ry/rx (which is to be the same as for "closest-side") var c = Math.min(Math.abs(y), Math.abs(y - height)) / Math.min(Math.abs(x), Math.abs(x - width)); var _a = findCorner(width, height, x, y, true), cx = _a[0], cy = _a[1]; rx = distance(cx - x, (cy - y) / c); ry = c * rx; } break; case CSSRadialExtent.FARTHEST_SIDE: // Same as closest-side, except the ending shape is sized based on the farthest side(s) if (gradient.shape === CSSRadialShape.CIRCLE) { rx = ry = Math.max(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height)); } else if (gradient.shape === CSSRadialShape.ELLIPSE) { rx = Math.max(Math.abs(x), Math.abs(x - width)); ry = Math.max(Math.abs(y), Math.abs(y - height)); } break; case CSSRadialExtent.FARTHEST_CORNER: // Same as closest-corner, except the ending shape is sized based on the farthest corner. // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified. if (gradient.shape === CSSRadialShape.CIRCLE) { rx = ry = Math.max(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height)); } else if (gradient.shape === CSSRadialShape.ELLIPSE) { // Compute the ratio ry/rx (which is to be the same as for "farthest-side") var c = Math.max(Math.abs(y), Math.abs(y - height)) / Math.max(Math.abs(x), Math.abs(x - width)); var _b = findCorner(width, height, x, y, false), cx = _b[0], cy = _b[1]; rx = distance(cx - x, (cy - y) / c); ry = c * rx; } break; } if (Array.isArray(gradient.size)) { rx = getAbsoluteValue(gradient.size[0], width); ry = gradient.size.length === 2 ? getAbsoluteValue(gradient.size[1], height) : rx; } return [rx, ry]; }; var linearGradient = function linearGradient(tokens) { var angle$1 = deg(180); var stops = []; parseFunctionArgs(tokens).forEach(function (arg, i) { if (i === 0) { var firstToken = arg[0]; if (firstToken.type === TokenType.IDENT_TOKEN && firstToken.value === 'to') { angle$1 = parseNamedSide(arg); return; } else if (isAngle(firstToken)) { angle$1 = angle.parse(firstToken); return; } } var colorStop = parseColorStop(arg); stops.push(colorStop); }); return { angle: angle$1, stops: stops, type: CSSImageType.LINEAR_GRADIENT }; }; var prefixLinearGradient = function prefixLinearGradient(tokens) { var angle$1 = deg(180); var stops = []; parseFunctionArgs(tokens).forEach(function (arg, i) { if (i === 0) { var firstToken = arg[0]; if (firstToken.type === TokenType.IDENT_TOKEN && ['top', 'left', 'right', 'bottom'].indexOf(firstToken.value) !== -1) { angle$1 = parseNamedSide(arg); return; } else if (isAngle(firstToken)) { angle$1 = (angle.parse(firstToken) + deg(270)) % deg(360); return; } } var colorStop = parseColorStop(arg); stops.push(colorStop); }); return { angle: angle$1, stops: stops, type: CSSImageType.LINEAR_GRADIENT }; }; var testRangeBounds = function testRangeBounds(document) { var TEST_HEIGHT = 123; if (document.createRange) { var range = document.createRange(); if (range.getBoundingClientRect) { var testElement = document.createElement('boundtest'); testElement.style.height = TEST_HEIGHT + "px"; testElement.style.display = 'block'; document.body.appendChild(testElement); range.selectNode(testElement); var rangeBounds = range.getBoundingClientRect(); var rangeHeight = Math.round(rangeBounds.height); document.body.removeChild(testElement); if (rangeHeight === TEST_HEIGHT) { return true; } } } return false; }; var testCORS = function testCORS() { return typeof new Image().crossOrigin !== 'undefined'; }; var testResponseType = function testResponseType() { return typeof new XMLHttpRequest().responseType === 'string'; }; var testSVG = function testSVG(document) { var img = new Image(); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); if (!ctx) { return false; } img.src = "data:image/svg+xml,"; try { ctx.drawImage(img, 0, 0); canvas.toDataURL(); } catch (e) { return false; } return true; }; var isGreenPixel = function isGreenPixel(data) { return data[0] === 0 && data[1] === 255 && data[2] === 0 && data[3] === 255; }; var testForeignObject = function testForeignObject(document) { var canvas = document.createElement('canvas'); var size = 100; canvas.width = size; canvas.height = size; var ctx = canvas.getContext('2d'); if (!ctx) { return Promise.reject(false); } ctx.fillStyle = 'rgb(0, 255, 0)'; ctx.fillRect(0, 0, size, size); var img = new Image(); var greenImageSrc = canvas.toDataURL(); img.src = greenImageSrc; var svg = createForeignObjectSVG(size, size, 0, 0, img); ctx.fillStyle = 'red'; ctx.fillRect(0, 0, size, size); return loadSerializedSVG(svg).then(function (img) { ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, size, size).data; ctx.fillStyle = 'red'; ctx.fillRect(0, 0, size, size); var node = document.createElement('div'); node.style.backgroundImage = "url(" + greenImageSrc + ")"; node.style.height = size + "px"; // Firefox 55 does not render inline tags return isGreenPixel(data) ? loadSerializedSVG(createForeignObjectSVG(size, size, 0, 0, node)) : Promise.reject(false); }).then(function (img) { ctx.drawImage(img, 0, 0); // Edge does not render background-images return isGreenPixel(ctx.getImageData(0, 0, size, size).data); })["catch"](function () { return false; }); }; var createForeignObjectSVG = function createForeignObjectSVG(width, height, x, y, node) { var xmlns = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(xmlns, 'svg'); var foreignObject = document.createElementNS(xmlns, 'foreignObject'); svg.setAttributeNS(null, 'width', width.toString()); svg.setAttributeNS(null, 'height', height.toString()); foreignObject.setAttributeNS(null, 'width', '100%'); foreignObject.setAttributeNS(null, 'height', '100%'); foreignObject.setAttributeNS(null, 'x', x.toString()); foreignObject.setAttributeNS(null, 'y', y.toString()); foreignObject.setAttributeNS(null, 'externalResourcesRequired', 'true'); svg.appendChild(foreignObject); foreignObject.appendChild(node); return svg; }; var loadSerializedSVG = function loadSerializedSVG(svg) { return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { return resolve(img); }; img.onerror = reject; img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg)); }); }; var FEATURES = { get SUPPORT_RANGE_BOUNDS() { var value = testRangeBounds(document); Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', { value: value }); return value; }, get SUPPORT_SVG_DRAWING() { var value = testSVG(document); Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', { value: value }); return value; }, get SUPPORT_FOREIGNOBJECT_DRAWING() { var value = typeof Array.from === 'function' && typeof window.fetch === 'function' ? testForeignObject(document) : Promise.resolve(false); Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', { value: value }); return value; }, get SUPPORT_CORS_IMAGES() { var value = testCORS(); Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', { value: value }); return value; }, get SUPPORT_RESPONSE_TYPE() { var value = testResponseType(); Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', { value: value }); return value; }, get SUPPORT_CORS_XHR() { var value = ('withCredentials' in new XMLHttpRequest()); Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', { value: value }); return value; } }; var Logger = /** @class */ function () { function Logger(_a) { var id = _a.id, enabled = _a.enabled; this.id = id; this.enabled = enabled; this.start = Date.now(); } // eslint-disable-next-line @typescript-eslint/no-explicit-any Logger.prototype.debug = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (this.enabled) { // eslint-disable-next-line no-console if (typeof window !== 'undefined' && window.console && typeof console.debug === 'function') { // eslint-disable-next-line no-console console.debug.apply(console, [this.id, this.getTime() + "ms"].concat(args)); } else { this.info.apply(this, args); } } }; Logger.prototype.getTime = function () { return Date.now() - this.start; }; Logger.create = function (options) { Logger.instances[options.id] = new Logger(options); }; Logger.destroy = function (id) { delete Logger.instances[id]; }; Logger.getInstance = function (id) { var instance = Logger.instances[id]; if (typeof instance === 'undefined') { throw new Error("No logger instance found with id " + id); } return instance; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any Logger.prototype.info = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (this.enabled) { // eslint-disable-next-line no-console if (typeof window !== 'undefined' && window.console && typeof console.info === 'function') { // eslint-disable-next-line no-console console.info.apply(console, [this.id, this.getTime() + "ms"].concat(args)); } } }; // eslint-disable-next-line @typescript-eslint/no-explicit-any Logger.prototype.error = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (this.enabled) { // eslint-disable-next-line no-console if (typeof window !== 'undefined' && window.console && typeof console.error === 'function') { // eslint-disable-next-line no-console console.error.apply(console, [this.id, this.getTime() + "ms"].concat(args)); } else { this.info.apply(this, args); } } }; Logger.instances = {}; return Logger; }(); var CacheStorage = /** @class */ function () { function CacheStorage() {} CacheStorage.create = function (name, options) { return CacheStorage._caches[name] = new Cache(name, options); }; CacheStorage.destroy = function (name) { delete CacheStorage._caches[name]; }; CacheStorage.open = function (name) { var cache = CacheStorage._caches[name]; if (typeof cache !== 'undefined') { return cache; } throw new Error("Cache with key \"" + name + "\" not found"); }; CacheStorage.getOrigin = function (url) { var link = CacheStorage._link; if (!link) { return 'about:blank'; } link.href = url; link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/ return link.protocol + link.hostname + link.port; }; CacheStorage.isSameOrigin = function (src) { return CacheStorage.getOrigin(src) === CacheStorage._origin; }; CacheStorage.setContext = function (window) { CacheStorage._link = window.document.createElement('a'); CacheStorage._origin = CacheStorage.getOrigin(window.location.href); }; CacheStorage.getInstance = function () { var current = CacheStorage._current; if (current === null) { throw new Error("No cache instance attached"); } return current; }; CacheStorage.attachInstance = function (cache) { CacheStorage._current = cache; }; CacheStorage.detachInstance = function () { CacheStorage._current = null; }; CacheStorage._caches = {}; CacheStorage._origin = 'about:blank'; CacheStorage._current = null; return CacheStorage; }(); var Cache = /** @class */ function () { function Cache(id, options) { this.id = id; this._options = options; this._cache = {}; } Cache.prototype.addImage = function (src) { var result = Promise.resolve(); if (this.has(src)) { return result; } if (isBlobImage(src) || isRenderable(src)) { this._cache[src] = this.loadImage(src); return result; } return result; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any Cache.prototype.match = function (src) { return this._cache[src]; }; Cache.prototype.loadImage = function (key) { return __awaiter(this, void 0, void 0, function () { var isSameOrigin, useCORS, useProxy, src; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: isSameOrigin = CacheStorage.isSameOrigin(key); useCORS = !isInlineImage(key) && this._options.useCORS === true && FEATURES.SUPPORT_CORS_IMAGES && !isSameOrigin; useProxy = !isInlineImage(key) && !isSameOrigin && typeof this._options.proxy === 'string' && FEATURES.SUPPORT_CORS_XHR && !useCORS; if (!isSameOrigin && this._options.allowTaint === false && !isInlineImage(key) && !useProxy && !useCORS) { return [2 /*return*/ ]; } src = key; if (!useProxy) return [3 /*break*/ , 2]; return [4 /*yield*/ , this.proxy(src)]; case 1: src = _a.sent(); _a.label = 2; case 2: Logger.getInstance(this.id).debug("Added image " + key.substring(0, 256)); return [4 /*yield*/ , new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { return resolve(img); }; img.onerror = reject; //ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous if (isInlineBase64Image(src) || useCORS) { img.crossOrigin = 'anonymous'; } img.src = src; if (img.complete === true) { // Inline XML images may fail to parse, throwing an Error later on setTimeout(function () { return resolve(img); }, 500); } if (_this._options.imageTimeout > 0) { setTimeout(function () { return reject("Timed out (" + _this._options.imageTimeout + "ms) loading image"); }, _this._options.imageTimeout); } })]; case 3: return [2 /*return*/ , _a.sent()]; } }); }); }; Cache.prototype.has = function (key) { return typeof this._cache[key] !== 'undefined'; }; Cache.prototype.keys = function () { return Promise.resolve(Object.keys(this._cache)); }; Cache.prototype.proxy = function (src) { var _this = this; var proxy = this._options.proxy; if (!proxy) { throw new Error('No proxy defined'); } var key = src.substring(0, 256); return new Promise(function (resolve, reject) { var responseType = FEATURES.SUPPORT_RESPONSE_TYPE ? 'blob' : 'text'; var xhr = new XMLHttpRequest(); xhr.onload = function () { if (xhr.status === 200) { if (responseType === 'text') { resolve(xhr.response); } else { var reader_1 = new FileReader(); reader_1.addEventListener('load', function () { return resolve(reader_1.result); }, false); reader_1.addEventListener('error', function (e) { return reject(e); }, false); reader_1.readAsDataURL(xhr.response); } } else { reject("Failed to proxy resource " + key + " with status code " + xhr.status); } }; xhr.onerror = reject; xhr.open('GET', proxy + "?url=" + encodeURIComponent(src) + "&responseType=" + responseType); if (responseType !== 'text' && xhr instanceof XMLHttpRequest) { xhr.responseType = responseType; } if (_this._options.imageTimeout) { var timeout_1 = _this._options.imageTimeout; xhr.timeout = timeout_1; xhr.ontimeout = function () { return reject("Timed out (" + timeout_1 + "ms) proxying " + key); }; } xhr.send(); }); }; return Cache; }(); var INLINE_SVG = /^data:image\/svg\+xml/i; var INLINE_BASE64 = /^data:image\/.*;base64,/i; var INLINE_IMG = /^data:image\/.*/i; var isRenderable = function isRenderable(src) { return FEATURES.SUPPORT_SVG_DRAWING || !isSVG(src); }; var isInlineImage = function isInlineImage(src) { return INLINE_IMG.test(src); }; var isInlineBase64Image = function isInlineBase64Image(src) { return INLINE_BASE64.test(src); }; var isBlobImage = function isBlobImage(src) { return src.substr(0, 4) === 'blob'; }; var isSVG = function isSVG(src) { return src.substr(-3).toLowerCase() === 'svg' || INLINE_SVG.test(src); }; var webkitGradient = function webkitGradient(tokens) { var angle = deg(180); var stops = []; var type = CSSImageType.LINEAR_GRADIENT; var shape = CSSRadialShape.CIRCLE; var size = CSSRadialExtent.FARTHEST_CORNER; var position = []; parseFunctionArgs(tokens).forEach(function (arg, i) { var firstToken = arg[0]; if (i === 0) { if (isIdentToken(firstToken) && firstToken.value === 'linear') { type = CSSImageType.LINEAR_GRADIENT; return; } else if (isIdentToken(firstToken) && firstToken.value === 'radial') { type = CSSImageType.RADIAL_GRADIENT; return; } } if (firstToken.type === TokenType.FUNCTION) { if (firstToken.name === 'from') { var color$1 = color.parse(firstToken.values[0]); stops.push({ stop: ZERO_LENGTH, color: color$1 }); } else if (firstToken.name === 'to') { var color$1 = color.parse(firstToken.values[0]); stops.push({ stop: HUNDRED_PERCENT, color: color$1 }); } else if (firstToken.name === 'color-stop') { var values = firstToken.values.filter(nonFunctionArgSeparator); if (values.length === 2) { var color$1 = color.parse(values[1]); var stop_1 = values[0]; if (isNumberToken(stop_1)) { stops.push({ stop: { type: TokenType.PERCENTAGE_TOKEN, number: stop_1.number * 100, flags: stop_1.flags }, color: color$1 }); } } } } }); return type === CSSImageType.LINEAR_GRADIENT ? { angle: (angle + deg(180)) % deg(360), stops: stops, type: type } : { size: size, shape: shape, stops: stops, position: position, type: type }; }; var CLOSEST_SIDE = 'closest-side'; var FARTHEST_SIDE = 'farthest-side'; var CLOSEST_CORNER = 'closest-corner'; var FARTHEST_CORNER = 'farthest-corner'; var CIRCLE = 'circle'; var ELLIPSE = 'ellipse'; var COVER = 'cover'; var CONTAIN = 'contain'; var radialGradient = function radialGradient(tokens) { var shape = CSSRadialShape.CIRCLE; var size = CSSRadialExtent.FARTHEST_CORNER; var stops = []; var position = []; parseFunctionArgs(tokens).forEach(function (arg, i) { var isColorStop = true; if (i === 0) { var isAtPosition_1 = false; isColorStop = arg.reduce(function (acc, token) { if (isAtPosition_1) { if (isIdentToken(token)) { switch (token.value) { case 'center': position.push(FIFTY_PERCENT); return acc; case 'top': case 'left': position.push(ZERO_LENGTH); return acc; case 'right': case 'bottom': position.push(HUNDRED_PERCENT); return acc; } } else if (isLengthPercentage(token) || isLength(token)) { position.push(token); } } else if (isIdentToken(token)) { switch (token.value) { case CIRCLE: shape = CSSRadialShape.CIRCLE; return false; case ELLIPSE: shape = CSSRadialShape.ELLIPSE; return false; case 'at': isAtPosition_1 = true; return false; case CLOSEST_SIDE: size = CSSRadialExtent.CLOSEST_SIDE; return false; case COVER: case FARTHEST_SIDE: size = CSSRadialExtent.FARTHEST_SIDE; return false; case CONTAIN: case CLOSEST_CORNER: size = CSSRadialExtent.CLOSEST_CORNER; return false; case FARTHEST_CORNER: size = CSSRadialExtent.FARTHEST_CORNER; return false; } } else if (isLength(token) || isLengthPercentage(token)) { if (!Array.isArray(size)) { size = []; } size.push(token); return false; } return acc; }, isColorStop); } if (isColorStop) { var colorStop = parseColorStop(arg); stops.push(colorStop); } }); return { size: size, shape: shape, stops: stops, position: position, type: CSSImageType.RADIAL_GRADIENT }; }; var prefixRadialGradient = function prefixRadialGradient(tokens) { var shape = CSSRadialShape.CIRCLE; var size = CSSRadialExtent.FARTHEST_CORNER; var stops = []; var position = []; parseFunctionArgs(tokens).forEach(function (arg, i) { var isColorStop = true; if (i === 0) { isColorStop = arg.reduce(function (acc, token) { if (isIdentToken(token)) { switch (token.value) { case 'center': position.push(FIFTY_PERCENT); return false; case 'top': case 'left': position.push(ZERO_LENGTH); return false; case 'right': case 'bottom': position.push(HUNDRED_PERCENT); return false; } } else if (isLengthPercentage(token) || isLength(token)) { position.push(token); return false; } return acc; }, isColorStop); } else if (i === 1) { isColorStop = arg.reduce(function (acc, token) { if (isIdentToken(token)) { switch (token.value) { case CIRCLE: shape = CSSRadialShape.CIRCLE; return false; case ELLIPSE: shape = CSSRadialShape.ELLIPSE; return false; case CONTAIN: case CLOSEST_SIDE: size = CSSRadialExtent.CLOSEST_SIDE; return false; case FARTHEST_SIDE: size = CSSRadialExtent.FARTHEST_SIDE; return false; case CLOSEST_CORNER: size = CSSRadialExtent.CLOSEST_CORNER; return false; case COVER: case FARTHEST_CORNER: size = CSSRadialExtent.FARTHEST_CORNER; return false; } } else if (isLength(token) || isLengthPercentage(token)) { if (!Array.isArray(size)) { size = []; } size.push(token); return false; } return acc; }, isColorStop); } if (isColorStop) { var colorStop = parseColorStop(arg); stops.push(colorStop); } }); return { size: size, shape: shape, stops: stops, position: position, type: CSSImageType.RADIAL_GRADIENT }; }; var CSSImageType; (function (CSSImageType) { CSSImageType[CSSImageType["URL"] = 0] = "URL"; CSSImageType[CSSImageType["LINEAR_GRADIENT"] = 1] = "LINEAR_GRADIENT"; CSSImageType[CSSImageType["RADIAL_GRADIENT"] = 2] = "RADIAL_GRADIENT"; })(CSSImageType || (CSSImageType = {})); var isLinearGradient = function isLinearGradient(background) { return background.type === CSSImageType.LINEAR_GRADIENT; }; var isRadialGradient = function isRadialGradient(background) { return background.type === CSSImageType.RADIAL_GRADIENT; }; var CSSRadialShape; (function (CSSRadialShape) { CSSRadialShape[CSSRadialShape["CIRCLE"] = 0] = "CIRCLE"; CSSRadialShape[CSSRadialShape["ELLIPSE"] = 1] = "ELLIPSE"; })(CSSRadialShape || (CSSRadialShape = {})); var CSSRadialExtent; (function (CSSRadialExtent) { CSSRadialExtent[CSSRadialExtent["CLOSEST_SIDE"] = 0] = "CLOSEST_SIDE"; CSSRadialExtent[CSSRadialExtent["FARTHEST_SIDE"] = 1] = "FARTHEST_SIDE"; CSSRadialExtent[CSSRadialExtent["CLOSEST_CORNER"] = 2] = "CLOSEST_CORNER"; CSSRadialExtent[CSSRadialExtent["FARTHEST_CORNER"] = 3] = "FARTHEST_CORNER"; })(CSSRadialExtent || (CSSRadialExtent = {})); var image = { name: 'image', parse: function parse(value) { if (value.type === TokenType.URL_TOKEN) { var image_1 = { url: value.value, type: CSSImageType.URL }; CacheStorage.getInstance().addImage(value.value); return image_1; } if (value.type === TokenType.FUNCTION) { var imageFunction = SUPPORTED_IMAGE_FUNCTIONS[value.name]; if (typeof imageFunction === 'undefined') { throw new Error("Attempting to parse an unsupported image function \"" + value.name + "\""); } return imageFunction(value.values); } throw new Error("Unsupported image type"); } }; function isSupportedImage(value) { return value.type !== TokenType.FUNCTION || SUPPORTED_IMAGE_FUNCTIONS[value.name]; } var SUPPORTED_IMAGE_FUNCTIONS = { 'linear-gradient': linearGradient, '-moz-linear-gradient': prefixLinearGradient, '-ms-linear-gradient': prefixLinearGradient, '-o-linear-gradient': prefixLinearGradient, '-webkit-linear-gradient': prefixLinearGradient, 'radial-gradient': radialGradient, '-moz-radial-gradient': prefixRadialGradient, '-ms-radial-gradient': prefixRadialGradient, '-o-radial-gradient': prefixRadialGradient, '-webkit-radial-gradient': prefixRadialGradient, '-webkit-gradient': webkitGradient }; var backgroundImage = { name: 'background-image', initialValue: 'none', type: PropertyDescriptorParsingType.LIST, prefix: false, parse: function parse(tokens) { if (tokens.length === 0) { return []; } var first = tokens[0]; if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') { return []; } return tokens.filter(function (value) { return nonFunctionArgSeparator(value) && isSupportedImage(value); }).map(image.parse); } }; var backgroundOrigin = { name: 'background-origin', initialValue: 'border-box', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return tokens.map(function (token) { if (isIdentToken(token)) { switch (token.value) { case 'padding-box': return 1 /* PADDING_BOX */ ; case 'content-box': return 2 /* CONTENT_BOX */ ; } } return 0 /* BORDER_BOX */ ; }); } }; var backgroundPosition = { name: 'background-position', initialValue: '0% 0%', type: PropertyDescriptorParsingType.LIST, prefix: false, parse: function parse(tokens) { return parseFunctionArgs(tokens).map(function (values) { return values.filter(isLengthPercentage); }).map(parseLengthPercentageTuple); } }; var BACKGROUND_REPEAT; (function (BACKGROUND_REPEAT) { BACKGROUND_REPEAT[BACKGROUND_REPEAT["REPEAT"] = 0] = "REPEAT"; BACKGROUND_REPEAT[BACKGROUND_REPEAT["NO_REPEAT"] = 1] = "NO_REPEAT"; BACKGROUND_REPEAT[BACKGROUND_REPEAT["REPEAT_X"] = 2] = "REPEAT_X"; BACKGROUND_REPEAT[BACKGROUND_REPEAT["REPEAT_Y"] = 3] = "REPEAT_Y"; })(BACKGROUND_REPEAT || (BACKGROUND_REPEAT = {})); var backgroundRepeat = { name: 'background-repeat', initialValue: 'repeat', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return parseFunctionArgs(tokens).map(function (values) { return values.filter(isIdentToken).map(function (token) { return token.value; }).join(' '); }).map(parseBackgroundRepeat); } }; var parseBackgroundRepeat = function parseBackgroundRepeat(value) { switch (value) { case 'no-repeat': return BACKGROUND_REPEAT.NO_REPEAT; case 'repeat-x': case 'repeat no-repeat': return BACKGROUND_REPEAT.REPEAT_X; case 'repeat-y': case 'no-repeat repeat': return BACKGROUND_REPEAT.REPEAT_Y; case 'repeat': default: return BACKGROUND_REPEAT.REPEAT; } }; var BACKGROUND_SIZE; (function (BACKGROUND_SIZE) { BACKGROUND_SIZE["AUTO"] = "auto"; BACKGROUND_SIZE["CONTAIN"] = "contain"; BACKGROUND_SIZE["COVER"] = "cover"; })(BACKGROUND_SIZE || (BACKGROUND_SIZE = {})); var backgroundSize = { name: 'background-size', initialValue: '0', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return parseFunctionArgs(tokens).map(function (values) { return values.filter(isBackgroundSizeInfoToken); }); } }; var isBackgroundSizeInfoToken = function isBackgroundSizeInfoToken(value) { return isIdentToken(value) || isLengthPercentage(value); }; var borderColorForSide = function borderColorForSide(side) { return { name: "border-" + side + "-color", initialValue: 'transparent', prefix: false, type: PropertyDescriptorParsingType.TYPE_VALUE, format: 'color' }; }; var borderTopColor = borderColorForSide('top'); var borderRightColor = borderColorForSide('right'); var borderBottomColor = borderColorForSide('bottom'); var borderLeftColor = borderColorForSide('left'); var borderRadiusForSide = function borderRadiusForSide(side) { return { name: "border-radius-" + side, initialValue: '0 0', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return parseLengthPercentageTuple(tokens.filter(isLengthPercentage)); } }; }; var borderTopLeftRadius = borderRadiusForSide('top-left'); var borderTopRightRadius = borderRadiusForSide('top-right'); var borderBottomRightRadius = borderRadiusForSide('bottom-right'); var borderBottomLeftRadius = borderRadiusForSide('bottom-left'); var BORDER_STYLE; (function (BORDER_STYLE) { BORDER_STYLE[BORDER_STYLE["NONE"] = 0] = "NONE"; BORDER_STYLE[BORDER_STYLE["SOLID"] = 1] = "SOLID"; })(BORDER_STYLE || (BORDER_STYLE = {})); var borderStyleForSide = function borderStyleForSide(side) { return { name: "border-" + side + "-style", initialValue: 'solid', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(style) { switch (style) { case 'none': return BORDER_STYLE.NONE; } return BORDER_STYLE.SOLID; } }; }; var borderTopStyle = borderStyleForSide('top'); var borderRightStyle = borderStyleForSide('right'); var borderBottomStyle = borderStyleForSide('bottom'); var borderLeftStyle = borderStyleForSide('left'); var borderWidthForSide = function borderWidthForSide(side) { return { name: "border-" + side + "-width", initialValue: '0', type: PropertyDescriptorParsingType.VALUE, prefix: false, parse: function parse(token) { if (isDimensionToken(token)) { return token.number; } return 0; } }; }; var borderTopWidth = borderWidthForSide('top'); var borderRightWidth = borderWidthForSide('right'); var borderBottomWidth = borderWidthForSide('bottom'); var borderLeftWidth = borderWidthForSide('left'); var color$1 = { name: "color", initialValue: 'transparent', prefix: false, type: PropertyDescriptorParsingType.TYPE_VALUE, format: 'color' }; var display = { name: 'display', initialValue: 'inline-block', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return tokens.filter(isIdentToken).reduce(function (bit, token) { return bit | parseDisplayValue(token.value); }, 0 /* NONE */ ); } }; var parseDisplayValue = function parseDisplayValue(display) { switch (display) { case 'block': return 2 /* BLOCK */ ; case 'inline': return 4 /* INLINE */ ; case 'run-in': return 8 /* RUN_IN */ ; case 'flow': return 16 /* FLOW */ ; case 'flow-root': return 32 /* FLOW_ROOT */ ; case 'table': return 64 /* TABLE */ ; case 'flex': case '-webkit-flex': return 128 /* FLEX */ ; case 'grid': case '-ms-grid': return 256 /* GRID */ ; case 'ruby': return 512 /* RUBY */ ; case 'subgrid': return 1024 /* SUBGRID */ ; case 'list-item': return 2048 /* LIST_ITEM */ ; case 'table-row-group': return 4096 /* TABLE_ROW_GROUP */ ; case 'table-header-group': return 8192 /* TABLE_HEADER_GROUP */ ; case 'table-footer-group': return 16384 /* TABLE_FOOTER_GROUP */ ; case 'table-row': return 32768 /* TABLE_ROW */ ; case 'table-cell': return 65536 /* TABLE_CELL */ ; case 'table-column-group': return 131072 /* TABLE_COLUMN_GROUP */ ; case 'table-column': return 262144 /* TABLE_COLUMN */ ; case 'table-caption': return 524288 /* TABLE_CAPTION */ ; case 'ruby-base': return 1048576 /* RUBY_BASE */ ; case 'ruby-text': return 2097152 /* RUBY_TEXT */ ; case 'ruby-base-container': return 4194304 /* RUBY_BASE_CONTAINER */ ; case 'ruby-text-container': return 8388608 /* RUBY_TEXT_CONTAINER */ ; case 'contents': return 16777216 /* CONTENTS */ ; case 'inline-block': return 33554432 /* INLINE_BLOCK */ ; case 'inline-list-item': return 67108864 /* INLINE_LIST_ITEM */ ; case 'inline-table': return 134217728 /* INLINE_TABLE */ ; case 'inline-flex': return 268435456 /* INLINE_FLEX */ ; case 'inline-grid': return 536870912 /* INLINE_GRID */ ; } return 0 /* NONE */ ; }; var FLOAT; (function (FLOAT) { FLOAT[FLOAT["NONE"] = 0] = "NONE"; FLOAT[FLOAT["LEFT"] = 1] = "LEFT"; FLOAT[FLOAT["RIGHT"] = 2] = "RIGHT"; FLOAT[FLOAT["INLINE_START"] = 3] = "INLINE_START"; FLOAT[FLOAT["INLINE_END"] = 4] = "INLINE_END"; })(FLOAT || (FLOAT = {})); var _float = { name: 'float', initialValue: 'none', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(_float2) { switch (_float2) { case 'left': return FLOAT.LEFT; case 'right': return FLOAT.RIGHT; case 'inline-start': return FLOAT.INLINE_START; case 'inline-end': return FLOAT.INLINE_END; } return FLOAT.NONE; } }; var letterSpacing = { name: 'letter-spacing', initialValue: '0', prefix: false, type: PropertyDescriptorParsingType.VALUE, parse: function parse(token) { if (token.type === TokenType.IDENT_TOKEN && token.value === 'normal') { return 0; } if (token.type === TokenType.NUMBER_TOKEN) { return token.number; } if (token.type === TokenType.DIMENSION_TOKEN) { return token.number; } return 0; } }; var LINE_BREAK; (function (LINE_BREAK) { LINE_BREAK["NORMAL"] = "normal"; LINE_BREAK["STRICT"] = "strict"; })(LINE_BREAK || (LINE_BREAK = {})); var lineBreak = { name: 'line-break', initialValue: 'normal', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(lineBreak) { switch (lineBreak) { case 'strict': return LINE_BREAK.STRICT; case 'normal': default: return LINE_BREAK.NORMAL; } } }; var lineHeight = { name: 'line-height', initialValue: 'normal', prefix: false, type: PropertyDescriptorParsingType.TOKEN_VALUE }; var computeLineHeight = function computeLineHeight(token, fontSize) { if (isIdentToken(token) && token.value === 'normal') { return 1.2 * fontSize; } else if (token.type === TokenType.NUMBER_TOKEN) { return fontSize * token.number; } else if (isLengthPercentage(token)) { return getAbsoluteValue(token, fontSize); } return fontSize; }; var listStyleImage = { name: 'list-style-image', initialValue: 'none', type: PropertyDescriptorParsingType.VALUE, prefix: false, parse: function parse(token) { if (token.type === TokenType.IDENT_TOKEN && token.value === 'none') { return null; } return image.parse(token); } }; var LIST_STYLE_POSITION; (function (LIST_STYLE_POSITION) { LIST_STYLE_POSITION[LIST_STYLE_POSITION["INSIDE"] = 0] = "INSIDE"; LIST_STYLE_POSITION[LIST_STYLE_POSITION["OUTSIDE"] = 1] = "OUTSIDE"; })(LIST_STYLE_POSITION || (LIST_STYLE_POSITION = {})); var listStylePosition = { name: 'list-style-position', initialValue: 'outside', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(position) { switch (position) { case 'inside': return LIST_STYLE_POSITION.INSIDE; case 'outside': default: return LIST_STYLE_POSITION.OUTSIDE; } } }; var LIST_STYLE_TYPE; (function (LIST_STYLE_TYPE) { LIST_STYLE_TYPE[LIST_STYLE_TYPE["NONE"] = -1] = "NONE"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["DISC"] = 0] = "DISC"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["CIRCLE"] = 1] = "CIRCLE"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["SQUARE"] = 2] = "SQUARE"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["DECIMAL"] = 3] = "DECIMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_DECIMAL"] = 4] = "CJK_DECIMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["DECIMAL_LEADING_ZERO"] = 5] = "DECIMAL_LEADING_ZERO"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_ROMAN"] = 6] = "LOWER_ROMAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["UPPER_ROMAN"] = 7] = "UPPER_ROMAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_GREEK"] = 8] = "LOWER_GREEK"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_ALPHA"] = 9] = "LOWER_ALPHA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["UPPER_ALPHA"] = 10] = "UPPER_ALPHA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["ARABIC_INDIC"] = 11] = "ARABIC_INDIC"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["ARMENIAN"] = 12] = "ARMENIAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["BENGALI"] = 13] = "BENGALI"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["CAMBODIAN"] = 14] = "CAMBODIAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_EARTHLY_BRANCH"] = 15] = "CJK_EARTHLY_BRANCH"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_HEAVENLY_STEM"] = 16] = "CJK_HEAVENLY_STEM"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_IDEOGRAPHIC"] = 17] = "CJK_IDEOGRAPHIC"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["DEVANAGARI"] = 18] = "DEVANAGARI"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["ETHIOPIC_NUMERIC"] = 19] = "ETHIOPIC_NUMERIC"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["GEORGIAN"] = 20] = "GEORGIAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["GUJARATI"] = 21] = "GUJARATI"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["GURMUKHI"] = 22] = "GURMUKHI"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["HEBREW"] = 22] = "HEBREW"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["HIRAGANA"] = 23] = "HIRAGANA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["HIRAGANA_IROHA"] = 24] = "HIRAGANA_IROHA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["JAPANESE_FORMAL"] = 25] = "JAPANESE_FORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["JAPANESE_INFORMAL"] = 26] = "JAPANESE_INFORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["KANNADA"] = 27] = "KANNADA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["KATAKANA"] = 28] = "KATAKANA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["KATAKANA_IROHA"] = 29] = "KATAKANA_IROHA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["KHMER"] = 30] = "KHMER"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["KOREAN_HANGUL_FORMAL"] = 31] = "KOREAN_HANGUL_FORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["KOREAN_HANJA_FORMAL"] = 32] = "KOREAN_HANJA_FORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["KOREAN_HANJA_INFORMAL"] = 33] = "KOREAN_HANJA_INFORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["LAO"] = 34] = "LAO"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_ARMENIAN"] = 35] = "LOWER_ARMENIAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["MALAYALAM"] = 36] = "MALAYALAM"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["MONGOLIAN"] = 37] = "MONGOLIAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["MYANMAR"] = 38] = "MYANMAR"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["ORIYA"] = 39] = "ORIYA"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["PERSIAN"] = 40] = "PERSIAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["SIMP_CHINESE_FORMAL"] = 41] = "SIMP_CHINESE_FORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["SIMP_CHINESE_INFORMAL"] = 42] = "SIMP_CHINESE_INFORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["TAMIL"] = 43] = "TAMIL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["TELUGU"] = 44] = "TELUGU"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["THAI"] = 45] = "THAI"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["TIBETAN"] = 46] = "TIBETAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["TRAD_CHINESE_FORMAL"] = 47] = "TRAD_CHINESE_FORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["TRAD_CHINESE_INFORMAL"] = 48] = "TRAD_CHINESE_INFORMAL"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["UPPER_ARMENIAN"] = 49] = "UPPER_ARMENIAN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["DISCLOSURE_OPEN"] = 50] = "DISCLOSURE_OPEN"; LIST_STYLE_TYPE[LIST_STYLE_TYPE["DISCLOSURE_CLOSED"] = 51] = "DISCLOSURE_CLOSED"; })(LIST_STYLE_TYPE || (LIST_STYLE_TYPE = {})); var listStyleType = { name: 'list-style-type', initialValue: 'none', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(type) { switch (type) { case 'disc': return LIST_STYLE_TYPE.DISC; case 'circle': return LIST_STYLE_TYPE.CIRCLE; case 'square': return LIST_STYLE_TYPE.SQUARE; case 'decimal': return LIST_STYLE_TYPE.DECIMAL; case 'cjk-decimal': return LIST_STYLE_TYPE.CJK_DECIMAL; case 'decimal-leading-zero': return LIST_STYLE_TYPE.DECIMAL_LEADING_ZERO; case 'lower-roman': return LIST_STYLE_TYPE.LOWER_ROMAN; case 'upper-roman': return LIST_STYLE_TYPE.UPPER_ROMAN; case 'lower-greek': return LIST_STYLE_TYPE.LOWER_GREEK; case 'lower-alpha': return LIST_STYLE_TYPE.LOWER_ALPHA; case 'upper-alpha': return LIST_STYLE_TYPE.UPPER_ALPHA; case 'arabic-indic': return LIST_STYLE_TYPE.ARABIC_INDIC; case 'armenian': return LIST_STYLE_TYPE.ARMENIAN; case 'bengali': return LIST_STYLE_TYPE.BENGALI; case 'cambodian': return LIST_STYLE_TYPE.CAMBODIAN; case 'cjk-earthly-branch': return LIST_STYLE_TYPE.CJK_EARTHLY_BRANCH; case 'cjk-heavenly-stem': return LIST_STYLE_TYPE.CJK_HEAVENLY_STEM; case 'cjk-ideographic': return LIST_STYLE_TYPE.CJK_IDEOGRAPHIC; case 'devanagari': return LIST_STYLE_TYPE.DEVANAGARI; case 'ethiopic-numeric': return LIST_STYLE_TYPE.ETHIOPIC_NUMERIC; case 'georgian': return LIST_STYLE_TYPE.GEORGIAN; case 'gujarati': return LIST_STYLE_TYPE.GUJARATI; case 'gurmukhi': return LIST_STYLE_TYPE.GURMUKHI; case 'hebrew': return LIST_STYLE_TYPE.HEBREW; case 'hiragana': return LIST_STYLE_TYPE.HIRAGANA; case 'hiragana-iroha': return LIST_STYLE_TYPE.HIRAGANA_IROHA; case 'japanese-formal': return LIST_STYLE_TYPE.JAPANESE_FORMAL; case 'japanese-informal': return LIST_STYLE_TYPE.JAPANESE_INFORMAL; case 'kannada': return LIST_STYLE_TYPE.KANNADA; case 'katakana': return LIST_STYLE_TYPE.KATAKANA; case 'katakana-iroha': return LIST_STYLE_TYPE.KATAKANA_IROHA; case 'khmer': return LIST_STYLE_TYPE.KHMER; case 'korean-hangul-formal': return LIST_STYLE_TYPE.KOREAN_HANGUL_FORMAL; case 'korean-hanja-formal': return LIST_STYLE_TYPE.KOREAN_HANJA_FORMAL; case 'korean-hanja-informal': return LIST_STYLE_TYPE.KOREAN_HANJA_INFORMAL; case 'lao': return LIST_STYLE_TYPE.LAO; case 'lower-armenian': return LIST_STYLE_TYPE.LOWER_ARMENIAN; case 'malayalam': return LIST_STYLE_TYPE.MALAYALAM; case 'mongolian': return LIST_STYLE_TYPE.MONGOLIAN; case 'myanmar': return LIST_STYLE_TYPE.MYANMAR; case 'oriya': return LIST_STYLE_TYPE.ORIYA; case 'persian': return LIST_STYLE_TYPE.PERSIAN; case 'simp-chinese-formal': return LIST_STYLE_TYPE.SIMP_CHINESE_FORMAL; case 'simp-chinese-informal': return LIST_STYLE_TYPE.SIMP_CHINESE_INFORMAL; case 'tamil': return LIST_STYLE_TYPE.TAMIL; case 'telugu': return LIST_STYLE_TYPE.TELUGU; case 'thai': return LIST_STYLE_TYPE.THAI; case 'tibetan': return LIST_STYLE_TYPE.TIBETAN; case 'trad-chinese-formal': return LIST_STYLE_TYPE.TRAD_CHINESE_FORMAL; case 'trad-chinese-informal': return LIST_STYLE_TYPE.TRAD_CHINESE_INFORMAL; case 'upper-armenian': return LIST_STYLE_TYPE.UPPER_ARMENIAN; case 'disclosure-open': return LIST_STYLE_TYPE.DISCLOSURE_OPEN; case 'disclosure-closed': return LIST_STYLE_TYPE.DISCLOSURE_CLOSED; case 'none': default: return LIST_STYLE_TYPE.NONE; } } }; var marginForSide = function marginForSide(side) { return { name: "margin-" + side, initialValue: '0', prefix: false, type: PropertyDescriptorParsingType.TOKEN_VALUE }; }; var marginTop = marginForSide('top'); var marginRight = marginForSide('right'); var marginBottom = marginForSide('bottom'); var marginLeft = marginForSide('left'); var OVERFLOW; (function (OVERFLOW) { OVERFLOW[OVERFLOW["VISIBLE"] = 0] = "VISIBLE"; OVERFLOW[OVERFLOW["HIDDEN"] = 1] = "HIDDEN"; OVERFLOW[OVERFLOW["SCROLL"] = 2] = "SCROLL"; OVERFLOW[OVERFLOW["AUTO"] = 3] = "AUTO"; })(OVERFLOW || (OVERFLOW = {})); var overflow = { name: 'overflow', initialValue: 'visible', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return tokens.filter(isIdentToken).map(function (overflow) { switch (overflow.value) { case 'hidden': return OVERFLOW.HIDDEN; case 'scroll': return OVERFLOW.SCROLL; case 'auto': return OVERFLOW.AUTO; case 'visible': default: return OVERFLOW.VISIBLE; } }); } }; var OVERFLOW_WRAP; (function (OVERFLOW_WRAP) { OVERFLOW_WRAP["NORMAL"] = "normal"; OVERFLOW_WRAP["BREAK_WORD"] = "break-word"; })(OVERFLOW_WRAP || (OVERFLOW_WRAP = {})); var overflowWrap = { name: 'overflow-wrap', initialValue: 'normal', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(overflow) { switch (overflow) { case 'break-word': return OVERFLOW_WRAP.BREAK_WORD; case 'normal': default: return OVERFLOW_WRAP.NORMAL; } } }; var paddingForSide = function paddingForSide(side) { return { name: "padding-" + side, initialValue: '0', prefix: false, type: PropertyDescriptorParsingType.TYPE_VALUE, format: 'length-percentage' }; }; var paddingTop = paddingForSide('top'); var paddingRight = paddingForSide('right'); var paddingBottom = paddingForSide('bottom'); var paddingLeft = paddingForSide('left'); var TEXT_ALIGN; (function (TEXT_ALIGN) { TEXT_ALIGN[TEXT_ALIGN["LEFT"] = 0] = "LEFT"; TEXT_ALIGN[TEXT_ALIGN["CENTER"] = 1] = "CENTER"; TEXT_ALIGN[TEXT_ALIGN["RIGHT"] = 2] = "RIGHT"; })(TEXT_ALIGN || (TEXT_ALIGN = {})); var textAlign = { name: 'text-align', initialValue: 'left', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(textAlign) { switch (textAlign) { case 'right': return TEXT_ALIGN.RIGHT; case 'center': case 'justify': return TEXT_ALIGN.CENTER; case 'left': default: return TEXT_ALIGN.LEFT; } } }; var POSITION; (function (POSITION) { POSITION[POSITION["STATIC"] = 0] = "STATIC"; POSITION[POSITION["RELATIVE"] = 1] = "RELATIVE"; POSITION[POSITION["ABSOLUTE"] = 2] = "ABSOLUTE"; POSITION[POSITION["FIXED"] = 3] = "FIXED"; POSITION[POSITION["STICKY"] = 4] = "STICKY"; })(POSITION || (POSITION = {})); var position = { name: 'position', initialValue: 'static', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(position) { switch (position) { case 'relative': return POSITION.RELATIVE; case 'absolute': return POSITION.ABSOLUTE; case 'fixed': return POSITION.FIXED; case 'sticky': return POSITION.STICKY; } return POSITION.STATIC; } }; var textShadow = { name: 'text-shadow', initialValue: 'none', type: PropertyDescriptorParsingType.LIST, prefix: false, parse: function parse(tokens) { if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) { return []; } return parseFunctionArgs(tokens).map(function (values) { var shadow = { color: COLORS.TRANSPARENT, offsetX: ZERO_LENGTH, offsetY: ZERO_LENGTH, blur: ZERO_LENGTH }; var c = 0; for (var i = 0; i < values.length; i++) { var token = values[i]; if (isLength(token)) { if (c === 0) { shadow.offsetX = token; } else if (c === 1) { shadow.offsetY = token; } else { shadow.blur = token; } c++; } else { shadow.color = color.parse(token); } } return shadow; }); } }; var TEXT_TRANSFORM; (function (TEXT_TRANSFORM) { TEXT_TRANSFORM[TEXT_TRANSFORM["NONE"] = 0] = "NONE"; TEXT_TRANSFORM[TEXT_TRANSFORM["LOWERCASE"] = 1] = "LOWERCASE"; TEXT_TRANSFORM[TEXT_TRANSFORM["UPPERCASE"] = 2] = "UPPERCASE"; TEXT_TRANSFORM[TEXT_TRANSFORM["CAPITALIZE"] = 3] = "CAPITALIZE"; })(TEXT_TRANSFORM || (TEXT_TRANSFORM = {})); var textTransform = { name: 'text-transform', initialValue: 'none', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(textTransform) { switch (textTransform) { case 'uppercase': return TEXT_TRANSFORM.UPPERCASE; case 'lowercase': return TEXT_TRANSFORM.LOWERCASE; case 'capitalize': return TEXT_TRANSFORM.CAPITALIZE; } return TEXT_TRANSFORM.NONE; } }; var transform = { name: 'transform', initialValue: 'none', prefix: true, type: PropertyDescriptorParsingType.VALUE, parse: function parse(token) { if (token.type === TokenType.IDENT_TOKEN && token.value === 'none') { return null; } if (token.type === TokenType.FUNCTION) { var transformFunction = SUPPORTED_TRANSFORM_FUNCTIONS[token.name]; if (typeof transformFunction === 'undefined') { throw new Error("Attempting to parse an unsupported transform function \"" + token.name + "\""); } return transformFunction(token.values); } return null; } }; var matrix = function matrix(args) { var values = args.filter(function (arg) { return arg.type === TokenType.NUMBER_TOKEN; }).map(function (arg) { return arg.number; }); return values.length === 6 ? values : null; }; // doesn't support 3D transforms at the moment var matrix3d = function matrix3d(args) { var values = args.filter(function (arg) { return arg.type === TokenType.NUMBER_TOKEN; }).map(function (arg) { return arg.number; }); var a1 = values[0], b1 = values[1], _a = values[2], _b = values[3], a2 = values[4], b2 = values[5], _c = values[6], _d = values[7], _e = values[8], _f = values[9], _g = values[10], _h = values[11], a4 = values[12], b4 = values[13], _j = values[14], _k = values[15]; return values.length === 16 ? [a1, b1, a2, b2, a4, b4] : null; }; var SUPPORTED_TRANSFORM_FUNCTIONS = { matrix: matrix, matrix3d: matrix3d }; var DEFAULT_VALUE = { type: TokenType.PERCENTAGE_TOKEN, number: 50, flags: FLAG_INTEGER }; var DEFAULT = [DEFAULT_VALUE, DEFAULT_VALUE]; var transformOrigin = { name: 'transform-origin', initialValue: '50% 50%', prefix: true, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { var origins = tokens.filter(isLengthPercentage); if (origins.length !== 2) { return DEFAULT; } return [origins[0], origins[1]]; } }; var VISIBILITY; (function (VISIBILITY) { VISIBILITY[VISIBILITY["VISIBLE"] = 0] = "VISIBLE"; VISIBILITY[VISIBILITY["HIDDEN"] = 1] = "HIDDEN"; VISIBILITY[VISIBILITY["COLLAPSE"] = 2] = "COLLAPSE"; })(VISIBILITY || (VISIBILITY = {})); var visibility = { name: 'visible', initialValue: 'none', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(visibility) { switch (visibility) { case 'hidden': return VISIBILITY.HIDDEN; case 'collapse': return VISIBILITY.COLLAPSE; case 'visible': default: return VISIBILITY.VISIBLE; } } }; var WORD_BREAK; (function (WORD_BREAK) { WORD_BREAK["NORMAL"] = "normal"; WORD_BREAK["BREAK_ALL"] = "break-all"; WORD_BREAK["KEEP_ALL"] = "keep-all"; })(WORD_BREAK || (WORD_BREAK = {})); var wordBreak = { name: 'word-break', initialValue: 'normal', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(wordBreak) { switch (wordBreak) { case 'break-all': return WORD_BREAK.BREAK_ALL; case 'keep-all': return WORD_BREAK.KEEP_ALL; case 'normal': default: return WORD_BREAK.NORMAL; } } }; var zIndex = { name: 'z-index', initialValue: 'auto', prefix: false, type: PropertyDescriptorParsingType.VALUE, parse: function parse(token) { if (token.type === TokenType.IDENT_TOKEN) { return { auto: true, order: 0 }; } if (isNumberToken(token)) { return { auto: false, order: token.number }; } throw new Error("Invalid z-index number parsed"); } }; var opacity = { name: 'opacity', initialValue: '1', type: PropertyDescriptorParsingType.VALUE, prefix: false, parse: function parse(token) { if (isNumberToken(token)) { return token.number; } return 1; } }; var textDecorationColor = { name: "text-decoration-color", initialValue: 'transparent', prefix: false, type: PropertyDescriptorParsingType.TYPE_VALUE, format: 'color' }; var textDecorationLine = { name: 'text-decoration-line', initialValue: 'none', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { return tokens.filter(isIdentToken).map(function (token) { switch (token.value) { case 'underline': return 1 /* UNDERLINE */ ; case 'overline': return 2 /* OVERLINE */ ; case 'line-through': return 3 /* LINE_THROUGH */ ; case 'none': return 4 /* BLINK */ ; } return 0 /* NONE */ ; }).filter(function (line) { return line !== 0 /* NONE */ ; }); } }; var fontFamily = { name: "font-family", initialValue: '', prefix: false, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { var accumulator = []; var results = []; tokens.forEach(function (token) { switch (token.type) { case TokenType.IDENT_TOKEN: case TokenType.STRING_TOKEN: accumulator.push(token.value); break; case TokenType.NUMBER_TOKEN: accumulator.push(token.number.toString()); break; case TokenType.COMMA_TOKEN: results.push(accumulator.join(' ')); accumulator.length = 0; break; } }); if (accumulator.length) { results.push(accumulator.join(' ')); } return results.map(function (result) { return result.indexOf(' ') === -1 ? result : "'" + result + "'"; }); } }; var fontSize = { name: "font-size", initialValue: '0', prefix: false, type: PropertyDescriptorParsingType.TYPE_VALUE, format: 'length' }; var fontWeight = { name: 'font-weight', initialValue: 'normal', type: PropertyDescriptorParsingType.VALUE, prefix: false, parse: function parse(token) { if (isNumberToken(token)) { return token.number; } if (isIdentToken(token)) { switch (token.value) { case 'bold': return 700; case 'normal': default: return 400; } } return 400; } }; var fontVariant = { name: 'font-variant', initialValue: 'none', type: PropertyDescriptorParsingType.LIST, prefix: false, parse: function parse(tokens) { return tokens.filter(isIdentToken).map(function (token) { return token.value; }); } }; var FONT_STYLE; (function (FONT_STYLE) { FONT_STYLE["NORMAL"] = "normal"; FONT_STYLE["ITALIC"] = "italic"; FONT_STYLE["OBLIQUE"] = "oblique"; })(FONT_STYLE || (FONT_STYLE = {})); var fontStyle = { name: 'font-style', initialValue: 'normal', prefix: false, type: PropertyDescriptorParsingType.IDENT_VALUE, parse: function parse(overflow) { switch (overflow) { case 'oblique': return FONT_STYLE.OBLIQUE; case 'italic': return FONT_STYLE.ITALIC; case 'normal': default: return FONT_STYLE.NORMAL; } } }; var contains = function contains(bit, value) { return (bit & value) !== 0; }; var content = { name: 'content', initialValue: 'none', type: PropertyDescriptorParsingType.LIST, prefix: false, parse: function parse(tokens) { if (tokens.length === 0) { return []; } var first = tokens[0]; if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') { return []; } return tokens; } }; var counterIncrement = { name: 'counter-increment', initialValue: 'none', prefix: true, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { if (tokens.length === 0) { return null; } var first = tokens[0]; if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') { return null; } var increments = []; var filtered = tokens.filter(nonWhiteSpace); for (var i = 0; i < filtered.length; i++) { var counter = filtered[i]; var next = filtered[i + 1]; if (counter.type === TokenType.IDENT_TOKEN) { var increment = next && isNumberToken(next) ? next.number : 1; increments.push({ counter: counter.value, increment: increment }); } } return increments; } }; var counterReset = { name: 'counter-reset', initialValue: 'none', prefix: true, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { if (tokens.length === 0) { return []; } var resets = []; var filtered = tokens.filter(nonWhiteSpace); for (var i = 0; i < filtered.length; i++) { var counter = filtered[i]; var next = filtered[i + 1]; if (isIdentToken(counter) && counter.value !== 'none') { var reset = next && isNumberToken(next) ? next.number : 0; resets.push({ counter: counter.value, reset: reset }); } } return resets; } }; var quotes = { name: 'quotes', initialValue: 'none', prefix: true, type: PropertyDescriptorParsingType.LIST, parse: function parse(tokens) { if (tokens.length === 0) { return null; } var first = tokens[0]; if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') { return null; } var quotes = []; var filtered = tokens.filter(isStringToken); if (filtered.length % 2 !== 0) { return null; } for (var i = 0; i < filtered.length; i += 2) { var open_1 = filtered[i].value; var close_1 = filtered[i + 1].value; quotes.push({ open: open_1, close: close_1 }); } return quotes; } }; var getQuote = function getQuote(quotes, depth, open) { if (!quotes) { return ''; } var quote = quotes[Math.min(depth, quotes.length - 1)]; if (!quote) { return ''; } return open ? quote.open : quote.close; }; var boxShadow = { name: 'box-shadow', initialValue: 'none', type: PropertyDescriptorParsingType.LIST, prefix: false, parse: function parse(tokens) { if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) { return []; } return parseFunctionArgs(tokens).map(function (values) { var shadow = { color: 0x000000ff, offsetX: ZERO_LENGTH, offsetY: ZERO_LENGTH, blur: ZERO_LENGTH, spread: ZERO_LENGTH, inset: false }; var c = 0; for (var i = 0; i < values.length; i++) { var token = values[i]; if (isIdentWithValue(token, 'inset')) { shadow.inset = true; } else if (isLength(token)) { if (c === 0) { shadow.offsetX = token; } else if (c === 1) { shadow.offsetY = token; } else if (c === 2) { shadow.blur = token; } else { shadow.spread = token; } c++; } else { shadow.color = color.parse(token); } } return shadow; }); } }; var CSSParsedDeclaration = /** @class */ function () { function CSSParsedDeclaration(declaration) { this.backgroundClip = parse(backgroundClip, declaration.backgroundClip); this.backgroundColor = parse(backgroundColor, declaration.backgroundColor); this.backgroundImage = parse(backgroundImage, declaration.backgroundImage); this.backgroundOrigin = parse(backgroundOrigin, declaration.backgroundOrigin); this.backgroundPosition = parse(backgroundPosition, declaration.backgroundPosition); this.backgroundRepeat = parse(backgroundRepeat, declaration.backgroundRepeat); this.backgroundSize = parse(backgroundSize, declaration.backgroundSize); this.borderTopColor = parse(borderTopColor, declaration.borderTopColor); this.borderRightColor = parse(borderRightColor, declaration.borderRightColor); this.borderBottomColor = parse(borderBottomColor, declaration.borderBottomColor); this.borderLeftColor = parse(borderLeftColor, declaration.borderLeftColor); this.borderTopLeftRadius = parse(borderTopLeftRadius, declaration.borderTopLeftRadius); this.borderTopRightRadius = parse(borderTopRightRadius, declaration.borderTopRightRadius); this.borderBottomRightRadius = parse(borderBottomRightRadius, declaration.borderBottomRightRadius); this.borderBottomLeftRadius = parse(borderBottomLeftRadius, declaration.borderBottomLeftRadius); this.borderTopStyle = parse(borderTopStyle, declaration.borderTopStyle); this.borderRightStyle = parse(borderRightStyle, declaration.borderRightStyle); this.borderBottomStyle = parse(borderBottomStyle, declaration.borderBottomStyle); this.borderLeftStyle = parse(borderLeftStyle, declaration.borderLeftStyle); this.borderTopWidth = parse(borderTopWidth, declaration.borderTopWidth); this.borderRightWidth = parse(borderRightWidth, declaration.borderRightWidth); this.borderBottomWidth = parse(borderBottomWidth, declaration.borderBottomWidth); this.borderLeftWidth = parse(borderLeftWidth, declaration.borderLeftWidth); this.boxShadow = parse(boxShadow, declaration.boxShadow); this.color = parse(color$1, declaration.color); this.display = parse(display, declaration.display); this["float"] = parse(_float, declaration.cssFloat); this.fontFamily = parse(fontFamily, declaration.fontFamily); this.fontSize = parse(fontSize, declaration.fontSize); this.fontStyle = parse(fontStyle, declaration.fontStyle); this.fontVariant = parse(fontVariant, declaration.fontVariant); this.fontWeight = parse(fontWeight, declaration.fontWeight); this.letterSpacing = parse(letterSpacing, declaration.letterSpacing); this.lineBreak = parse(lineBreak, declaration.lineBreak); this.lineHeight = parse(lineHeight, declaration.lineHeight); this.listStyleImage = parse(listStyleImage, declaration.listStyleImage); this.listStylePosition = parse(listStylePosition, declaration.listStylePosition); this.listStyleType = parse(listStyleType, declaration.listStyleType); this.marginTop = parse(marginTop, declaration.marginTop); this.marginRight = parse(marginRight, declaration.marginRight); this.marginBottom = parse(marginBottom, declaration.marginBottom); this.marginLeft = parse(marginLeft, declaration.marginLeft); this.opacity = parse(opacity, declaration.opacity); var overflowTuple = parse(overflow, declaration.overflow); this.overflowX = overflowTuple[0]; this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0]; this.overflowWrap = parse(overflowWrap, declaration.overflowWrap); this.paddingTop = parse(paddingTop, declaration.paddingTop); this.paddingRight = parse(paddingRight, declaration.paddingRight); this.paddingBottom = parse(paddingBottom, declaration.paddingBottom); this.paddingLeft = parse(paddingLeft, declaration.paddingLeft); this.position = parse(position, declaration.position); this.textAlign = parse(textAlign, declaration.textAlign); this.textDecorationColor = parse(textDecorationColor, declaration.textDecorationColor || declaration.color); this.textDecorationLine = parse(textDecorationLine, declaration.textDecorationLine); this.textShadow = parse(textShadow, declaration.textShadow); this.textTransform = parse(textTransform, declaration.textTransform); this.transform = parse(transform, declaration.transform); this.transformOrigin = parse(transformOrigin, declaration.transformOrigin); this.visibility = parse(visibility, declaration.visibility); this.wordBreak = parse(wordBreak, declaration.wordBreak); this.zIndex = parse(zIndex, declaration.zIndex); } CSSParsedDeclaration.prototype.isVisible = function () { return this.display > 0 && this.opacity > 0 && this.visibility === VISIBILITY.VISIBLE; }; CSSParsedDeclaration.prototype.isTransparent = function () { return isTransparent(this.backgroundColor); }; CSSParsedDeclaration.prototype.isTransformed = function () { return this.transform !== null; }; CSSParsedDeclaration.prototype.isPositioned = function () { return this.position !== POSITION.STATIC; }; CSSParsedDeclaration.prototype.isPositionedWithZIndex = function () { return this.isPositioned() && !this.zIndex.auto; }; CSSParsedDeclaration.prototype.isFloating = function () { return this["float"] !== FLOAT.NONE; }; CSSParsedDeclaration.prototype.isInlineLevel = function () { return contains(this.display, 4 /* INLINE */ ) || contains(this.display, 33554432 /* INLINE_BLOCK */ ) || contains(this.display, 268435456 /* INLINE_FLEX */ ) || contains(this.display, 536870912 /* INLINE_GRID */ ) || contains(this.display, 67108864 /* INLINE_LIST_ITEM */ ) || contains(this.display, 134217728 /* INLINE_TABLE */ ); }; return CSSParsedDeclaration; }(); var CSSParsedPseudoDeclaration = /** @class */ function () { function CSSParsedPseudoDeclaration(declaration) { this.content = parse(content, declaration.content); this.quotes = parse(quotes, declaration.quotes); } return CSSParsedPseudoDeclaration; }(); var CSSParsedCounterDeclaration = /** @class */ function () { function CSSParsedCounterDeclaration(declaration) { this.counterIncrement = parse(counterIncrement, declaration.counterIncrement); this.counterReset = parse(counterReset, declaration.counterReset); } return CSSParsedCounterDeclaration; }(); // eslint-disable-next-line @typescript-eslint/no-explicit-any var parse = function parse(descriptor, style) { var tokenizer = new Tokenizer(); var value = style !== null && typeof style !== 'undefined' ? style.toString() : descriptor.initialValue; tokenizer.write(value); var parser = new Parser(tokenizer.read()); switch (descriptor.type) { case PropertyDescriptorParsingType.IDENT_VALUE: var token = parser.parseComponentValue(); return descriptor.parse(isIdentToken(token) ? token.value : descriptor.initialValue); case PropertyDescriptorParsingType.VALUE: return descriptor.parse(parser.parseComponentValue()); case PropertyDescriptorParsingType.LIST: return descriptor.parse(parser.parseComponentValues()); case PropertyDescriptorParsingType.TOKEN_VALUE: return parser.parseComponentValue(); case PropertyDescriptorParsingType.TYPE_VALUE: switch (descriptor.format) { case 'angle': return angle.parse(parser.parseComponentValue()); case 'color': return color.parse(parser.parseComponentValue()); case 'image': return image.parse(parser.parseComponentValue()); case 'length': var length_1 = parser.parseComponentValue(); return isLength(length_1) ? length_1 : ZERO_LENGTH; case 'length-percentage': var value_1 = parser.parseComponentValue(); return isLengthPercentage(value_1) ? value_1 : ZERO_LENGTH; } } throw new Error("Attempting to parse unsupported css format type " + descriptor.format); }; var ElementContainer = /** @class */ function () { function ElementContainer(element) { this.styles = new CSSParsedDeclaration(window.getComputedStyle(element, null)); this.textNodes = []; this.elements = []; if (this.styles.transform !== null && isHTMLElementNode(element)) { // getBoundingClientRect takes transforms into account element.style.transform = 'none'; } this.bounds = parseBounds(element); this.flags = 0; } return ElementContainer; }(); var TextBounds = /** @class */ function () { function TextBounds(text, bounds) { this.text = text; this.bounds = bounds; } return TextBounds; }(); var parseTextBounds = function parseTextBounds(value, styles, node) { var textList = breakText(value, styles); var textBounds = []; var offset = 0; textList.forEach(function (text) { if (styles.textDecorationLine.length || text.trim().length > 0) { if (FEATURES.SUPPORT_RANGE_BOUNDS) { textBounds.push(new TextBounds(text, getRangeBounds(node, offset, text.length))); } else { var replacementNode = node.splitText(text.length); textBounds.push(new TextBounds(text, getWrapperBounds(node))); node = replacementNode; } } else if (!FEATURES.SUPPORT_RANGE_BOUNDS) { node = node.splitText(text.length); } offset += text.length; }); return textBounds; }; var getWrapperBounds = function getWrapperBounds(node) { var ownerDocument = node.ownerDocument; if (ownerDocument) { var wrapper = ownerDocument.createElement('html2canvaswrapper'); wrapper.appendChild(node.cloneNode(true)); var parentNode = node.parentNode; if (parentNode) { parentNode.replaceChild(wrapper, node); var bounds = parseBounds(wrapper); if (wrapper.firstChild) { parentNode.replaceChild(wrapper.firstChild, wrapper); } return bounds; } } return new Bounds(0, 0, 0, 0); }; var getRangeBounds = function getRangeBounds(node, offset, length) { var ownerDocument = node.ownerDocument; if (!ownerDocument) { throw new Error('Node has no owner document'); } var range = ownerDocument.createRange(); range.setStart(node, offset); range.setEnd(node, offset + length); return Bounds.fromClientRect(range.getBoundingClientRect()); }; var breakText = function breakText(value, styles) { return styles.letterSpacing !== 0 ? toCodePoints(value).map(function (i) { return fromCodePoint(i); }) : breakWords(value, styles); }; var breakWords = function breakWords(str, styles) { var breaker = LineBreaker(str, { lineBreak: styles.lineBreak, wordBreak: styles.overflowWrap === OVERFLOW_WRAP.BREAK_WORD ? 'break-word' : styles.wordBreak }); var words = []; var bk; while (!(bk = breaker.next()).done) { if (bk.value) { words.push(bk.value.slice()); } } return words; }; var TextContainer = /** @class */ function () { function TextContainer(node, styles) { this.text = transform$1(node.data, styles.textTransform); this.textBounds = parseTextBounds(this.text, styles, node); } return TextContainer; }(); var transform$1 = function transform$1(text, transform) { switch (transform) { case TEXT_TRANSFORM.LOWERCASE: return text.toLowerCase(); case TEXT_TRANSFORM.CAPITALIZE: return text.replace(CAPITALIZE, capitalize); case TEXT_TRANSFORM.UPPERCASE: return text.toUpperCase(); default: return text; } }; var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g; var capitalize = function capitalize(m, p1, p2) { if (m.length > 0) { return p1 + p2.toUpperCase(); } return m; }; var ImageElementContainer = /** @class */ function (_super) { __extends(ImageElementContainer, _super); function ImageElementContainer(img) { var _this = _super.call(this, img) || this; _this.src = img.currentSrc || img.src; _this.intrinsicWidth = img.naturalWidth; _this.intrinsicHeight = img.naturalHeight; CacheStorage.getInstance().addImage(_this.src); return _this; } return ImageElementContainer; }(ElementContainer); var CanvasElementContainer = /** @class */ function (_super) { __extends(CanvasElementContainer, _super); function CanvasElementContainer(canvas) { var _this = _super.call(this, canvas) || this; _this.canvas = canvas; _this.intrinsicWidth = canvas.width; _this.intrinsicHeight = canvas.height; return _this; } return CanvasElementContainer; }(ElementContainer); var SVGElementContainer = /** @class */ function (_super) { __extends(SVGElementContainer, _super); function SVGElementContainer(img) { var _this = _super.call(this, img) || this; var s = new XMLSerializer(); _this.svg = "data:image/svg+xml," + encodeURIComponent(s.serializeToString(img)); _this.intrinsicWidth = img.width.baseVal.value; _this.intrinsicHeight = img.height.baseVal.value; CacheStorage.getInstance().addImage(_this.svg); return _this; } return SVGElementContainer; }(ElementContainer); var LIElementContainer = /** @class */ function (_super) { __extends(LIElementContainer, _super); function LIElementContainer(element) { var _this = _super.call(this, element) || this; _this.value = element.value; return _this; } return LIElementContainer; }(ElementContainer); var OLElementContainer = /** @class */ function (_super) { __extends(OLElementContainer, _super); function OLElementContainer(element) { var _this = _super.call(this, element) || this; _this.start = element.start; _this.reversed = typeof element.reversed === 'boolean' && element.reversed === true; return _this; } return OLElementContainer; }(ElementContainer); var CHECKBOX_BORDER_RADIUS = [{ type: TokenType.DIMENSION_TOKEN, flags: 0, unit: 'px', number: 3 }]; var RADIO_BORDER_RADIUS = [{ type: TokenType.PERCENTAGE_TOKEN, flags: 0, number: 50 }]; var reformatInputBounds = function reformatInputBounds(bounds) { if (bounds.width > bounds.height) { return new Bounds(bounds.left + (bounds.width - bounds.height) / 2, bounds.top, bounds.height, bounds.height); } else if (bounds.width < bounds.height) { return new Bounds(bounds.left, bounds.top + (bounds.height - bounds.width) / 2, bounds.width, bounds.width); } return bounds; }; var getInputValue = function getInputValue(node) { var value = node.type === PASSWORD ? new Array(node.value.length + 1).join("\u2022") : node.value; return value.length === 0 ? node.placeholder || '' : value; }; var CHECKBOX = 'checkbox'; var RADIO = 'radio'; var PASSWORD = 'password'; var INPUT_COLOR = 0x2a2a2aff; var InputElementContainer = /** @class */ function (_super) { __extends(InputElementContainer, _super); function InputElementContainer(input) { var _this = _super.call(this, input) || this; _this.type = input.type.toLowerCase(); _this.checked = input.checked; _this.value = getInputValue(input); if (_this.type === CHECKBOX || _this.type === RADIO) { _this.styles.backgroundColor = 0xdededeff; _this.styles.borderTopColor = _this.styles.borderRightColor = _this.styles.borderBottomColor = _this.styles.borderLeftColor = 0xa5a5a5ff; _this.styles.borderTopWidth = _this.styles.borderRightWidth = _this.styles.borderBottomWidth = _this.styles.borderLeftWidth = 1; _this.styles.borderTopStyle = _this.styles.borderRightStyle = _this.styles.borderBottomStyle = _this.styles.borderLeftStyle = BORDER_STYLE.SOLID; _this.styles.backgroundClip = [BACKGROUND_CLIP.BORDER_BOX]; _this.styles.backgroundOrigin = [0 /* BORDER_BOX */ ]; _this.bounds = reformatInputBounds(_this.bounds); } switch (_this.type) { case CHECKBOX: _this.styles.borderTopRightRadius = _this.styles.borderTopLeftRadius = _this.styles.borderBottomRightRadius = _this.styles.borderBottomLeftRadius = CHECKBOX_BORDER_RADIUS; break; case RADIO: _this.styles.borderTopRightRadius = _this.styles.borderTopLeftRadius = _this.styles.borderBottomRightRadius = _this.styles.borderBottomLeftRadius = RADIO_BORDER_RADIUS; break; } return _this; } return InputElementContainer; }(ElementContainer); var SelectElementContainer = /** @class */ function (_super) { __extends(SelectElementContainer, _super); function SelectElementContainer(element) { var _this = _super.call(this, element) || this; var option = element.options[element.selectedIndex || 0]; _this.value = option ? option.text || '' : ''; return _this; } return SelectElementContainer; }(ElementContainer); var TextareaElementContainer = /** @class */ function (_super) { __extends(TextareaElementContainer, _super); function TextareaElementContainer(element) { var _this = _super.call(this, element) || this; _this.value = element.value; return _this; } return TextareaElementContainer; }(ElementContainer); var parseColor = function parseColor(value) { return color.parse(Parser.create(value).parseComponentValue()); }; var IFrameElementContainer = /** @class */ function (_super) { __extends(IFrameElementContainer, _super); function IFrameElementContainer(iframe) { var _this = _super.call(this, iframe) || this; _this.src = iframe.src; _this.width = parseInt(iframe.width, 10) || 0; _this.height = parseInt(iframe.height, 10) || 0; _this.backgroundColor = _this.styles.backgroundColor; try { if (iframe.contentWindow && iframe.contentWindow.document && iframe.contentWindow.document.documentElement) { _this.tree = parseTree(iframe.contentWindow.document.documentElement); // http://www.w3.org/TR/css3-background/#special-backgrounds var documentBackgroundColor = iframe.contentWindow.document.documentElement ? parseColor(getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor) : COLORS.TRANSPARENT; var bodyBackgroundColor = iframe.contentWindow.document.body ? parseColor(getComputedStyle(iframe.contentWindow.document.body).backgroundColor) : COLORS.TRANSPARENT; _this.backgroundColor = isTransparent(documentBackgroundColor) ? isTransparent(bodyBackgroundColor) ? _this.styles.backgroundColor : bodyBackgroundColor : documentBackgroundColor; } } catch (e) {} return _this; } return IFrameElementContainer; }(ElementContainer); var LIST_OWNERS = ['OL', 'UL', 'MENU']; var parseNodeTree = function parseNodeTree(node, parent, root) { for (var childNode = node.firstChild, nextNode = void 0; childNode; childNode = nextNode) { nextNode = childNode.nextSibling; if (isTextNode(childNode) && childNode.data.trim().length > 0) { parent.textNodes.push(new TextContainer(childNode, parent.styles)); } else if (isElementNode(childNode)) { var container = createContainer(childNode); if (container.styles.isVisible()) { if (createsRealStackingContext(childNode, container, root)) { container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */ ; } else if (createsStackingContext(container.styles)) { container.flags |= 2 /* CREATES_STACKING_CONTEXT */ ; } if (LIST_OWNERS.indexOf(childNode.tagName) !== -1) { container.flags |= 8 /* IS_LIST_OWNER */ ; } parent.elements.push(container); if (!isTextareaElement(childNode) && !isSVGElement(childNode) && !isSelectElement(childNode)) { parseNodeTree(childNode, container, root); } } } } }; var createContainer = function createContainer(element) { if (isImageElement(element)) { return new ImageElementContainer(element); } if (isCanvasElement(element)) { return new CanvasElementContainer(element); } if (isSVGElement(element)) { return new SVGElementContainer(element); } if (isLIElement(element)) { return new LIElementContainer(element); } if (isOLElement(element)) { return new OLElementContainer(element); } if (isInputElement(element)) { return new InputElementContainer(element); } if (isSelectElement(element)) { return new SelectElementContainer(element); } if (isTextareaElement(element)) { return new TextareaElementContainer(element); } if (isIFrameElement(element)) { return new IFrameElementContainer(element); } return new ElementContainer(element); }; var parseTree = function parseTree(element) { var container = createContainer(element); container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */ ; parseNodeTree(element, container, container); return container; }; var createsRealStackingContext = function createsRealStackingContext(node, container, root) { return container.styles.isPositionedWithZIndex() || container.styles.opacity < 1 || container.styles.isTransformed() || isBodyElement(node) && root.styles.isTransparent(); }; var createsStackingContext = function createsStackingContext(styles) { return styles.isPositioned() || styles.isFloating(); }; var isTextNode = function isTextNode(node) { return node.nodeType === Node.TEXT_NODE; }; var isElementNode = function isElementNode(node) { return node.nodeType === Node.ELEMENT_NODE; }; var isHTMLElementNode = function isHTMLElementNode(node) { return isElementNode(node) && typeof node.style !== 'undefined' && !isSVGElementNode(node); }; var isSVGElementNode = function isSVGElementNode(element) { return _typeof(element.className) === 'object'; }; var isLIElement = function isLIElement(node) { return node.tagName === 'LI'; }; var isOLElement = function isOLElement(node) { return node.tagName === 'OL'; }; var isInputElement = function isInputElement(node) { return node.tagName === 'INPUT'; }; var isHTMLElement = function isHTMLElement(node) { return node.tagName === 'HTML'; }; var isSVGElement = function isSVGElement(node) { return node.tagName === 'svg'; }; var isBodyElement = function isBodyElement(node) { return node.tagName === 'BODY'; }; var isCanvasElement = function isCanvasElement(node) { return node.tagName === 'CANVAS'; }; var isImageElement = function isImageElement(node) { return node.tagName === 'IMG'; }; var isIFrameElement = function isIFrameElement(node) { return node.tagName === 'IFRAME'; }; var isStyleElement = function isStyleElement(node) { return node.tagName === 'STYLE'; }; var isScriptElement = function isScriptElement(node) { return node.tagName === 'SCRIPT'; }; var isTextareaElement = function isTextareaElement(node) { return node.tagName === 'TEXTAREA'; }; var isSelectElement = function isSelectElement(node) { return node.tagName === 'SELECT'; }; var CounterState = /** @class */ function () { function CounterState() { this.counters = {}; } CounterState.prototype.getCounterValue = function (name) { var counter = this.counters[name]; if (counter && counter.length) { return counter[counter.length - 1]; } return 1; }; CounterState.prototype.getCounterValues = function (name) { var counter = this.counters[name]; return counter ? counter : []; }; CounterState.prototype.pop = function (counters) { var _this = this; counters.forEach(function (counter) { return _this.counters[counter].pop(); }); }; CounterState.prototype.parse = function (style) { var _this = this; var counterIncrement = style.counterIncrement; var counterReset = style.counterReset; var canReset = true; if (counterIncrement !== null) { counterIncrement.forEach(function (entry) { var counter = _this.counters[entry.counter]; if (counter && entry.increment !== 0) { canReset = false; counter[Math.max(0, counter.length - 1)] += entry.increment; } }); } var counterNames = []; if (canReset) { counterReset.forEach(function (entry) { var counter = _this.counters[entry.counter]; counterNames.push(entry.counter); if (!counter) { counter = _this.counters[entry.counter] = []; } counter.push(entry.reset); }); } return counterNames; }; return CounterState; }(); var ROMAN_UPPER = { integers: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1], values: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] }; var ARMENIAN = { integers: [9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], values: ['Ք', 'Փ', 'Ւ', 'Ց', 'Ր', 'Տ', 'Վ', 'Ս', 'Ռ', 'Ջ', 'Պ', 'Չ', 'Ո', 'Շ', 'Ն', 'Յ', 'Մ', 'Ճ', 'Ղ', 'Ձ', 'Հ', 'Կ', 'Ծ', 'Խ', 'Լ', 'Ի', 'Ժ', 'Թ', 'Ը', 'Է', 'Զ', 'Ե', 'Դ', 'Գ', 'Բ', 'Ա'] }; var HEBREW = { integers: [10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], values: ['י׳', 'ט׳', 'ח׳', 'ז׳', 'ו׳', 'ה׳', 'ד׳', 'ג׳', 'ב׳', 'א׳', 'ת', 'ש', 'ר', 'ק', 'צ', 'פ', 'ע', 'ס', 'נ', 'מ', 'ל', 'כ', 'יט', 'יח', 'יז', 'טז', 'טו', 'י', 'ט', 'ח', 'ז', 'ו', 'ה', 'ד', 'ג', 'ב', 'א'] }; var GEORGIAN = { integers: [10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], values: ['ჵ', 'ჰ', 'ჯ', 'ჴ', 'ხ', 'ჭ', 'წ', 'ძ', 'ც', 'ჩ', 'შ', 'ყ', 'ღ', 'ქ', 'ფ', 'ჳ', 'ტ', 'ს', 'რ', 'ჟ', 'პ', 'ო', 'ჲ', 'ნ', 'მ', 'ლ', 'კ', 'ი', 'თ', 'ჱ', 'ზ', 'ვ', 'ე', 'დ', 'გ', 'ბ', 'ა'] }; var createAdditiveCounter = function createAdditiveCounter(value, min, max, symbols, fallback, suffix) { if (value < min || value > max) { return createCounterText(value, fallback, suffix.length > 0); } return symbols.integers.reduce(function (string, integer, index) { while (value >= integer) { value -= integer; string += symbols.values[index]; } return string; }, '') + suffix; }; var createCounterStyleWithSymbolResolver = function createCounterStyleWithSymbolResolver(value, codePointRangeLength, isNumeric, resolver) { var string = ''; do { if (!isNumeric) { value--; } string = resolver(value) + string; value /= codePointRangeLength; } while (value * codePointRangeLength >= codePointRangeLength); return string; }; var createCounterStyleFromRange = function createCounterStyleFromRange(value, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) { var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1; return (value < 0 ? '-' : '') + (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, function (codePoint) { return fromCodePoint(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart); }) + suffix); }; var createCounterStyleFromSymbols = function createCounterStyleFromSymbols(value, symbols, suffix) { if (suffix === void 0) { suffix = '. '; } var codePointRangeLength = symbols.length; return createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, false, function (codePoint) { return symbols[Math.floor(codePoint % codePointRangeLength)]; }) + suffix; }; var CJK_ZEROS = 1 << 0; var CJK_TEN_COEFFICIENTS = 1 << 1; var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2; var CJK_HUNDRED_COEFFICIENTS = 1 << 3; var createCJKCounter = function createCJKCounter(value, numbers, multipliers, negativeSign, suffix, flags) { if (value < -9999 || value > 9999) { return createCounterText(value, LIST_STYLE_TYPE.CJK_DECIMAL, suffix.length > 0); } var tmp = Math.abs(value); var string = suffix; if (tmp === 0) { return numbers[0] + string; } for (var digit = 0; tmp > 0 && digit <= 4; digit++) { var coefficient = tmp % 10; if (coefficient === 0 && contains(flags, CJK_ZEROS) && string !== '') { string = numbers[coefficient] + string; } else if (coefficient > 1 || coefficient === 1 && digit === 0 || coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_COEFFICIENTS) || coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_HIGH_COEFFICIENTS) && value > 100 || coefficient === 1 && digit > 1 && contains(flags, CJK_HUNDRED_COEFFICIENTS)) { string = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : '') + string; } else if (coefficient === 1 && digit > 0) { string = multipliers[digit - 1] + string; } tmp = Math.floor(tmp / 10); } return (value < 0 ? negativeSign : '') + string; }; var CHINESE_INFORMAL_MULTIPLIERS = '十百千萬'; var CHINESE_FORMAL_MULTIPLIERS = '拾佰仟萬'; var JAPANESE_NEGATIVE = 'マイナス'; var KOREAN_NEGATIVE = '마이너스'; var createCounterText = function createCounterText(value, type, appendSuffix) { var defaultSuffix = appendSuffix ? '. ' : ''; var cjkSuffix = appendSuffix ? '、' : ''; var koreanSuffix = appendSuffix ? ', ' : ''; var spaceSuffix = appendSuffix ? ' ' : ''; switch (type) { case LIST_STYLE_TYPE.DISC: return '•' + spaceSuffix; case LIST_STYLE_TYPE.CIRCLE: return '◦' + spaceSuffix; case LIST_STYLE_TYPE.SQUARE: return '◾' + spaceSuffix; case LIST_STYLE_TYPE.DECIMAL_LEADING_ZERO: var string = createCounterStyleFromRange(value, 48, 57, true, defaultSuffix); return string.length < 4 ? "0" + string : string; case LIST_STYLE_TYPE.CJK_DECIMAL: return createCounterStyleFromSymbols(value, '〇一二三四五六七八九', cjkSuffix); case LIST_STYLE_TYPE.LOWER_ROMAN: return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, LIST_STYLE_TYPE.DECIMAL, defaultSuffix).toLowerCase(); case LIST_STYLE_TYPE.UPPER_ROMAN: return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, LIST_STYLE_TYPE.DECIMAL, defaultSuffix); case LIST_STYLE_TYPE.LOWER_GREEK: return createCounterStyleFromRange(value, 945, 969, false, defaultSuffix); case LIST_STYLE_TYPE.LOWER_ALPHA: return createCounterStyleFromRange(value, 97, 122, false, defaultSuffix); case LIST_STYLE_TYPE.UPPER_ALPHA: return createCounterStyleFromRange(value, 65, 90, false, defaultSuffix); case LIST_STYLE_TYPE.ARABIC_INDIC: return createCounterStyleFromRange(value, 1632, 1641, true, defaultSuffix); case LIST_STYLE_TYPE.ARMENIAN: case LIST_STYLE_TYPE.UPPER_ARMENIAN: return createAdditiveCounter(value, 1, 9999, ARMENIAN, LIST_STYLE_TYPE.DECIMAL, defaultSuffix); case LIST_STYLE_TYPE.LOWER_ARMENIAN: return createAdditiveCounter(value, 1, 9999, ARMENIAN, LIST_STYLE_TYPE.DECIMAL, defaultSuffix).toLowerCase(); case LIST_STYLE_TYPE.BENGALI: return createCounterStyleFromRange(value, 2534, 2543, true, defaultSuffix); case LIST_STYLE_TYPE.CAMBODIAN: case LIST_STYLE_TYPE.KHMER: return createCounterStyleFromRange(value, 6112, 6121, true, defaultSuffix); case LIST_STYLE_TYPE.CJK_EARTHLY_BRANCH: return createCounterStyleFromSymbols(value, '子丑寅卯辰巳午未申酉戌亥', cjkSuffix); case LIST_STYLE_TYPE.CJK_HEAVENLY_STEM: return createCounterStyleFromSymbols(value, '甲乙丙丁戊己庚辛壬癸', cjkSuffix); case LIST_STYLE_TYPE.CJK_IDEOGRAPHIC: case LIST_STYLE_TYPE.TRAD_CHINESE_INFORMAL: return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); case LIST_STYLE_TYPE.TRAD_CHINESE_FORMAL: return createCJKCounter(value, '零壹貳參肆伍陸柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); case LIST_STYLE_TYPE.SIMP_CHINESE_INFORMAL: return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); case LIST_STYLE_TYPE.SIMP_CHINESE_FORMAL: return createCJKCounter(value, '零壹贰叁肆伍陆柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); case LIST_STYLE_TYPE.JAPANESE_INFORMAL: return createCJKCounter(value, '〇一二三四五六七八九', '十百千万', JAPANESE_NEGATIVE, cjkSuffix, 0); case LIST_STYLE_TYPE.JAPANESE_FORMAL: return createCJKCounter(value, '零壱弐参四伍六七八九', '拾百千万', JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS); case LIST_STYLE_TYPE.KOREAN_HANGUL_FORMAL: return createCJKCounter(value, '영일이삼사오육칠팔구', '십백천만', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS); case LIST_STYLE_TYPE.KOREAN_HANJA_INFORMAL: return createCJKCounter(value, '零一二三四五六七八九', '十百千萬', KOREAN_NEGATIVE, koreanSuffix, 0); case LIST_STYLE_TYPE.KOREAN_HANJA_FORMAL: return createCJKCounter(value, '零壹貳參四五六七八九', '拾百千', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS); case LIST_STYLE_TYPE.DEVANAGARI: return createCounterStyleFromRange(value, 0x966, 0x96f, true, defaultSuffix); case LIST_STYLE_TYPE.GEORGIAN: return createAdditiveCounter(value, 1, 19999, GEORGIAN, LIST_STYLE_TYPE.DECIMAL, defaultSuffix); case LIST_STYLE_TYPE.GUJARATI: return createCounterStyleFromRange(value, 0xae6, 0xaef, true, defaultSuffix); case LIST_STYLE_TYPE.GURMUKHI: return createCounterStyleFromRange(value, 0xa66, 0xa6f, true, defaultSuffix); case LIST_STYLE_TYPE.HEBREW: return createAdditiveCounter(value, 1, 10999, HEBREW, LIST_STYLE_TYPE.DECIMAL, defaultSuffix); case LIST_STYLE_TYPE.HIRAGANA: return createCounterStyleFromSymbols(value, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん'); case LIST_STYLE_TYPE.HIRAGANA_IROHA: return createCounterStyleFromSymbols(value, 'いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす'); case LIST_STYLE_TYPE.KANNADA: return createCounterStyleFromRange(value, 0xce6, 0xcef, true, defaultSuffix); case LIST_STYLE_TYPE.KATAKANA: return createCounterStyleFromSymbols(value, 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン', cjkSuffix); case LIST_STYLE_TYPE.KATAKANA_IROHA: return createCounterStyleFromSymbols(value, 'イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス', cjkSuffix); case LIST_STYLE_TYPE.LAO: return createCounterStyleFromRange(value, 0xed0, 0xed9, true, defaultSuffix); case LIST_STYLE_TYPE.MONGOLIAN: return createCounterStyleFromRange(value, 0x1810, 0x1819, true, defaultSuffix); case LIST_STYLE_TYPE.MYANMAR: return createCounterStyleFromRange(value, 0x1040, 0x1049, true, defaultSuffix); case LIST_STYLE_TYPE.ORIYA: return createCounterStyleFromRange(value, 0xb66, 0xb6f, true, defaultSuffix); case LIST_STYLE_TYPE.PERSIAN: return createCounterStyleFromRange(value, 0x6f0, 0x6f9, true, defaultSuffix); case LIST_STYLE_TYPE.TAMIL: return createCounterStyleFromRange(value, 0xbe6, 0xbef, true, defaultSuffix); case LIST_STYLE_TYPE.TELUGU: return createCounterStyleFromRange(value, 0xc66, 0xc6f, true, defaultSuffix); case LIST_STYLE_TYPE.THAI: return createCounterStyleFromRange(value, 0xe50, 0xe59, true, defaultSuffix); case LIST_STYLE_TYPE.TIBETAN: return createCounterStyleFromRange(value, 0xf20, 0xf29, true, defaultSuffix); case LIST_STYLE_TYPE.DECIMAL: default: return createCounterStyleFromRange(value, 48, 57, true, defaultSuffix); } }; var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore'; var DocumentCloner = /** @class */ function () { function DocumentCloner(element, options) { this.options = options; this.scrolledElements = []; this.referenceElement = element; this.counters = new CounterState(); this.quoteDepth = 0; if (!element.ownerDocument) { throw new Error('Cloned element does not have an owner document'); } this.documentElement = this.cloneNode(element.ownerDocument.documentElement); } DocumentCloner.prototype.toIFrame = function (ownerDocument, windowSize) { var _this = this; var iframe = createIFrameContainer(ownerDocument, windowSize); if (!iframe.contentWindow) { return Promise.reject("Unable to find iframe window"); } var scrollX = ownerDocument.defaultView.pageXOffset; var scrollY = ownerDocument.defaultView.pageYOffset; var cloneWindow = iframe.contentWindow; var documentClone = cloneWindow.document; /* Chrome doesn't detect relative background-images assigned in inline